blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
34dc80efcc850e9f8ce93ad1733b20305bc4f91b
21,260,088,116,436
5a14db9c02a75039f1c2e08c802273feebfb0eae
/src/main/java/org/r/idea/plugin/generator/ktimpl/parser/KtInterfaceParser.java
2f8d7fac41b8d6cac4cf089ee52a3ca44afb4629
[]
no_license
Casper-Mars/idea-plugin-api-generator
https://github.com/Casper-Mars/idea-plugin-api-generator
a6e8e6464c62ecedc7d4ee333439782a10b668a9
dfcee38649d752e5c467eba5161ed1383974c2cb
refs/heads/master
2020-06-03T00:45:11.024000
2019-10-12T04:00:21
2019-10-12T04:00:21
191,364,054
8
1
null
null
null
null
null
null
null
null
null
null
null
null
null
//package org.r.idea.plugin.generator.ktimpl.parser; // //import com.intellij.psi.PsiElement; //import org.jetbrains.kotlin.psi.*; //import org.r.idea.plugin.generator.core.exceptions.ClassNotFoundException; //import org.r.idea.plugin.generator.core.nodes.Node; //import org.r.idea.plugin.generator.core.parser.Parser; //import org.r.idea.plugin.generator.impl.nodes.InterfaceNode; //import org.r.idea.plugin.generator.ktimpl.Utils; //import org.r.idea.plugin.generator.utils.CollectionUtils; // //import java.util.ArrayList; //import java.util.List; // ///** // * @author casper // */ //public class KtInterfaceParser implements Parser { // /** // * 根据class对象转化出信息 // * // * @param target class对象 // * @return // * @throws ClassNotFoundException // */ // @Override // public Node parse(PsiElement target) throws ClassNotFoundException { // // if (target == null) { // throw new ClassNotFoundException("需要parse的对象不能为空"); // } // if (!(target instanceof KtClass)) { // throw new ClassNotFoundException("需要parse的对象不是kotlin class"); // } // // KtClass target0 = (KtClass)target; // System.out.println(target0.getFqName()); // // InterfaceNode interfaceNode = new InterfaceNode(); // /*设置描述*/ // interfaceNode.setDesc(Utils.getDocCommentDesc(target0.getDocComment())); // interfaceNode.setName(target0.getName()); // interfaceNode.setBaseUrl(getBaseUrl(target0)); // /*处理方法*/ // List<Node> methods = new ArrayList<>(); // // // // // // return null; // } // // // private String getBaseUrl(KtClass target) { // List<KtAnnotationEntry> annotationEntries = target.getAnnotationEntries(); // KtAnnotationEntry req = Utils // .findAnnotationByName("RequestMapping", annotationEntries); // if(req == null){ // return ""; // } // List<? extends ValueArgument> valueArguments = req.getValueArguments(); // if(CollectionUtils.isEmpty(valueArguments)){ // return ""; // } // ValueArgument argument = valueArguments.get(0); // return argument.getArgumentExpression().getText(); // } // // // // // // // // // // // // // // //}
UTF-8
Java
2,347
java
KtInterfaceParser.java
Java
[ { "context": "st;\n//import java.util.List;\n//\n///**\n// * @author casper\n// */\n//public class KtInterfaceParser implements", "end": 579, "score": 0.9995448589324951, "start": 573, "tag": "USERNAME", "value": "casper" } ]
null
[]
//package org.r.idea.plugin.generator.ktimpl.parser; // //import com.intellij.psi.PsiElement; //import org.jetbrains.kotlin.psi.*; //import org.r.idea.plugin.generator.core.exceptions.ClassNotFoundException; //import org.r.idea.plugin.generator.core.nodes.Node; //import org.r.idea.plugin.generator.core.parser.Parser; //import org.r.idea.plugin.generator.impl.nodes.InterfaceNode; //import org.r.idea.plugin.generator.ktimpl.Utils; //import org.r.idea.plugin.generator.utils.CollectionUtils; // //import java.util.ArrayList; //import java.util.List; // ///** // * @author casper // */ //public class KtInterfaceParser implements Parser { // /** // * 根据class对象转化出信息 // * // * @param target class对象 // * @return // * @throws ClassNotFoundException // */ // @Override // public Node parse(PsiElement target) throws ClassNotFoundException { // // if (target == null) { // throw new ClassNotFoundException("需要parse的对象不能为空"); // } // if (!(target instanceof KtClass)) { // throw new ClassNotFoundException("需要parse的对象不是kotlin class"); // } // // KtClass target0 = (KtClass)target; // System.out.println(target0.getFqName()); // // InterfaceNode interfaceNode = new InterfaceNode(); // /*设置描述*/ // interfaceNode.setDesc(Utils.getDocCommentDesc(target0.getDocComment())); // interfaceNode.setName(target0.getName()); // interfaceNode.setBaseUrl(getBaseUrl(target0)); // /*处理方法*/ // List<Node> methods = new ArrayList<>(); // // // // // // return null; // } // // // private String getBaseUrl(KtClass target) { // List<KtAnnotationEntry> annotationEntries = target.getAnnotationEntries(); // KtAnnotationEntry req = Utils // .findAnnotationByName("RequestMapping", annotationEntries); // if(req == null){ // return ""; // } // List<? extends ValueArgument> valueArguments = req.getValueArguments(); // if(CollectionUtils.isEmpty(valueArguments)){ // return ""; // } // ValueArgument argument = valueArguments.get(0); // return argument.getArgumentExpression().getText(); // } // // // // // // // // // // // // // // //}
2,347
0.619675
0.61704
83
26.433735
25.791187
84
false
false
0
0
0
0
0
0
0.349398
false
false
14
e72622f5fdcc61a4822944c7575d9723b88a1c22
21,655,225,125,202
b4e0af8545466bbd0d2fb53ef6a5cf68e4458863
/src/main/java/nirvana/cash/loan/privilege/service/impl/UserServiceImpl.java
735af63aa45eb259251930a538512cd42e7d0ce1
[]
no_license
zouwenhai/weipin-cash-loan-privilege
https://github.com/zouwenhai/weipin-cash-loan-privilege
5741e56b3adaa2ef1203299ed77ca73630af6431
673234cdaa2bf1dba20c15d818a7124f472d1a9c
refs/heads/master
2022-03-01T11:56:53.544000
2019-12-13T02:33:30
2019-12-13T02:33:30
228,373,781
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package nirvana.cash.loan.privilege.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import nirvana.cash.loan.privilege.common.enums.RoleEnum; import nirvana.cash.loan.privilege.fegin.facade.*; import nirvana.cash.loan.privilege.service.base.impl.BaseService; import nirvana.cash.loan.privilege.common.util.MD5Utils; import nirvana.cash.loan.privilege.common.util.ResResult; import nirvana.cash.loan.privilege.fegin.FeginCollectionApi; import nirvana.cash.loan.privilege.fegin.FeginRiskApi; import nirvana.cash.loan.privilege.fegin.NewResponseUtil; import nirvana.cash.loan.privilege.service.LogoutUserService; import nirvana.cash.loan.privilege.dao.RoleMapper; import nirvana.cash.loan.privilege.dao.UserMapper; import nirvana.cash.loan.privilege.dao.UserRoleMapper; import nirvana.cash.loan.privilege.domain.User; import nirvana.cash.loan.privilege.domain.UserRole; import nirvana.cash.loan.privilege.domain.UserWithRole; import nirvana.cash.loan.privilege.service.UserRoleService; import nirvana.cash.loan.privilege.service.UserService; import nirvana.cash.loan.privilege.common.exception.BizException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import tk.mybatis.mapper.entity.Example; import java.util.*; @Service public class UserServiceImpl extends BaseService<User> implements UserService { public static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserMapper userMapper; @Autowired private UserRoleMapper userRoleMapper; @Autowired private UserRoleService userRoleService; @Autowired private RoleMapper roleMapper; @Autowired private FeginCollectionApi feginCollectionApi; @Autowired private FeginRiskApi feginRiskApi; @Autowired private LogoutUserService logoutUserService; @Override public User findByName(String userName) { Example example = new Example(User.class); example.createCriteria().andCondition("lower(username)=", userName.toLowerCase()); return this.selectOneByExample(example); } @Override public List<User> findUserWithDept(User user) { if (StringUtils.isNotBlank(user.getUsername())) { user.setUsername(user.getUsername().toLowerCase()); } return this.userMapper.findUserWithDept(user); } @Override @Transactional public ResResult addUser(User user, List<Long> roles, User loginUser) { if (StringUtils.isBlank(user.getDeptId())) { user.setViewRange(0); } else { user.setViewRange(1); } /* user.setUserId(this.getSequence(User.SEQ)) * 数据库住建设为自增 * */ ; user.setCrateTime(new Date()); user.setTheme(User.DEFAULT_THEME); user.setAvatar(User.DEFAULT_AVATAR); user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword())); user.setIsDelete(0); user.setIsSeperate(0); user.setIsSeat(0); user.setExtNumber("0"); user.setOrderTop(0); this.save(user); setUserRoles(user, roles); //子系统用户同步 List<Long> roleIds = roles; List<String> roleCodeList = roleMapper.findRoleCodeListByRoleIds(roleIds); //催收用户 List<String> collRoleCodeList = filterRoleCodeList(roleCodeList, "coll"); if (collRoleCodeList != null && collRoleCodeList.size() > 0) { if (collRoleCodeList.size() > 1) { throw BizException.newInstance("添加催收用户失败:一个催收登录帐号只能拥有一个催收角色"); } UserAddApiFacade facade = new UserAddApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleCodeList(collRoleCodeList); facade.setCreateUser(loginUser.getUsername()); facade.setUpdateUser(loginUser.getUsername()); try { NewResponseUtil apiRes = feginCollectionApi.addUser(facade); logger.info("添加催收用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } catch (Exception ex) { logger.error("添加催收用户失败|程序异常:{}", ex); } } //风控 List<String> riskRoleCodeList = filterRoleCodeList(roleCodeList, "risk"); if (riskRoleCodeList != null && riskRoleCodeList.size() > 0) { if (riskRoleCodeList.size() > 1) { throw BizException.newInstance("添加风控用户失败:一个风控登录帐号只能拥有一个风控角色"); } RiskUserAddApiFacade facade = new RiskUserAddApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleType(riskRoleCodeList.get(0)); facade.setUserStatus("1"); try { NewResponseUtil apiRes = feginRiskApi.addOrderUser(facade); logger.info("添加风控用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } catch (Exception ex) { logger.error("添加风控用户失败|程序异常:{}", ex); } } return ResResult.success(); } private void setUserRoles(User user, List<Long> roles) { for (Long roleId : roles) { UserRole ur = new UserRole(); ur.setUserId(user.getUserId()); ur.setRoleId(roleId); this.userRoleMapper.insert(ur); } } @Override @Transactional public void updateUser(User user, List<Long> roles, Long loginUserId, String username) { if (StringUtils.isBlank(user.getDeptId())) { user.setViewRange(0); } else { user.setViewRange(1); } List<String> oldRoleCodeList = userRoleService.findRoleCodeListByUserId(user.getUserId().intValue()); List<String> newRoleCodeList = roleMapper.findRoleCodeListByRoleIds(roles); User oldUser = this.userMapper.selectByPrimaryKey(user.getUserId()); user.setCrateTime(oldUser.getCrateTime()); user.setPassword(oldUser.getPassword()); user.setUsername(oldUser.getUsername()); user.setModifyTime(new Date()); user.setIsDelete(0); user.setIsSeperate(oldUser.getIsSeperate()); user.setIsSeat(oldUser.getIsSeat()); user.setExtNumber(oldUser.getExtNumber()); user.setOrderTop(oldUser.getOrderTop()); this.updateAll(user); Example example = new Example(UserRole.class); example.createCriteria().andCondition("user_id=", user.getUserId()); this.userRoleMapper.deleteByExample(example); setUserRoles(user, roles); if (user.getUserId().longValue() != loginUserId) { logoutUserService.logoutUser(user.getUserId()); } //子系统用户同步 //催收用户 List<String> oldCollRoleCodeList = filterRoleCodeList(oldRoleCodeList, "coll"); List<String> newCollRoleCodeList = filterRoleCodeList(newRoleCodeList, "coll"); if (oldCollRoleCodeList.size() > 0 || newCollRoleCodeList.size() > 0) { if (newCollRoleCodeList.size() > 1) { throw BizException.newInstance("修改催收用户失败:一个催收登录帐号只能拥有一个催收角色"); } UserUpdateApiFacade facade = new UserUpdateApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setUpdateUser(username); if (newCollRoleCodeList.size() == 0) { facade.setStatus(2);//删除 facade.setRoleCodeList(oldCollRoleCodeList); } else { facade.setStatus(1);//修改 facade.setRoleCodeList(newCollRoleCodeList); } try { NewResponseUtil apiRes = feginCollectionApi.updateUser(facade); logger.info("修改催收用户成功|响应数据:{}", JSON.toJSONString(apiRes)); } catch (Exception ex) { logger.error("修改催收用户失败|程序异常:{}", ex); } } //风控 List<String> oldRiskRoleCodes = filterRoleCodeList(oldRoleCodeList, "risk"); List<String> newRiskRoleCodes = filterRoleCodeList(newRoleCodeList, "risk"); RiskUserUpdateApiFacade facade = new RiskUserUpdateApiFacade(); facade.setMobile(user.getMobile()); facade.setLoginName(user.getUsername()); facade.setUserName(user.getName()); //撤销用户风控角色 if (!CollectionUtils.isEmpty(oldRiskRoleCodes) && CollectionUtils.isEmpty(newRiskRoleCodes)) { //删除风控用户 logger.info("删除风控用户:{}", user.getUsername()); facade.setRoleType(oldRiskRoleCodes.get(0)); facade.setUserStatus("0"); } //设置用户风控角色,但角色数量大于1,不允许 if (!CollectionUtils.isEmpty(newRiskRoleCodes) && newRiskRoleCodes.size() > 1) { throw BizException.newInstance("修改风控用户失败:一个风控登录帐号只能拥有一个风控角色"); } //设置用户风控角色,且风控角色数量等于1 if (!CollectionUtils.isEmpty(newRiskRoleCodes)) { //更新风控用户角色 String newRoleCode = newRiskRoleCodes.get(0); logger.info("更新风控用户:{} 的角色为:{}", user.getUsername(), newRoleCode); facade.setRoleType(newRoleCode); facade.setUserStatus("1"); try { logger.info("修改风控用户:" + JSONObject.toJSONString(facade)); NewResponseUtil result = feginRiskApi.updateOrderUser(facade); if (!NewResponseUtil.SUCCESS.equals(result.getCode())) { throw BizException.newInstance(result.getDesc()); } } catch (Exception e) { logger.error("修改风控用户失败:{}", e.getMessage()); } } } @Override @Transactional public void deleteUser(Integer userId) { User user = userMapper.selectByPrimaryKey(Long.valueOf(userId)); List<String> roleCodeList = userRoleService.findRoleCodeListByUserId(userId); user.setIsDelete(1); this.updateNotNull(user); this.userRoleService.deleteUserRolesByUserId(userId.toString()); logoutUserService.logoutUser(user.getUserId()); //子系统用户同步 //催收用户 List<String> collRoleCodeList = filterRoleCodeList(roleCodeList, "coll"); if (collRoleCodeList != null && collRoleCodeList.size() > 0) { UserUpdateApiFacade facade = new UserUpdateApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleCodeList(collRoleCodeList); facade.setStatus(2); NewResponseUtil apiRes = feginCollectionApi.updateUser(facade); logger.info("删除催收用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } //风控 List<String> riskRoleCodeList = filterRoleCodeList(roleCodeList, "risk"); if (riskRoleCodeList != null && riskRoleCodeList.size() > 0) { RiskUserUpdateApiFacade facade = new RiskUserUpdateApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleType(riskRoleCodeList.get(0)); facade.setUserStatus("0");//删除 NewResponseUtil apiRes = feginRiskApi.updateOrderUser(facade); logger.info("删除风控用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } } @Override @Transactional public void updateLoginTime(String userName) { Example example = new Example(User.class); example.createCriteria().andCondition("lower(username)=", userName.toLowerCase()); User user = new User(); user.setLastLoginTime(new Date()); this.userMapper.updateByExampleSelective(user, example); } @Override @Transactional public void updatePassword(String password, Long userId) { User user = this.userMapper.selectByPrimaryKey(userId); String newPassword = MD5Utils.encrypt(user.getUsername().toLowerCase(), password); User newUser = new User(); newUser.setUserId(userId); newUser.setPassword(newPassword); this.userMapper.updateByPrimaryKeySelective(newUser); } @Override public UserWithRole findById(Long userId) { List<UserWithRole> list = this.userMapper.findUserWithRole(userId); List<Long> roleList = new ArrayList<>(); for (UserWithRole uwr : list) { roleList.add(uwr.getRoleId()); } if (list.size() == 0) { return null; } UserWithRole userWithRole = list.get(0); userWithRole.setRoleIds(roleList); return userWithRole; } @Override public String findUserRoldIds(Integer userId) { return this.userMapper.findUserRoldIds(userId); } @Override public String findUserRoldCodes(String roleIds) { List<Long> roleIdList = new ArrayList<>(); Arrays.asList(roleIds.split(",")).forEach(t -> { roleIdList.add(Long.valueOf(t)); }); List<String> roleCodeList = roleMapper.findRoleCodeListByRoleIds(roleIdList); return String.join(",", roleCodeList); } public List<String> filterRoleCodeList(List<String> roleCodeList, String syncService) { List<String> collRoleCodeList = new ArrayList<>(); if (roleCodeList != null) { for (String roleCode : roleCodeList) { RoleEnum roleEnum = RoleEnum.getPaymentStatusEnumByValue(roleCode); String service = roleEnum == null ? null : roleEnum.getService(); if (service != null && service.equals(syncService)) { collRoleCodeList.add(roleCode); } } } return collRoleCodeList; } @Override public List<User> findByIds(Set<Long> userIdSet) { Example example = new Example(User.class); example.createCriteria().andIn("userId", userIdSet); return userMapper.selectByExample(example); } @Override public List<User> findAllLikeDeptId(Long deptId) { Example example = new Example(User.class); Example.Criteria criteria = example.createCriteria() .andEqualTo("isDelete", 0); if (deptId != null) { criteria.andLike("deptId", "%" + deptId + "%"); } return userMapper.selectByExample(example); } @Override public List<User> findUserById(List<Long> userIdList, Integer isSeperate) { return userMapper.getUserById(userIdList, isSeperate); } @Override public User getUserById(Long userId) { return userMapper.selectByPrimaryKey(userId); } @Override public int isDivideOrder(IsDivideOrderFacade isDivideOrderFacade) { return userMapper.updateDivideOrder(isDivideOrderFacade); } @Override public List<User> getAuditUser(Integer isSeperate) { return userMapper.getAuditUser(isSeperate); } @Override public void isOpenSeat(IsOpenSeatFacade isOpenSeatFacade) { userMapper.updateSeat(isOpenSeatFacade); } @Override public void addExtNumber(ExtNumberFacade extNumberFacade) { userMapper.updateExtNumber(extNumberFacade); } @Override public List<User> getReviewUser(Integer isSeperate) { return userMapper.getReviewUser(isSeperate); } @Override public void updateOrderTop(OrderTopFacade orderTopFacade) { userMapper.updateOrderTop(orderTopFacade); } }
UTF-8
Java
16,621
java
UserServiceImpl.java
Java
[ { "context": "oldUser.getCrateTime());\n user.setPassword(oldUser.getPassword());\n user.setUsername(oldUser.", "end": 6379, "score": 0.8445415496826172, "start": 6372, "tag": "PASSWORD", "value": "oldUser" }, { "context": "getCrateTime());\n user.setPassword(old...
null
[]
package nirvana.cash.loan.privilege.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import nirvana.cash.loan.privilege.common.enums.RoleEnum; import nirvana.cash.loan.privilege.fegin.facade.*; import nirvana.cash.loan.privilege.service.base.impl.BaseService; import nirvana.cash.loan.privilege.common.util.MD5Utils; import nirvana.cash.loan.privilege.common.util.ResResult; import nirvana.cash.loan.privilege.fegin.FeginCollectionApi; import nirvana.cash.loan.privilege.fegin.FeginRiskApi; import nirvana.cash.loan.privilege.fegin.NewResponseUtil; import nirvana.cash.loan.privilege.service.LogoutUserService; import nirvana.cash.loan.privilege.dao.RoleMapper; import nirvana.cash.loan.privilege.dao.UserMapper; import nirvana.cash.loan.privilege.dao.UserRoleMapper; import nirvana.cash.loan.privilege.domain.User; import nirvana.cash.loan.privilege.domain.UserRole; import nirvana.cash.loan.privilege.domain.UserWithRole; import nirvana.cash.loan.privilege.service.UserRoleService; import nirvana.cash.loan.privilege.service.UserService; import nirvana.cash.loan.privilege.common.exception.BizException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import tk.mybatis.mapper.entity.Example; import java.util.*; @Service public class UserServiceImpl extends BaseService<User> implements UserService { public static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserMapper userMapper; @Autowired private UserRoleMapper userRoleMapper; @Autowired private UserRoleService userRoleService; @Autowired private RoleMapper roleMapper; @Autowired private FeginCollectionApi feginCollectionApi; @Autowired private FeginRiskApi feginRiskApi; @Autowired private LogoutUserService logoutUserService; @Override public User findByName(String userName) { Example example = new Example(User.class); example.createCriteria().andCondition("lower(username)=", userName.toLowerCase()); return this.selectOneByExample(example); } @Override public List<User> findUserWithDept(User user) { if (StringUtils.isNotBlank(user.getUsername())) { user.setUsername(user.getUsername().toLowerCase()); } return this.userMapper.findUserWithDept(user); } @Override @Transactional public ResResult addUser(User user, List<Long> roles, User loginUser) { if (StringUtils.isBlank(user.getDeptId())) { user.setViewRange(0); } else { user.setViewRange(1); } /* user.setUserId(this.getSequence(User.SEQ)) * 数据库住建设为自增 * */ ; user.setCrateTime(new Date()); user.setTheme(User.DEFAULT_THEME); user.setAvatar(User.DEFAULT_AVATAR); user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword())); user.setIsDelete(0); user.setIsSeperate(0); user.setIsSeat(0); user.setExtNumber("0"); user.setOrderTop(0); this.save(user); setUserRoles(user, roles); //子系统用户同步 List<Long> roleIds = roles; List<String> roleCodeList = roleMapper.findRoleCodeListByRoleIds(roleIds); //催收用户 List<String> collRoleCodeList = filterRoleCodeList(roleCodeList, "coll"); if (collRoleCodeList != null && collRoleCodeList.size() > 0) { if (collRoleCodeList.size() > 1) { throw BizException.newInstance("添加催收用户失败:一个催收登录帐号只能拥有一个催收角色"); } UserAddApiFacade facade = new UserAddApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleCodeList(collRoleCodeList); facade.setCreateUser(loginUser.getUsername()); facade.setUpdateUser(loginUser.getUsername()); try { NewResponseUtil apiRes = feginCollectionApi.addUser(facade); logger.info("添加催收用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } catch (Exception ex) { logger.error("添加催收用户失败|程序异常:{}", ex); } } //风控 List<String> riskRoleCodeList = filterRoleCodeList(roleCodeList, "risk"); if (riskRoleCodeList != null && riskRoleCodeList.size() > 0) { if (riskRoleCodeList.size() > 1) { throw BizException.newInstance("添加风控用户失败:一个风控登录帐号只能拥有一个风控角色"); } RiskUserAddApiFacade facade = new RiskUserAddApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleType(riskRoleCodeList.get(0)); facade.setUserStatus("1"); try { NewResponseUtil apiRes = feginRiskApi.addOrderUser(facade); logger.info("添加风控用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } catch (Exception ex) { logger.error("添加风控用户失败|程序异常:{}", ex); } } return ResResult.success(); } private void setUserRoles(User user, List<Long> roles) { for (Long roleId : roles) { UserRole ur = new UserRole(); ur.setUserId(user.getUserId()); ur.setRoleId(roleId); this.userRoleMapper.insert(ur); } } @Override @Transactional public void updateUser(User user, List<Long> roles, Long loginUserId, String username) { if (StringUtils.isBlank(user.getDeptId())) { user.setViewRange(0); } else { user.setViewRange(1); } List<String> oldRoleCodeList = userRoleService.findRoleCodeListByUserId(user.getUserId().intValue()); List<String> newRoleCodeList = roleMapper.findRoleCodeListByRoleIds(roles); User oldUser = this.userMapper.selectByPrimaryKey(user.getUserId()); user.setCrateTime(oldUser.getCrateTime()); user.setPassword(<PASSWORD>.<PASSWORD>()); user.setUsername(oldUser.getUsername()); user.setModifyTime(new Date()); user.setIsDelete(0); user.setIsSeperate(oldUser.getIsSeperate()); user.setIsSeat(oldUser.getIsSeat()); user.setExtNumber(oldUser.getExtNumber()); user.setOrderTop(oldUser.getOrderTop()); this.updateAll(user); Example example = new Example(UserRole.class); example.createCriteria().andCondition("user_id=", user.getUserId()); this.userRoleMapper.deleteByExample(example); setUserRoles(user, roles); if (user.getUserId().longValue() != loginUserId) { logoutUserService.logoutUser(user.getUserId()); } //子系统用户同步 //催收用户 List<String> oldCollRoleCodeList = filterRoleCodeList(oldRoleCodeList, "coll"); List<String> newCollRoleCodeList = filterRoleCodeList(newRoleCodeList, "coll"); if (oldCollRoleCodeList.size() > 0 || newCollRoleCodeList.size() > 0) { if (newCollRoleCodeList.size() > 1) { throw BizException.newInstance("修改催收用户失败:一个催收登录帐号只能拥有一个催收角色"); } UserUpdateApiFacade facade = new UserUpdateApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setUpdateUser(username); if (newCollRoleCodeList.size() == 0) { facade.setStatus(2);//删除 facade.setRoleCodeList(oldCollRoleCodeList); } else { facade.setStatus(1);//修改 facade.setRoleCodeList(newCollRoleCodeList); } try { NewResponseUtil apiRes = feginCollectionApi.updateUser(facade); logger.info("修改催收用户成功|响应数据:{}", JSON.toJSONString(apiRes)); } catch (Exception ex) { logger.error("修改催收用户失败|程序异常:{}", ex); } } //风控 List<String> oldRiskRoleCodes = filterRoleCodeList(oldRoleCodeList, "risk"); List<String> newRiskRoleCodes = filterRoleCodeList(newRoleCodeList, "risk"); RiskUserUpdateApiFacade facade = new RiskUserUpdateApiFacade(); facade.setMobile(user.getMobile()); facade.setLoginName(user.getUsername()); facade.setUserName(user.getName()); //撤销用户风控角色 if (!CollectionUtils.isEmpty(oldRiskRoleCodes) && CollectionUtils.isEmpty(newRiskRoleCodes)) { //删除风控用户 logger.info("删除风控用户:{}", user.getUsername()); facade.setRoleType(oldRiskRoleCodes.get(0)); facade.setUserStatus("0"); } //设置用户风控角色,但角色数量大于1,不允许 if (!CollectionUtils.isEmpty(newRiskRoleCodes) && newRiskRoleCodes.size() > 1) { throw BizException.newInstance("修改风控用户失败:一个风控登录帐号只能拥有一个风控角色"); } //设置用户风控角色,且风控角色数量等于1 if (!CollectionUtils.isEmpty(newRiskRoleCodes)) { //更新风控用户角色 String newRoleCode = newRiskRoleCodes.get(0); logger.info("更新风控用户:{} 的角色为:{}", user.getUsername(), newRoleCode); facade.setRoleType(newRoleCode); facade.setUserStatus("1"); try { logger.info("修改风控用户:" + JSONObject.toJSONString(facade)); NewResponseUtil result = feginRiskApi.updateOrderUser(facade); if (!NewResponseUtil.SUCCESS.equals(result.getCode())) { throw BizException.newInstance(result.getDesc()); } } catch (Exception e) { logger.error("修改风控用户失败:{}", e.getMessage()); } } } @Override @Transactional public void deleteUser(Integer userId) { User user = userMapper.selectByPrimaryKey(Long.valueOf(userId)); List<String> roleCodeList = userRoleService.findRoleCodeListByUserId(userId); user.setIsDelete(1); this.updateNotNull(user); this.userRoleService.deleteUserRolesByUserId(userId.toString()); logoutUserService.logoutUser(user.getUserId()); //子系统用户同步 //催收用户 List<String> collRoleCodeList = filterRoleCodeList(roleCodeList, "coll"); if (collRoleCodeList != null && collRoleCodeList.size() > 0) { UserUpdateApiFacade facade = new UserUpdateApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleCodeList(collRoleCodeList); facade.setStatus(2); NewResponseUtil apiRes = feginCollectionApi.updateUser(facade); logger.info("删除催收用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } //风控 List<String> riskRoleCodeList = filterRoleCodeList(roleCodeList, "risk"); if (riskRoleCodeList != null && riskRoleCodeList.size() > 0) { RiskUserUpdateApiFacade facade = new RiskUserUpdateApiFacade(); facade.setUserName(user.getName()); facade.setLoginName(user.getUsername()); facade.setMobile(user.getMobile()); facade.setRoleType(riskRoleCodeList.get(0)); facade.setUserStatus("0");//删除 NewResponseUtil apiRes = feginRiskApi.updateOrderUser(facade); logger.info("删除风控用户失败|响应数据:{}", JSON.toJSONString(apiRes)); } } @Override @Transactional public void updateLoginTime(String userName) { Example example = new Example(User.class); example.createCriteria().andCondition("lower(username)=", userName.toLowerCase()); User user = new User(); user.setLastLoginTime(new Date()); this.userMapper.updateByExampleSelective(user, example); } @Override @Transactional public void updatePassword(String password, Long userId) { User user = this.userMapper.selectByPrimaryKey(userId); String newPassword = MD5Utils.encrypt(user.getUsername().toLowerCase(), password); User newUser = new User(); newUser.setUserId(userId); newUser.setPassword(<PASSWORD>); this.userMapper.updateByPrimaryKeySelective(newUser); } @Override public UserWithRole findById(Long userId) { List<UserWithRole> list = this.userMapper.findUserWithRole(userId); List<Long> roleList = new ArrayList<>(); for (UserWithRole uwr : list) { roleList.add(uwr.getRoleId()); } if (list.size() == 0) { return null; } UserWithRole userWithRole = list.get(0); userWithRole.setRoleIds(roleList); return userWithRole; } @Override public String findUserRoldIds(Integer userId) { return this.userMapper.findUserRoldIds(userId); } @Override public String findUserRoldCodes(String roleIds) { List<Long> roleIdList = new ArrayList<>(); Arrays.asList(roleIds.split(",")).forEach(t -> { roleIdList.add(Long.valueOf(t)); }); List<String> roleCodeList = roleMapper.findRoleCodeListByRoleIds(roleIdList); return String.join(",", roleCodeList); } public List<String> filterRoleCodeList(List<String> roleCodeList, String syncService) { List<String> collRoleCodeList = new ArrayList<>(); if (roleCodeList != null) { for (String roleCode : roleCodeList) { RoleEnum roleEnum = RoleEnum.getPaymentStatusEnumByValue(roleCode); String service = roleEnum == null ? null : roleEnum.getService(); if (service != null && service.equals(syncService)) { collRoleCodeList.add(roleCode); } } } return collRoleCodeList; } @Override public List<User> findByIds(Set<Long> userIdSet) { Example example = new Example(User.class); example.createCriteria().andIn("userId", userIdSet); return userMapper.selectByExample(example); } @Override public List<User> findAllLikeDeptId(Long deptId) { Example example = new Example(User.class); Example.Criteria criteria = example.createCriteria() .andEqualTo("isDelete", 0); if (deptId != null) { criteria.andLike("deptId", "%" + deptId + "%"); } return userMapper.selectByExample(example); } @Override public List<User> findUserById(List<Long> userIdList, Integer isSeperate) { return userMapper.getUserById(userIdList, isSeperate); } @Override public User getUserById(Long userId) { return userMapper.selectByPrimaryKey(userId); } @Override public int isDivideOrder(IsDivideOrderFacade isDivideOrderFacade) { return userMapper.updateDivideOrder(isDivideOrderFacade); } @Override public List<User> getAuditUser(Integer isSeperate) { return userMapper.getAuditUser(isSeperate); } @Override public void isOpenSeat(IsOpenSeatFacade isOpenSeatFacade) { userMapper.updateSeat(isOpenSeatFacade); } @Override public void addExtNumber(ExtNumberFacade extNumberFacade) { userMapper.updateExtNumber(extNumberFacade); } @Override public List<User> getReviewUser(Integer isSeperate) { return userMapper.getReviewUser(isSeperate); } @Override public void updateOrderTop(OrderTopFacade orderTopFacade) { userMapper.updateOrderTop(orderTopFacade); } }
16,622
0.645866
0.643167
406
38.23399
26.085724
109
false
false
0
0
0
0
0
0
0.64532
false
false
14
53bfd334299144bc914cb52efe53236b6ed74fcb
32,736,240,755,180
edea52735f46a3cdb0a8c396c8bf324720f58777
/2013-OOProgrammingWithJava-PART1/week3-045.Greatest/src/Greatest.java
9a4a10cb364d29371e0fd159b99d165017a4a892
[]
no_license
AndreiCatinas/mooc.fi
https://github.com/AndreiCatinas/mooc.fi
78aa600ede32eb301c145a9a75b99240eeea0113
8ffb3c4b5aeeff26755ce0729b8951f3786ade33
refs/heads/master
2021-07-08T17:30:03.366000
2017-10-03T15:11:17
2017-10-03T15:11:17
105,665,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Greatest { public static int greatest(int n1, int n2, int n3) { if (Math.max(n1, n2) > Math.max(n2, n3)) { return Math.max(n1, n2); } else if (Math.max(n1, n2) < Math.max(n2, n3)) { return Math.max(n2, n3); } return Math.max(n1, n2); } public static void main(String[] args) { int result = greatest(2, 7, 3); System.out.println("Greatest: " + result); } }
UTF-8
Java
467
java
Greatest.java
Java
[]
null
[]
public class Greatest { public static int greatest(int n1, int n2, int n3) { if (Math.max(n1, n2) > Math.max(n2, n3)) { return Math.max(n1, n2); } else if (Math.max(n1, n2) < Math.max(n2, n3)) { return Math.max(n2, n3); } return Math.max(n1, n2); } public static void main(String[] args) { int result = greatest(2, 7, 3); System.out.println("Greatest: " + result); } }
467
0.513919
0.471092
17
26.470589
20.384878
56
false
false
0
0
0
0
0
0
0.941176
false
false
14
c88aca33b562636c93fd14bce53564a2af5a1d02
7,825,430,417,614
357299330f0fdfc007bd78f93cc5d8b0be6e7a01
/src/com/harry/crawler/persist/impl/MongodbPersist.java
e624f1603ffaa3615b129c1b473a33edae9a2b16
[]
no_license
lshb/crawler
https://github.com/lshb/crawler
c4ec476d2b1b5ef8f8ad3aa17928ad42d2e8ba6b
a52ead88b55c502fce02dcfcd2fc48c6cffa7d2d
refs/heads/master
2020-03-05T17:23:58.066000
2019-10-07T04:51:30
2019-10-07T04:51:30
85,264,616
0
2
null
false
2020-10-13T02:16:10
2017-03-17T02:58:30
2019-10-07T04:51:38
2020-10-13T02:16:08
8,917
0
0
1
Java
false
false
package com.harry.crawler.persist.impl; import com.harry.crawler.config.Constant; import com.harry.crawler.data.DataReg; import com.harry.crawler.persist.Persist; import org.apache.log4j.Logger; import org.bson.Document; import com.alibaba.fastjson.JSONObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; public class MongodbPersist implements Persist { private final static Logger log = Logger.getLogger(MongodbPersist.class); private static MongoClient client = new MongoClient(new MongoClientURI(Constant.DATA_STORE_MONGO_URI)); @Override public void persistData(DataReg reg, JSONObject json) { log.info("落地的数据:" + json.toJSONString()); String db = reg.getDb(); MongoDatabase database = client.getDatabase(db); String dataTable = reg.getDataTable(); // 验证data解析没有问题,落地 if (validateDate(reg, json)) { Document doc = Document.parse(json.toJSONString()); database.getCollection(dataTable).insertOne(doc); } } @Override public void persistHtml(DataReg reg, JSONObject html) { String db = reg.getDb(); MongoDatabase database = client.getDatabase(db); String htmlTable = reg.getHtmlTable(); Document ht = Document.parse(html.toJSONString()); database.getCollection(htmlTable).insertOne(ht); } @Override public boolean validateDate(DataReg dataReg, JSONObject json) { // TODO 验证数据是否完整 // QUESTION 数据不完整时是否也落地? return true; } }
UTF-8
Java
1,515
java
MongodbPersist.java
Java
[]
null
[]
package com.harry.crawler.persist.impl; import com.harry.crawler.config.Constant; import com.harry.crawler.data.DataReg; import com.harry.crawler.persist.Persist; import org.apache.log4j.Logger; import org.bson.Document; import com.alibaba.fastjson.JSONObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; public class MongodbPersist implements Persist { private final static Logger log = Logger.getLogger(MongodbPersist.class); private static MongoClient client = new MongoClient(new MongoClientURI(Constant.DATA_STORE_MONGO_URI)); @Override public void persistData(DataReg reg, JSONObject json) { log.info("落地的数据:" + json.toJSONString()); String db = reg.getDb(); MongoDatabase database = client.getDatabase(db); String dataTable = reg.getDataTable(); // 验证data解析没有问题,落地 if (validateDate(reg, json)) { Document doc = Document.parse(json.toJSONString()); database.getCollection(dataTable).insertOne(doc); } } @Override public void persistHtml(DataReg reg, JSONObject html) { String db = reg.getDb(); MongoDatabase database = client.getDatabase(db); String htmlTable = reg.getHtmlTable(); Document ht = Document.parse(html.toJSONString()); database.getCollection(htmlTable).insertOne(ht); } @Override public boolean validateDate(DataReg dataReg, JSONObject json) { // TODO 验证数据是否完整 // QUESTION 数据不完整时是否也落地? return true; } }
1,515
0.763687
0.762994
49
28.44898
23.74358
104
false
false
0
0
0
0
0
0
1.530612
false
false
14
0c73c33dadc7588d4d925f27ca4ac6268449e4f8
4,020,089,410,368
64ce7a1404b60bdb6996a9cc319d898dc166c81e
/wot_api_lib/src/main/java/de/sambalmueslie/wot_api_lib/tankopedia_api/request/EncyclopediaTankChassisRequest.java
cdcad65d016ba0efee7fee0188b924b7e86c6d29
[ "Apache-2.0" ]
permissive
chipsi007/WOT-API-LIB
https://github.com/chipsi007/WOT-API-LIB
520803a83ef6b578949344a38102783111f88a1d
f9f33967f4eca0c699f3e665e0795ee444d261f2
refs/heads/master
2020-03-30T19:49:29.480000
2015-08-21T19:51:25
2015-08-21T19:51:25
151,560,300
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.sambalmueslie.wot_api_lib.tankopedia_api.request; import de.sambalmueslie.wot_api_lib.common.BaseWotRequest; import java.lang.String; import java.util.Map; import java.lang.Object; public class EncyclopediaTankChassisRequest extends BaseWotRequest { public EncyclopediaTankChassisRequest() { } @Override public String getMethod( ) { return "wot/encyclopedia/tankchassis/"; } @Override public void getParameter( Map<String, Object> params ) { if (module_id > 0) { params.put("module_id",module_id); } if (nation != null ) { params.put("nation",nation); } } public void setModule_id( long module_id ) { this.module_id = module_id; } public void setNation( String nation ) { this.nation = nation; } private long module_id; private java.lang.String nation; }
UTF-8
Java
819
java
EncyclopediaTankChassisRequest.java
Java
[]
null
[]
package de.sambalmueslie.wot_api_lib.tankopedia_api.request; import de.sambalmueslie.wot_api_lib.common.BaseWotRequest; import java.lang.String; import java.util.Map; import java.lang.Object; public class EncyclopediaTankChassisRequest extends BaseWotRequest { public EncyclopediaTankChassisRequest() { } @Override public String getMethod( ) { return "wot/encyclopedia/tankchassis/"; } @Override public void getParameter( Map<String, Object> params ) { if (module_id > 0) { params.put("module_id",module_id); } if (nation != null ) { params.put("nation",nation); } } public void setModule_id( long module_id ) { this.module_id = module_id; } public void setNation( String nation ) { this.nation = nation; } private long module_id; private java.lang.String nation; }
819
0.711844
0.710623
41
18.95122
20.428282
69
false
false
0
0
0
0
0
0
1.146341
false
false
14
4503f0acdaab9d660c4aacc0167d8863cd3b46a4
455,266,554,532
eff66e65c6b08b98caecdc66f029cae85b4d53fa
/wear/src/main/java/com/mattaniahbeezy/hangup/services/MessageReceiverService.java
a16fc8cb64f1c6b2b46ba1ec1e744bb7653d00b5
[]
no_license
BeezyWorks/Hangup
https://github.com/BeezyWorks/Hangup
496ed8d6f48a72b3c52c1aa00168e4bcfae15e5f
4d8951ba5574b7427e2e57c88d0bd899c4d71045
refs/heads/master
2021-01-24T07:06:26.093000
2017-06-08T05:18:02
2017-06-08T05:18:02
93,332,766
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mattaniahbeezy.hangup.services; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.WearableListenerService; import com.mattaniahbeezy.common.Constants; import com.mattaniahbeezy.hangup.MainActivity; import com.mattaniahbeezy.hangup.R; /** * Created by Beezy Works Studios on 6/4/2017. */ public class MessageReceiverService extends WearableListenerService { private static final String TAG = "MessageReciever"; private static final int NOTIFICAITON_ID = 0; @Override public void onMessageReceived(MessageEvent messageEvent) { switch (messageEvent.getPath()) { case Constants.START_WATCH_APP_PATH: startMainActivity(); break; case Constants.END_WATCH_APP_PATH: endMainActivity(); break; } } private Intent getMainActivityIntent() { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private void startMainActivity() { Log.d(TAG, "received start activity command"); startActivity(getMainActivityIntent()); createNotification(); } private void endMainActivity() { Log.d(TAG, "received kill activity command"); Intent intent = getMainActivityIntent(); intent.putExtra(MainActivity.KEY_KILL_SELF, true); startActivity(intent); killNotification(); } private void createNotification() { PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getMainActivityIntent(), PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Ongoing Call") .setContentIntent(pendingIntent) .setOngoing(true) .build(); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICAITON_ID, notification); } private void killNotification(){ ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICAITON_ID); } }
UTF-8
Java
2,432
java
MessageReceiverService.java
Java
[ { "context": "rt com.mattaniahbeezy.hangup.R;\n\n/**\n * Created by Beezy Works Studios on 6/4/2017.\n */\n\npublic class MessageReceiverSer", "end": 523, "score": 0.9995478391647339, "start": 504, "tag": "NAME", "value": "Beezy Works Studios" } ]
null
[]
package com.mattaniahbeezy.hangup.services; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.WearableListenerService; import com.mattaniahbeezy.common.Constants; import com.mattaniahbeezy.hangup.MainActivity; import com.mattaniahbeezy.hangup.R; /** * Created by <NAME> on 6/4/2017. */ public class MessageReceiverService extends WearableListenerService { private static final String TAG = "MessageReciever"; private static final int NOTIFICAITON_ID = 0; @Override public void onMessageReceived(MessageEvent messageEvent) { switch (messageEvent.getPath()) { case Constants.START_WATCH_APP_PATH: startMainActivity(); break; case Constants.END_WATCH_APP_PATH: endMainActivity(); break; } } private Intent getMainActivityIntent() { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private void startMainActivity() { Log.d(TAG, "received start activity command"); startActivity(getMainActivityIntent()); createNotification(); } private void endMainActivity() { Log.d(TAG, "received kill activity command"); Intent intent = getMainActivityIntent(); intent.putExtra(MainActivity.KEY_KILL_SELF, true); startActivity(intent); killNotification(); } private void createNotification() { PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getMainActivityIntent(), PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Ongoing Call") .setContentIntent(pendingIntent) .setOngoing(true) .build(); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICAITON_ID, notification); } private void killNotification(){ ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICAITON_ID); } }
2,419
0.6875
0.684211
70
33.742859
27.344723
133
false
false
0
0
0
0
0
0
0.585714
false
false
14
9aff8e950a2db54ae03f5475b6d159cf4d0d5e66
30,434,138,300,788
39a379c240858d1f1a63b43686c50808764d98c3
/src/main/java/cn/bdqn/kab/controller/NoticeController.java
ff50b03aabfdf39abc6818f976de9023dac6cdd5
[]
no_license
KabTeam/kab
https://github.com/KabTeam/kab
0cec2dfc4946793e168d254c2f65a40d6c84a690
b662d6a009ac5ca2b7af036a70cd78b2c9b35627
refs/heads/master
2020-05-07T06:06:37.510000
2019-04-23T02:00:59
2019-04-23T02:00:59
180,302,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.bdqn.kab.controller; import cn.bdqn.kab.pojo.Notice; import cn.bdqn.kab.service.NoticeService; import jdk.nashorn.internal.ir.ReturnNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class NoticeController { @Autowired private NoticeService noticeService; @RequestMapping("/kabNoticeManage") public String kabNoticeManage(Model model){ Page<Notice> kabNoticePage = noticeService.getNotice(0,4); model.addAttribute("kabNoticePage",kabNoticePage); return "kabNoticeManage"; } }
UTF-8
Java
766
java
NoticeController.java
Java
[]
null
[]
package cn.bdqn.kab.controller; import cn.bdqn.kab.pojo.Notice; import cn.bdqn.kab.service.NoticeService; import jdk.nashorn.internal.ir.ReturnNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class NoticeController { @Autowired private NoticeService noticeService; @RequestMapping("/kabNoticeManage") public String kabNoticeManage(Model model){ Page<Notice> kabNoticePage = noticeService.getNotice(0,4); model.addAttribute("kabNoticePage",kabNoticePage); return "kabNoticeManage"; } }
766
0.784595
0.781984
23
32.304348
20.985367
66
false
false
0
0
0
0
0
0
0.652174
false
false
14
1f2e6ec773612a663eab240a8c63323d346adcf1
962,072,699,766
ef20ccf2a20e5d107a4ad6f2c5dd82b4c3d16ec7
/data-api/java-rest/src/main/java/io/coinapi/rest/Taker_side.java
cb55eedd5c2b916e8d474b6aab485c7a51ea8f2c
[ "MIT" ]
permissive
coinapi/coinapi-sdk
https://github.com/coinapi/coinapi-sdk
7769916f6af3444e737819d677b5b03f1370dccb
045bbca85d3ee3e3e9c27c9bf94b92c66ec4f2d9
refs/heads/master
2023-09-01T03:20:39.640000
2023-08-31T11:53:50
2023-08-31T11:53:50
92,073,011
462
230
MIT
false
2023-09-13T22:23:28
2017-05-22T16:05:55
2023-09-13T22:13:40
2023-09-13T22:23:27
36,388
433
191
21
C#
false
false
package io.coinapi.rest; /** * Defines all the elements of a taker_side, as described in <a href= "https://docs.coinapi.io/#json-structure">https://docs.coinapi.io/#json-structure</a>. * <p> * This enum is multithread safe: it is stateless (except for the enumeration of values, which are immutable). * <p> * Like all java enums, this enum is Comparable and Serializable. * <p> * @see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/language/enums.html">Enum documentation</a> */ public enum Taker_side { BUY, SELL, BUY_ESTIMATED, SELL_ESTIMATED, UNKNOWN; }
UTF-8
Java
592
java
Taker_side.java
Java
[]
null
[]
package io.coinapi.rest; /** * Defines all the elements of a taker_side, as described in <a href= "https://docs.coinapi.io/#json-structure">https://docs.coinapi.io/#json-structure</a>. * <p> * This enum is multithread safe: it is stateless (except for the enumeration of values, which are immutable). * <p> * Like all java enums, this enum is Comparable and Serializable. * <p> * @see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/language/enums.html">Enum documentation</a> */ public enum Taker_side { BUY, SELL, BUY_ESTIMATED, SELL_ESTIMATED, UNKNOWN; }
592
0.70777
0.706081
20
28.6
44.402027
156
false
false
0
0
0
0
0
0
0.8
false
false
14
0833164631948947db25db1a6e4587f5c1809d36
13,271,448,991,010
f3ac243974889a76332ca0ebb8a0f118f165cb2c
/src/main/java/com/gordeev/campaignbooking/dao/jdbc/mapper/CampaignSummaryRowMapper.java
d40355465d9096df7075ae4d9e87f0020fb1c1a3
[]
no_license
PavelGordeev/campaign-booking
https://github.com/PavelGordeev/campaign-booking
71509c0be997073bf969e89b60c9e29abbabc973
d44083811d3508ad686a64b2d874a0cbc474e1a5
refs/heads/master
2020-04-25T06:04:17.996000
2019-02-27T20:13:45
2019-02-27T20:13:45
172,566,478
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gordeev.campaignbooking.dao.jdbc.mapper; import com.gordeev.campaignbooking.entity.CampaignSummary; import com.gordeev.campaignbooking.entity.Status; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class CampaignSummaryRowMapper implements RowMapper<CampaignSummary> { @Override public CampaignSummary mapRow(ResultSet resultSet, int rowNum) throws SQLException { CampaignSummary campaignSummary = new CampaignSummary(); campaignSummary.setId(resultSet.getInt("c_id")); campaignSummary.setName(resultSet.getString("c_name")); campaignSummary.setStatus(Status.getById(resultSet.getInt("c_status_id"))); campaignSummary.setAdvertCount(resultSet.getInt("ads_count")); return campaignSummary; } }
UTF-8
Java
833
java
CampaignSummaryRowMapper.java
Java
[]
null
[]
package com.gordeev.campaignbooking.dao.jdbc.mapper; import com.gordeev.campaignbooking.entity.CampaignSummary; import com.gordeev.campaignbooking.entity.Status; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class CampaignSummaryRowMapper implements RowMapper<CampaignSummary> { @Override public CampaignSummary mapRow(ResultSet resultSet, int rowNum) throws SQLException { CampaignSummary campaignSummary = new CampaignSummary(); campaignSummary.setId(resultSet.getInt("c_id")); campaignSummary.setName(resultSet.getString("c_name")); campaignSummary.setStatus(Status.getById(resultSet.getInt("c_status_id"))); campaignSummary.setAdvertCount(resultSet.getInt("ads_count")); return campaignSummary; } }
833
0.770708
0.770708
22
36.909092
30.184145
88
false
false
0
0
0
0
0
0
0.590909
false
false
14
60dd643b3223fc1ce95685b79f62c6d87e3c1649
15,444,702,432,840
2c00b9c4ec9fca85833a0d47ed39a16a31d272c0
/Java/LC251.java
ff40d6e1b057d2bd3356c33d6319e2ee3c1b708e
[]
no_license
oily126/Leetcode
https://github.com/oily126/Leetcode
fff8d00ab41e338a02adc821b19b58d2ce9db6ad
23393768ab1fae704ac753290d7ea36ce2c3c0c6
refs/heads/master
2020-04-16T02:16:22.847000
2016-11-25T04:34:05
2016-11-25T04:34:05
64,791,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Vector2D implements Iterator<Integer> { Integer nextNum; Queue<Iterator> iters; public Vector2D(List<List<Integer>> vec2d) { nextNum = null; iters = new LinkedList<>(); for (List<Integer> list : vec2d) { iters.offer(list.iterator()); } findNext(); } @Override public Integer next() { Integer next = nextNum.intValue(); findNext(); return next; } @Override public boolean hasNext() { return nextNum != null; } private void findNext() { if (iters.isEmpty()) return; Iterator iter = iters.peek(); while (!iters.isEmpty() && !iter.hasNext()) { iters.poll(); if (iters.isEmpty()) break; iter = iters.peek(); //System.out.println("Del"); } if (iters.isEmpty()) nextNum = null; else { nextNum = (Integer) iter.next(); } } } /** * Your Vector2D object will be instantiated and called as such: * Vector2D i = new Vector2D(vec2d); * while (i.hasNext()) v[f()] = i.next(); */
UTF-8
Java
1,137
java
LC251.java
Java
[]
null
[]
public class Vector2D implements Iterator<Integer> { Integer nextNum; Queue<Iterator> iters; public Vector2D(List<List<Integer>> vec2d) { nextNum = null; iters = new LinkedList<>(); for (List<Integer> list : vec2d) { iters.offer(list.iterator()); } findNext(); } @Override public Integer next() { Integer next = nextNum.intValue(); findNext(); return next; } @Override public boolean hasNext() { return nextNum != null; } private void findNext() { if (iters.isEmpty()) return; Iterator iter = iters.peek(); while (!iters.isEmpty() && !iter.hasNext()) { iters.poll(); if (iters.isEmpty()) break; iter = iters.peek(); //System.out.println("Del"); } if (iters.isEmpty()) nextNum = null; else { nextNum = (Integer) iter.next(); } } } /** * Your Vector2D object will be instantiated and called as such: * Vector2D i = new Vector2D(vec2d); * while (i.hasNext()) v[f()] = i.next(); */
1,137
0.528584
0.521548
45
24.288889
17.096617
64
false
false
0
0
0
0
0
0
0.444444
false
false
14
2dd9efd1685abffdae9bf7b819299a0e10d2facf
19,602,230,773,306
36023ed066b596a7156ac69541f001297366fb0f
/contas/src/main/java/PadraoBean.java
70bd46d28dad9fce2e375f08be127103f2d32628
[]
no_license
edsonsousa/Contas
https://github.com/edsonsousa/Contas
986edfc538f95a84ab1d4b6001486b3b41faaf26
13a6dddfc35a77e6eb3cbb449d48ae523463d6d4
refs/heads/master
2021-01-02T22:58:43.270000
2015-09-23T13:12:00
2015-09-23T13:12:00
31,980,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.Serializable; import java.lang.reflect.ParameterizedType; import javax.ejb.EJB; import javax.enterprise.context.Conversation; import javax.inject.Inject; public class PadraoBean<T extends EntidadeBase> implements Serializable { @EJB ControleEntidade controleEntidade; @Inject private Conversation conversation; private Long id; private T instance; public T getInstance() { if (instance == null) { if (id != null) { instance = loadInstance(); } else { instance = createInstance(); } } return instance; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public T loadInstance() { return controleEntidade.find(getClassType(), getId()); } public T createInstance() { try { return getClassType().newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } private Class<T> getClassType() { ParameterizedType parameterizedType = (ParameterizedType) getClass() .getGenericSuperclass(); return (Class<T>) parameterizedType.getActualTypeArguments()[0]; } public boolean isManaged() { return (getInstance()).getId() != null; } public String save() { if (isManaged()) { controleEntidade.updateObject(getInstance()); } else { controleEntidade.createObject(getInstance()); } //conversation.end(); return "Registro Salvo com Sucesso"; } public String cancel() { //conversation.end(); return "cancelled"; } public void initConversation() { if (conversation.isTransient()) { conversation.begin(); } } }
UTF-8
Java
1,660
java
PadraoBean.java
Java
[]
null
[]
import java.io.Serializable; import java.lang.reflect.ParameterizedType; import javax.ejb.EJB; import javax.enterprise.context.Conversation; import javax.inject.Inject; public class PadraoBean<T extends EntidadeBase> implements Serializable { @EJB ControleEntidade controleEntidade; @Inject private Conversation conversation; private Long id; private T instance; public T getInstance() { if (instance == null) { if (id != null) { instance = loadInstance(); } else { instance = createInstance(); } } return instance; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public T loadInstance() { return controleEntidade.find(getClassType(), getId()); } public T createInstance() { try { return getClassType().newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } private Class<T> getClassType() { ParameterizedType parameterizedType = (ParameterizedType) getClass() .getGenericSuperclass(); return (Class<T>) parameterizedType.getActualTypeArguments()[0]; } public boolean isManaged() { return (getInstance()).getId() != null; } public String save() { if (isManaged()) { controleEntidade.updateObject(getInstance()); } else { controleEntidade.createObject(getInstance()); } //conversation.end(); return "Registro Salvo com Sucesso"; } public String cancel() { //conversation.end(); return "cancelled"; } public void initConversation() { if (conversation.isTransient()) { conversation.begin(); } } }
1,660
0.654819
0.654217
81
18.444445
18.02536
73
false
false
0
0
0
0
0
0
1.703704
false
false
14
96df5a233311e394aa7fbfb614367056ba45d407
12,962,211,322,463
0026331f43462e52d2eb882ded023e9f881be29f
/manager/manager-service/src/main/java/com/lambert/manager/service/impl/TestDubboServiceImpl.java
89cdbd4de9b290237b6b6bb932d2f79dffbe66f9
[]
no_license
Lin-Lambert/youyijia
https://github.com/Lin-Lambert/youyijia
b743a041005d59ee6d95b3cf55512a29b823e65f
017e8079ed5c10f18f04789c9ed74db40b2a1fcd
refs/heads/master
2020-03-27T06:54:57.768000
2018-08-26T02:37:12
2018-08-26T02:37:12
146,146,409
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lambert.manager.service.impl; import com.lambert.manager.service.TestDubboService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; @Service public class TestDubboServiceImpl implements TestDubboService { @Override public String getDate() { return "two"; } }
UTF-8
Java
379
java
TestDubboServiceImpl.java
Java
[]
null
[]
package com.lambert.manager.service.impl; import com.lambert.manager.service.TestDubboService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; @Service public class TestDubboServiceImpl implements TestDubboService { @Override public String getDate() { return "two"; } }
379
0.778364
0.778364
16
22.6875
22.504774
63
false
false
0
0
0
0
0
0
0.375
false
false
14
bbdbd48cb7c7b15f0b4e8e1b725c1630d40d543e
28,071,906,250,166
e119cf913048c3502b2a919315fa4738818c0fba
/computator/src/main/java/com/alta/computator/core/computator/movement/directionCalculation/StandSpotMovementStrategy.java
6af0e81febd8dc22922afca3f796fafc504ba113
[]
no_license
amakhaev/alta_story
https://github.com/amakhaev/alta_story
9b80fecb39b1527c6c504ea0f49c28a54fc2e231
a093a23234d6a36316ba0e28509040b7fa45909e
refs/heads/dev
2020-03-28T17:25:03.041000
2019-09-24T07:38:00
2019-09-24T07:38:00
148,787,470
0
0
null
false
2019-09-24T07:38:02
2018-09-14T12:47:45
2019-09-12T12:22:34
2019-09-24T07:38:01
12,339
0
0
0
Java
false
false
package com.alta.computator.core.computator.movement.directionCalculation; import com.alta.computator.model.altitudeMap.AltitudeMap; import java.awt.*; /** * Provides the direction action that focused on one point. */ public class StandSpotMovementStrategy implements MovementDirectionStrategy { /** * Calculates the parameters for next movement. * * @param startPoint - the start point for calculation. * @param direction - the direction of movement. * @param altitudeMap - the altitude map instance. */ @Override public void calculateMovement(Point startPoint, MovementDirection direction, AltitudeMap altitudeMap) { } /** * Gets the direction for future movement. */ @Override public MovementDirection getDirection() { return null; } /** * Gets the target point for moving. * * @return the target point for moving. */ @Override public Point getTargetPointForMoving() { return null; } /** * Indicates if object can be moved to given map coordinates * * @param mapCoordinates - the target map coordinates. * @param altitudeMap - the {@link AltitudeMap} instance * @return true if move process can be run for given direction, false otherwise */ @Override public boolean isCanMoveTo(Point mapCoordinates, AltitudeMap altitudeMap) { return false; } /** * Indicates when the route of movement completed. * * @return true if route was completed, false otherwise. */ @Override public boolean isRouteCompleted() { return true; } }
UTF-8
Java
1,664
java
StandSpotMovementStrategy.java
Java
[]
null
[]
package com.alta.computator.core.computator.movement.directionCalculation; import com.alta.computator.model.altitudeMap.AltitudeMap; import java.awt.*; /** * Provides the direction action that focused on one point. */ public class StandSpotMovementStrategy implements MovementDirectionStrategy { /** * Calculates the parameters for next movement. * * @param startPoint - the start point for calculation. * @param direction - the direction of movement. * @param altitudeMap - the altitude map instance. */ @Override public void calculateMovement(Point startPoint, MovementDirection direction, AltitudeMap altitudeMap) { } /** * Gets the direction for future movement. */ @Override public MovementDirection getDirection() { return null; } /** * Gets the target point for moving. * * @return the target point for moving. */ @Override public Point getTargetPointForMoving() { return null; } /** * Indicates if object can be moved to given map coordinates * * @param mapCoordinates - the target map coordinates. * @param altitudeMap - the {@link AltitudeMap} instance * @return true if move process can be run for given direction, false otherwise */ @Override public boolean isCanMoveTo(Point mapCoordinates, AltitudeMap altitudeMap) { return false; } /** * Indicates when the route of movement completed. * * @return true if route was completed, false otherwise. */ @Override public boolean isRouteCompleted() { return true; } }
1,664
0.661659
0.661659
63
25.412699
27.209146
107
false
false
0
0
0
0
0
0
0.190476
false
false
14
bf1e9e7e631826cfad48111ffb6d99c67187e14e
23,192,823,430,771
278b157c428fab274b2d6256323e6fcde5c66f6d
/src/main/java/com/icthh/xm/ms/entity/util/DatabaseUtil.java
3804e0823605ba18f7427ffb0773d720908b941a
[ "Apache-2.0" ]
permissive
xm-online/xm-ms-entity
https://github.com/xm-online/xm-ms-entity
1d1dc9a56f1128fe6d8c9aff64df554922bcac62
48ed69dff5d7b5f0e8ef947efc0950a8ef2dcfed
refs/heads/master
2023-08-25T13:24:38.322000
2023-08-14T07:14:59
2023-08-14T07:14:59
105,269,474
10
3
Apache-2.0
false
2023-09-13T09:16:59
2017-09-29T12:25:50
2023-02-13T13:43:16
2023-09-13T09:16:58
3,696
13
4
11
Java
false
false
package com.icthh.xm.ms.entity.util; import com.icthh.xm.ms.entity.domain.XmEntity; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.function.Consumer; /** * Utility for database operations. */ @Slf4j @UtilityClass @SuppressWarnings("squid:S1118") // private constructor generated by lombok public final class DatabaseUtil { public static void runAfterTransaction(XmEntity xmEntity, Consumer<XmEntity> task) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { super.afterCompletion(status); if (status == STATUS_COMMITTED) { try { task.accept(xmEntity); } catch (Exception e) { log.error("Error in afterCompletion stage during transaction synchronization for entity: {}", xmEntity, e); } } } }); } }
UTF-8
Java
1,265
java
DatabaseUtil.java
Java
[]
null
[]
package com.icthh.xm.ms.entity.util; import com.icthh.xm.ms.entity.domain.XmEntity; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.function.Consumer; /** * Utility for database operations. */ @Slf4j @UtilityClass @SuppressWarnings("squid:S1118") // private constructor generated by lombok public final class DatabaseUtil { public static void runAfterTransaction(XmEntity xmEntity, Consumer<XmEntity> task) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { super.afterCompletion(status); if (status == STATUS_COMMITTED) { try { task.accept(xmEntity); } catch (Exception e) { log.error("Error in afterCompletion stage during transaction synchronization for entity: {}", xmEntity, e); } } } }); } }
1,265
0.648221
0.642688
35
35.142857
31.111912
117
false
false
0
0
0
0
0
0
0.4
false
false
14
cd9f712edfcfa1840395392869aa6e54a634c894
1,211,180,792,016
007f9a008c2c40fb9cdbee0f4d7a51e8f9ca534c
/MMP/src/main/java/org/iit/util/DataBaseTesting.java
fc559ea94c59dbf63779cfc5858fa7430c750840
[]
no_license
anikaavisha/MMPRepo
https://github.com/anikaavisha/MMPRepo
6cd35b5b5c48e653466d8c96a7d4aff35a772b39
34b6ca1e01d2f24803dd2501e75856cc104b58bd
refs/heads/master
2022-12-22T09:22:18.091000
2020-10-02T17:36:42
2020-10-02T17:36:42
296,769,107
0
0
null
false
2020-10-02T17:36:43
2020-09-19T02:17:11
2020-09-30T21:25:09
2020-10-02T17:36:43
4,835
0
0
0
Java
false
false
package org.iit.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataBaseTesting { //Command Line Command to create table and test databse //show databases; --This query will show all the datbases available //use mysql ; --This query is used to select mysql database //create database testdb; --This will create new database testdb //use testdb; -- Will point to testDb database //create table MMPLogin (pUname varchar(20),pPwd varchar(20),text varchar(20); --Will create new table in testdb database with 3 columns (pUname & pPwd & textand these 3 fields will take String of 20 charcters)(since we did "use testDb" , this datbase is pointed ) //describe MMOLogin; - will show all the columns(field) , datatype of the fields) //insert into MMPLogin values("ria1","Ria12345","ria1"); this will insert values in the columns //insert into MMPLogin(text,pUname,pPwd) values("ria1","ria1","Ria12345"); this will insert value int he respective columns //select * from MMPLogin; -- will show you all the data in this table // Calling getDBValue method and passing database url ,username,pwd, database name ,table name //and this method will return 2 dimension array, which will be passed to test via dataProvider public String[][] feedDP() throws Exception { String data[][] = getDBValues("jdbc:mysql://localhost:3306/testdb", "root", "admin", "testDataBase", "MMPLogin"); return data; } // Method to get data from any database and this method will return data in // two dimensional array // String url = "jdbc:mysql://localhost:3306/testdb"; // String username = "root"; // String pwd = "admin"; public String[][] getDBValues(String url, String username, String pwd, String dbName, String tableName) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); // getConnection method of DriverManager is used to extablish connection // with data base.Data base url will be of format // "jdbc:subprotocol:subname" and for extablishing connection you will // need username and password of database //This will give connection Object - con Connection con = DriverManager.getConnection(url, username, pwd); //Using this connection Object we create statmenet object to execute query and decide //result set which is result of execution Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Below 2 statement are used to Insert data in table which can be done // manually via command line // int value = stmt.executeUpdate("INSERT INTO `testdb`.`login` VALUES // ('java','java123#');"); // System.out.println("The rows are upated "+ value); //commandFinal will be a query slect * from dbName.tableName String query1 = "Select * from %dbName%.%tableName%"; String query2 = query1.replace("%dbName%", dbName); String sqlQuery = query2.replace("%tableName%", tableName); //We are executing SQL query //stmt.executeQuery(select *from dbName.table) will execute this query and results will be stored in Resultset object ResultSet rs = stmt.executeQuery(sqlQuery); //pointing to the last row .By default it points to first row. rs.last(); //now getting row number of last row , which will be same as total number of rows as row starts from 1. int rows = rs.getRow(); System.out.println("Number of rows " + rows); //getMetaData() method will have all the properties of result set columns ResultSetMetaData rsmd = rs.getMetaData(); //Total column number in result set int cols = rsmd.getColumnCount(); System.out.println("Number of cols: " + cols); //Declaring 2 dimensional array String data[][] = new String[rows][cols]; //Row Number and Column number of Result set will atrt from 1 . But in data[][] we will be storing data from index 0 i.e data[0][0] int i = 0; //pointing resultset cursor before first row rs.beforeFirst(); while (rs.next()) { for (int j = 0; j < cols; j++) { data[i][j] = rs.getString(j + 1); System.out.println(data[i][j]); } i++; } return data; } }
UTF-8
Java
4,447
java
DataBaseTesting.java
Java
[ { "context": "e of the fields)\r\n\t//insert into MMPLogin values(\"ria1\",\"Ria12345\",\"ria1\"); this will insert values in t", "end": 1030, "score": 0.9679759740829468, "start": 1026, "tag": "USERNAME", "value": "ria1" }, { "context": "e fields)\r\n\t//insert into MMPLogin values(...
null
[]
package org.iit.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataBaseTesting { //Command Line Command to create table and test databse //show databases; --This query will show all the datbases available //use mysql ; --This query is used to select mysql database //create database testdb; --This will create new database testdb //use testdb; -- Will point to testDb database //create table MMPLogin (pUname varchar(20),pPwd varchar(20),text varchar(20); --Will create new table in testdb database with 3 columns (pUname & pPwd & textand these 3 fields will take String of 20 charcters)(since we did "use testDb" , this datbase is pointed ) //describe MMOLogin; - will show all the columns(field) , datatype of the fields) //insert into MMPLogin values("ria1","<PASSWORD>","<PASSWORD>"); this will insert values in the columns //insert into MMPLogin(text,pUname,pPwd) values("ria1","ria1","<PASSWORD>"); this will insert value int he respective columns //select * from MMPLogin; -- will show you all the data in this table // Calling getDBValue method and passing database url ,username,pwd, database name ,table name //and this method will return 2 dimension array, which will be passed to test via dataProvider public String[][] feedDP() throws Exception { String data[][] = getDBValues("jdbc:mysql://localhost:3306/testdb", "root", "admin", "testDataBase", "MMPLogin"); return data; } // Method to get data from any database and this method will return data in // two dimensional array // String url = "jdbc:mysql://localhost:3306/testdb"; // String username = "root"; // String pwd = "<PASSWORD>"; public String[][] getDBValues(String url, String username, String pwd, String dbName, String tableName) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); // getConnection method of DriverManager is used to extablish connection // with data base.Data base url will be of format // "jdbc:subprotocol:subname" and for extablishing connection you will // need username and password of database //This will give connection Object - con Connection con = DriverManager.getConnection(url, username, pwd); //Using this connection Object we create statmenet object to execute query and decide //result set which is result of execution Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Below 2 statement are used to Insert data in table which can be done // manually via command line // int value = stmt.executeUpdate("INSERT INTO `testdb`.`login` VALUES // ('java','java123#');"); // System.out.println("The rows are upated "+ value); //commandFinal will be a query slect * from dbName.tableName String query1 = "Select * from %dbName%.%tableName%"; String query2 = query1.replace("%dbName%", dbName); String sqlQuery = query2.replace("%tableName%", tableName); //We are executing SQL query //stmt.executeQuery(select *from dbName.table) will execute this query and results will be stored in Resultset object ResultSet rs = stmt.executeQuery(sqlQuery); //pointing to the last row .By default it points to first row. rs.last(); //now getting row number of last row , which will be same as total number of rows as row starts from 1. int rows = rs.getRow(); System.out.println("Number of rows " + rows); //getMetaData() method will have all the properties of result set columns ResultSetMetaData rsmd = rs.getMetaData(); //Total column number in result set int cols = rsmd.getColumnCount(); System.out.println("Number of cols: " + cols); //Declaring 2 dimensional array String data[][] = new String[rows][cols]; //Row Number and Column number of Result set will atrt from 1 . But in data[][] we will be storing data from index 0 i.e data[0][0] int i = 0; //pointing resultset cursor before first row rs.beforeFirst(); while (rs.next()) { for (int j = 0; j < cols; j++) { data[i][j] = rs.getString(j + 1); System.out.println(data[i][j]); } i++; } return data; } }
4,462
0.698448
0.687205
104
40.73077
39.901134
265
false
false
0
0
0
0
0
0
2.086539
false
false
14
0bfa71a527be0b918736b0cc763a143f25e8cddc
11,553,462,063,488
ee079a6fbcbcdcee969a833b189fe06b0e31e27f
/src/main/java/com/boot/base/BaseException.java
0c1b8f89bac4b96dd9b0abbc778819eab58af077
[]
no_license
loumt/framework-spring-boot
https://github.com/loumt/framework-spring-boot
2af87950ed4ba8fa578a7b364b2337c72e3fb769
70391b9f953787b6cd8e36bc66c869e9973c3070
refs/heads/master
2020-05-15T02:12:56.002000
2019-04-29T03:03:37
2019-04-29T03:03:37
182,045,019
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boot.base; public class BaseException extends RuntimeException { private int code; public BaseException() { super(); } public BaseException(int code, String message) { super(message); this.code = code; } public BaseException(int code, String message, Throwable cause) { super(message, cause); this.code = code; } public BaseException(Throwable cause) { super(cause); } public BaseException(int code, String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); this.code = code; } }
UTF-8
Java
701
java
BaseException.java
Java
[]
null
[]
package com.boot.base; public class BaseException extends RuntimeException { private int code; public BaseException() { super(); } public BaseException(int code, String message) { super(message); this.code = code; } public BaseException(int code, String message, Throwable cause) { super(message, cause); this.code = code; } public BaseException(Throwable cause) { super(cause); } public BaseException(int code, String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); this.code = code; } }
701
0.651926
0.651926
29
23.172413
27.869238
124
false
false
0
0
0
0
0
0
0.724138
false
false
2
1ebb101202ab02d2259ba3817de68a1f2f6c4296
14,448,270,045,516
082e26b011e30dc62a62fae95f375e4f87d9e99c
/docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/liteav/audio/impl/a.java
73a057c79977ec39e7f14efe9c2683c61f992f50
[]
no_license
xsren/AndroidReverseNotes
https://github.com/xsren/AndroidReverseNotes
9631a5aabc031006e795a112b7ac756a8edd4385
9202c276fe9f04a978e4e08b08e42645d97ca94b
refs/heads/master
2021-04-07T22:50:51.072000
2019-07-16T02:24:43
2019-07-16T02:24:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.liteav.audio.impl; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothProfile.ServiceListener; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.os.Handler; import android.os.Looper; import com.samsung.android.sdk.look.airbutton.SlookAirButtonRecentMediaAdapter; import com.tencent.liteav.audio.TXEAudioDef; import com.tencent.liteav.basic.log.TXCLog; import com.tencent.liteav.basic.util.b; import com.tencent.matrix.trace.core.AppMethodBeat; import java.util.ArrayList; import java.util.List; public class a implements e { private final String a; private Context b; private BroadcastReceiver c; private ServiceListener d; private BluetoothHeadset e; private List<d> f; private Handler g; private boolean h; private int i; private AudioManager j; static class a { private static final a a = new a(); static { AppMethodBeat.i(66553); AppMethodBeat.o(66553); } } /* synthetic */ a(AnonymousClass1 anonymousClass1) { this(); } static /* synthetic */ void b(a aVar, Intent intent) { AppMethodBeat.i(66581); aVar.a(intent); AppMethodBeat.o(66581); } public static void a(String str) { AppMethodBeat.i(66568); TXCTraeJNI.nativeSetTraeConfig(str); AppMethodBeat.o(66568); } static { AppMethodBeat.i(66583); b.e(); AppMethodBeat.o(66583); } public static a a() { AppMethodBeat.i(66569); a a = a.a; AppMethodBeat.o(66569); return a; } private a() { AppMethodBeat.i(66570); this.a = "AudioCenter:" + a.class.getSimpleName(); this.i = TXEAudioDef.TXE_AUDIO_MODE_SPEAKER; this.f = new ArrayList(); AppMethodBeat.o(66570); } public void a(Context context) { AppMethodBeat.i(66571); if (this.c != null) { AppMethodBeat.o(66571); return; } TXCLog.i(this.a, "init"); this.b = context.getApplicationContext(); c.a().a(this.b); c.a().a((e) this); this.j = (AudioManager) context.getSystemService(SlookAirButtonRecentMediaAdapter.AUDIO_TYPE); this.g = new Handler(Looper.getMainLooper()); this.c = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { AppMethodBeat.i(66707); String action = intent.getAction(); TXCLog.i(a.this.a, "onReceive, action = ".concat(String.valueOf(action))); if (action.equals("android.intent.action.HEADSET_PLUG")) { a.a(a.this, intent); AppMethodBeat.o(66707); } else if (action.equals("android.media.ACTION_SCO_AUDIO_STATE_UPDATED")) { a.b(a.this, intent); AppMethodBeat.o(66707); } else { BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE"); if (!(bluetoothDevice == null || a.this.e == null)) { try { Thread.sleep(500); } catch (InterruptedException e) { } a.a(a.this, bluetoothDevice); } AppMethodBeat.o(66707); } } }; this.d = new ServiceListener() { public void onServiceConnected(int i, BluetoothProfile bluetoothProfile) { AppMethodBeat.i(66705); TXCLog.i(a.this.a, "onServiceConnected"); if (i == 1) { a.this.e = (BluetoothHeadset) bluetoothProfile; List connectedDevices = a.this.e.getConnectedDevices(); if (connectedDevices != null && connectedDevices.size() > 0) { a.a(a.this, (BluetoothDevice) connectedDevices.get(0)); } } AppMethodBeat.o(66705); } public void onServiceDisconnected(int i) { AppMethodBeat.i(66706); TXCLog.i(a.this.a, "onServiceDisconnected"); if (i == 1) { a.this.e = null; a.this.a(a.this.i); } AppMethodBeat.o(66706); } }; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED"); intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED"); intentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED"); intentFilter.addAction("android.media.ACTION_SCO_AUDIO_STATE_UPDATED"); this.b.registerReceiver(this.c, intentFilter); try { BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter(); if (defaultAdapter != null) { defaultAdapter.getProfileProxy(this.b, this.d, 1); } AppMethodBeat.o(66571); } catch (Exception e) { TXCLog.e(this.a, "BluetoothAdapter getProfileProxy: ".concat(String.valueOf(e))); AppMethodBeat.o(66571); } } private void a(Intent intent) { AppMethodBeat.i(66572); int intExtra = intent.getIntExtra("android.media.extra.SCO_AUDIO_STATE", -1); new StringBuilder("Audio SCO state: ").append(intExtra).append(", thread id = ").append(Thread.currentThread().getId()); if (intExtra == 1) { TXCLog.i(this.a, "SCO connected, yeah!"); this.j.setBluetoothScoOn(true); a(this.i); AppMethodBeat.o(66572); } else if (intExtra == 2) { TXCLog.i(this.a, "SCO connecting"); AppMethodBeat.o(66572); } else { if (intExtra == 0) { TXCLog.i(this.a, "SCO disconnect"); if (this.e == null) { AppMethodBeat.o(66572); return; } this.g.postDelayed(new Runnable() { public void run() { AppMethodBeat.i(66567); a.this.j.startBluetoothSco(); AppMethodBeat.o(66567); } }, 1000); } AppMethodBeat.o(66572); } } private void b(Intent intent) { AppMethodBeat.i(66573); if (intent.hasExtra("state")) { int intExtra = intent.getIntExtra("state", 0); if (intExtra == 0) { this.h = false; a(false); a(this.i); TXCLog.d(this.a, "pull out wired headset"); AppMethodBeat.o(66573); return; } else if (1 == intExtra) { this.h = true; a(true); a(this.i); TXCLog.d(this.a, "insert wired headset"); } } AppMethodBeat.o(66573); } private void a(BluetoothDevice bluetoothDevice) { AppMethodBeat.i(66574); if (bluetoothDevice == null || this.e == null) { AppMethodBeat.o(66574); return; } int connectionState; try { connectionState = this.e.getConnectionState(bluetoothDevice); } catch (Exception e) { TXCLog.e(this.a, "getConnectionState exception: ".concat(String.valueOf(e))); connectionState = 0; } TXCLog.d(this.a, "BluetoothHeadset state:".concat(String.valueOf(connectionState))); switch (connectionState) { case 0: a(false); TXCLog.d(this.a, "BluetoothHeadset disconnect"); this.j.setBluetoothScoOn(false); this.j.stopBluetoothSco(); a(this.i); break; case 2: a(true); TXCLog.d(this.a, "BluetoothHeadset connect"); if (this.j.isBluetoothScoAvailableOffCall()) { this.j.startBluetoothSco(); AppMethodBeat.o(66574); return; } TXCLog.e(this.a, "not support BTHeadset sco"); AppMethodBeat.o(66574); return; } AppMethodBeat.o(66574); } public synchronized void a(int i) { AppMethodBeat.i(66575); this.i = i; if (this.h) { this.j.setMode(0); this.j.setSpeakerphoneOn(false); TXCLog.d(this.a, "setAudioMode, is wiredHeadsetOn, set MODE_NORMAL and speakerphoneOn false"); AppMethodBeat.o(66575); } else if (this.e != null && this.j.isBluetoothScoOn()) { this.j.setMode(3); this.j.setSpeakerphoneOn(false); TXCLog.d(this.a, "setAudioMode, is bluetoothHeadset connect and isBluetoothScoOn true, set mode MODE_IN_COMMUNICATION and speakerphoneOn false"); AppMethodBeat.o(66575); } else if (this.j == null) { AppMethodBeat.o(66575); } else if (i == TXEAudioDef.TXE_AUDIO_MODE_RECEIVER) { this.j.setMode(3); this.j.setSpeakerphoneOn(false); TXCLog.i(this.a, "AudioCenter setAudioMode to receiver, MODE_IN_COMMUNICATION, speakerphoneOn false"); AppMethodBeat.o(66575); } else { this.j.setMode(0); this.j.setSpeakerphoneOn(true); TXCLog.i(this.a, "AudioCenter setAudioMode to speaker, MODE_NORMAL, speakerphoneOn true"); AppMethodBeat.o(66575); } } public synchronized void a(d dVar) { AppMethodBeat.i(66576); if (dVar == null) { AppMethodBeat.o(66576); } else { this.f.add(dVar); if (this.h) { dVar.OnHeadsetState(true); AppMethodBeat.o(66576); } else if (this.e == null || this.j == null || !this.j.isBluetoothScoOn()) { dVar.OnHeadsetState(false); AppMethodBeat.o(66576); } else { dVar.OnHeadsetState(true); AppMethodBeat.o(66576); } } } public synchronized void b(d dVar) { AppMethodBeat.i(66577); if (dVar == null) { AppMethodBeat.o(66577); } else { this.f.remove(dVar); AppMethodBeat.o(66577); } } private synchronized void a(boolean z) { AppMethodBeat.i(66578); for (d OnHeadsetState : this.f) { OnHeadsetState.OnHeadsetState(z); } AppMethodBeat.o(66578); } public void b(int i) { AppMethodBeat.i(66579); TXCLog.i(this.a, "onCallStateChanged, state = ".concat(String.valueOf(i))); if (this.j.isBluetoothScoAvailableOffCall()) { if (!(i != 0 || this.e == null || this.j.isBluetoothScoOn())) { TXCLog.i(this.a, "to restartBluetoothSco"); this.g.postDelayed(new Runnable() { public void run() { AppMethodBeat.i(66543); a.this.j.startBluetoothSco(); AppMethodBeat.o(66543); } }, 1000); } AppMethodBeat.o(66579); return; } TXCLog.e(this.a, "not support BTHeadset sco"); AppMethodBeat.o(66579); } }
UTF-8
Java
12,058
java
a.java
Java
[]
null
[]
package com.tencent.liteav.audio.impl; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothProfile.ServiceListener; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.os.Handler; import android.os.Looper; import com.samsung.android.sdk.look.airbutton.SlookAirButtonRecentMediaAdapter; import com.tencent.liteav.audio.TXEAudioDef; import com.tencent.liteav.basic.log.TXCLog; import com.tencent.liteav.basic.util.b; import com.tencent.matrix.trace.core.AppMethodBeat; import java.util.ArrayList; import java.util.List; public class a implements e { private final String a; private Context b; private BroadcastReceiver c; private ServiceListener d; private BluetoothHeadset e; private List<d> f; private Handler g; private boolean h; private int i; private AudioManager j; static class a { private static final a a = new a(); static { AppMethodBeat.i(66553); AppMethodBeat.o(66553); } } /* synthetic */ a(AnonymousClass1 anonymousClass1) { this(); } static /* synthetic */ void b(a aVar, Intent intent) { AppMethodBeat.i(66581); aVar.a(intent); AppMethodBeat.o(66581); } public static void a(String str) { AppMethodBeat.i(66568); TXCTraeJNI.nativeSetTraeConfig(str); AppMethodBeat.o(66568); } static { AppMethodBeat.i(66583); b.e(); AppMethodBeat.o(66583); } public static a a() { AppMethodBeat.i(66569); a a = a.a; AppMethodBeat.o(66569); return a; } private a() { AppMethodBeat.i(66570); this.a = "AudioCenter:" + a.class.getSimpleName(); this.i = TXEAudioDef.TXE_AUDIO_MODE_SPEAKER; this.f = new ArrayList(); AppMethodBeat.o(66570); } public void a(Context context) { AppMethodBeat.i(66571); if (this.c != null) { AppMethodBeat.o(66571); return; } TXCLog.i(this.a, "init"); this.b = context.getApplicationContext(); c.a().a(this.b); c.a().a((e) this); this.j = (AudioManager) context.getSystemService(SlookAirButtonRecentMediaAdapter.AUDIO_TYPE); this.g = new Handler(Looper.getMainLooper()); this.c = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { AppMethodBeat.i(66707); String action = intent.getAction(); TXCLog.i(a.this.a, "onReceive, action = ".concat(String.valueOf(action))); if (action.equals("android.intent.action.HEADSET_PLUG")) { a.a(a.this, intent); AppMethodBeat.o(66707); } else if (action.equals("android.media.ACTION_SCO_AUDIO_STATE_UPDATED")) { a.b(a.this, intent); AppMethodBeat.o(66707); } else { BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE"); if (!(bluetoothDevice == null || a.this.e == null)) { try { Thread.sleep(500); } catch (InterruptedException e) { } a.a(a.this, bluetoothDevice); } AppMethodBeat.o(66707); } } }; this.d = new ServiceListener() { public void onServiceConnected(int i, BluetoothProfile bluetoothProfile) { AppMethodBeat.i(66705); TXCLog.i(a.this.a, "onServiceConnected"); if (i == 1) { a.this.e = (BluetoothHeadset) bluetoothProfile; List connectedDevices = a.this.e.getConnectedDevices(); if (connectedDevices != null && connectedDevices.size() > 0) { a.a(a.this, (BluetoothDevice) connectedDevices.get(0)); } } AppMethodBeat.o(66705); } public void onServiceDisconnected(int i) { AppMethodBeat.i(66706); TXCLog.i(a.this.a, "onServiceDisconnected"); if (i == 1) { a.this.e = null; a.this.a(a.this.i); } AppMethodBeat.o(66706); } }; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED"); intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED"); intentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED"); intentFilter.addAction("android.media.ACTION_SCO_AUDIO_STATE_UPDATED"); this.b.registerReceiver(this.c, intentFilter); try { BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter(); if (defaultAdapter != null) { defaultAdapter.getProfileProxy(this.b, this.d, 1); } AppMethodBeat.o(66571); } catch (Exception e) { TXCLog.e(this.a, "BluetoothAdapter getProfileProxy: ".concat(String.valueOf(e))); AppMethodBeat.o(66571); } } private void a(Intent intent) { AppMethodBeat.i(66572); int intExtra = intent.getIntExtra("android.media.extra.SCO_AUDIO_STATE", -1); new StringBuilder("Audio SCO state: ").append(intExtra).append(", thread id = ").append(Thread.currentThread().getId()); if (intExtra == 1) { TXCLog.i(this.a, "SCO connected, yeah!"); this.j.setBluetoothScoOn(true); a(this.i); AppMethodBeat.o(66572); } else if (intExtra == 2) { TXCLog.i(this.a, "SCO connecting"); AppMethodBeat.o(66572); } else { if (intExtra == 0) { TXCLog.i(this.a, "SCO disconnect"); if (this.e == null) { AppMethodBeat.o(66572); return; } this.g.postDelayed(new Runnable() { public void run() { AppMethodBeat.i(66567); a.this.j.startBluetoothSco(); AppMethodBeat.o(66567); } }, 1000); } AppMethodBeat.o(66572); } } private void b(Intent intent) { AppMethodBeat.i(66573); if (intent.hasExtra("state")) { int intExtra = intent.getIntExtra("state", 0); if (intExtra == 0) { this.h = false; a(false); a(this.i); TXCLog.d(this.a, "pull out wired headset"); AppMethodBeat.o(66573); return; } else if (1 == intExtra) { this.h = true; a(true); a(this.i); TXCLog.d(this.a, "insert wired headset"); } } AppMethodBeat.o(66573); } private void a(BluetoothDevice bluetoothDevice) { AppMethodBeat.i(66574); if (bluetoothDevice == null || this.e == null) { AppMethodBeat.o(66574); return; } int connectionState; try { connectionState = this.e.getConnectionState(bluetoothDevice); } catch (Exception e) { TXCLog.e(this.a, "getConnectionState exception: ".concat(String.valueOf(e))); connectionState = 0; } TXCLog.d(this.a, "BluetoothHeadset state:".concat(String.valueOf(connectionState))); switch (connectionState) { case 0: a(false); TXCLog.d(this.a, "BluetoothHeadset disconnect"); this.j.setBluetoothScoOn(false); this.j.stopBluetoothSco(); a(this.i); break; case 2: a(true); TXCLog.d(this.a, "BluetoothHeadset connect"); if (this.j.isBluetoothScoAvailableOffCall()) { this.j.startBluetoothSco(); AppMethodBeat.o(66574); return; } TXCLog.e(this.a, "not support BTHeadset sco"); AppMethodBeat.o(66574); return; } AppMethodBeat.o(66574); } public synchronized void a(int i) { AppMethodBeat.i(66575); this.i = i; if (this.h) { this.j.setMode(0); this.j.setSpeakerphoneOn(false); TXCLog.d(this.a, "setAudioMode, is wiredHeadsetOn, set MODE_NORMAL and speakerphoneOn false"); AppMethodBeat.o(66575); } else if (this.e != null && this.j.isBluetoothScoOn()) { this.j.setMode(3); this.j.setSpeakerphoneOn(false); TXCLog.d(this.a, "setAudioMode, is bluetoothHeadset connect and isBluetoothScoOn true, set mode MODE_IN_COMMUNICATION and speakerphoneOn false"); AppMethodBeat.o(66575); } else if (this.j == null) { AppMethodBeat.o(66575); } else if (i == TXEAudioDef.TXE_AUDIO_MODE_RECEIVER) { this.j.setMode(3); this.j.setSpeakerphoneOn(false); TXCLog.i(this.a, "AudioCenter setAudioMode to receiver, MODE_IN_COMMUNICATION, speakerphoneOn false"); AppMethodBeat.o(66575); } else { this.j.setMode(0); this.j.setSpeakerphoneOn(true); TXCLog.i(this.a, "AudioCenter setAudioMode to speaker, MODE_NORMAL, speakerphoneOn true"); AppMethodBeat.o(66575); } } public synchronized void a(d dVar) { AppMethodBeat.i(66576); if (dVar == null) { AppMethodBeat.o(66576); } else { this.f.add(dVar); if (this.h) { dVar.OnHeadsetState(true); AppMethodBeat.o(66576); } else if (this.e == null || this.j == null || !this.j.isBluetoothScoOn()) { dVar.OnHeadsetState(false); AppMethodBeat.o(66576); } else { dVar.OnHeadsetState(true); AppMethodBeat.o(66576); } } } public synchronized void b(d dVar) { AppMethodBeat.i(66577); if (dVar == null) { AppMethodBeat.o(66577); } else { this.f.remove(dVar); AppMethodBeat.o(66577); } } private synchronized void a(boolean z) { AppMethodBeat.i(66578); for (d OnHeadsetState : this.f) { OnHeadsetState.OnHeadsetState(z); } AppMethodBeat.o(66578); } public void b(int i) { AppMethodBeat.i(66579); TXCLog.i(this.a, "onCallStateChanged, state = ".concat(String.valueOf(i))); if (this.j.isBluetoothScoAvailableOffCall()) { if (!(i != 0 || this.e == null || this.j.isBluetoothScoOn())) { TXCLog.i(this.a, "to restartBluetoothSco"); this.g.postDelayed(new Runnable() { public void run() { AppMethodBeat.i(66543); a.this.j.startBluetoothSco(); AppMethodBeat.o(66543); } }, 1000); } AppMethodBeat.o(66579); return; } TXCLog.e(this.a, "not support BTHeadset sco"); AppMethodBeat.o(66579); } }
12,058
0.536413
0.508792
334
35.09581
24.317938
157
false
false
0
0
0
0
0
0
0.766467
false
false
2
5066c3f04acf8ec4f148df476d08e4fe7c5fdf30
27,195,732,953,326
04e4b0b110bd27d9205a110b54cd33f9b467e533
/src/main/java/ru/breffi/storyclmsdk/Models/StorySimpleTable.java
c2457886bfb9531a971bc5a89ea025c29b1dc154
[ "MIT" ]
permissive
storyclm/Java-SDK
https://github.com/storyclm/Java-SDK
25a2b5cdbdea84e49caedf8f0fee36caa237374a
7d56c3e46bd7c69394c84af142b3af7be0e7c304
refs/heads/master
2021-01-20T07:36:33.607000
2017-12-25T17:41:51
2017-12-25T17:41:51
90,017,861
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.breffi.storyclmsdk.Models; public class StorySimpleTable { public int id; public String name; }
UTF-8
Java
121
java
StorySimpleTable.java
Java
[]
null
[]
package ru.breffi.storyclmsdk.Models; public class StorySimpleTable { public int id; public String name; }
121
0.710744
0.710744
6
18.166666
14.040616
37
false
false
0
0
0
0
0
0
0.666667
false
false
2
588cd54f23ecf1784fbe98bd5e187556a1973634
22,874,995,868,063
2f3c264b2ec5b74ec5f701c47238c1898845858c
/spring-helper-web/src/test/java/com/github/gcorporationcare/notest/entity/PersonTagAuthor.java
b4f31ca75fa6d2fad5847a69bcfbb129967a91d7
[]
no_license
gcorporationcare/spring-helper
https://github.com/gcorporationcare/spring-helper
92565df411154a7586524bdb8a759831b628c6b9
b288d369ea1723f3305e4bfa803ff55397ab2c0d
refs/heads/master
2023-06-01T04:07:33.988000
2021-06-03T13:36:05
2021-06-03T13:36:05
340,679,284
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.gcorporationcare.notest.entity; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.NotEmpty; import com.github.gcorporationcare.data.entity.BaseEmbedded; import com.github.gcorporationcare.data.field.Country; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Embeddable @NoArgsConstructor @AllArgsConstructor public class PersonTagAuthor extends BaseEmbedded { protected static final String FIRST_NAME_COLUMN = "first_name"; protected static final String LAST_NAME_COLUMN = "last_name"; protected static final String COUNTRY_COLUMN = "country"; private static final long serialVersionUID = 1L; // ------------------------------------------------- @NotEmpty @Column(name = PersonTagAuthor.FIRST_NAME_COLUMN, nullable = false) private String firstName; // ------------------------------------------------- @NotEmpty @Column(name = PersonTagAuthor.LAST_NAME_COLUMN, nullable = false) private String lastName; // ------------------------------------------------- @Column(name = PersonTagAuthor.COUNTRY_COLUMN) private Country country; @Override public void format() { // Nothing in there } }
UTF-8
Java
1,267
java
PersonTagAuthor.java
Java
[]
null
[]
package com.github.gcorporationcare.notest.entity; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.NotEmpty; import com.github.gcorporationcare.data.entity.BaseEmbedded; import com.github.gcorporationcare.data.field.Country; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Embeddable @NoArgsConstructor @AllArgsConstructor public class PersonTagAuthor extends BaseEmbedded { protected static final String FIRST_NAME_COLUMN = "first_name"; protected static final String LAST_NAME_COLUMN = "last_name"; protected static final String COUNTRY_COLUMN = "country"; private static final long serialVersionUID = 1L; // ------------------------------------------------- @NotEmpty @Column(name = PersonTagAuthor.FIRST_NAME_COLUMN, nullable = false) private String firstName; // ------------------------------------------------- @NotEmpty @Column(name = PersonTagAuthor.LAST_NAME_COLUMN, nullable = false) private String lastName; // ------------------------------------------------- @Column(name = PersonTagAuthor.COUNTRY_COLUMN) private Country country; @Override public void format() { // Nothing in there } }
1,267
0.69929
0.6985
43
28.465117
22.451342
68
false
false
0
0
0
0
0
0
0.906977
false
false
2
9be3407a50c08f36cd62942f4e49bb25686c77df
22,874,995,869,329
48cde16ac16b72164a69d1e6b301b19be884009f
/src/main/java/br/com/pos/academico/entidade/Local.java
35e44d98e62300962c835fff438b5d08b6289b39
[]
no_license
m-lib/bancas
https://github.com/m-lib/bancas
6f0fc30ef4c0f6813b6b2df289fc173017cc0130
f01ed228e134a56f4853b41a79c9132499266de7
refs/heads/master
2021-01-13T12:46:21.849000
2016-05-25T22:40:02
2016-05-25T22:40:02
33,789,380
0
13
null
false
2015-05-07T23:57:26
2015-04-11T19:34:19
2015-05-07T23:56:33
2015-05-07T23:57:26
248
0
3
0
Java
null
null
package br.com.pos.academico.entidade; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @EqualsAndHashCode(of = "codigo") public class Local { @Getter @Setter private Integer codigo; @Getter @Setter private String nome; }
UTF-8
Java
261
java
Local.java
Java
[]
null
[]
package br.com.pos.academico.entidade; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @EqualsAndHashCode(of = "codigo") public class Local { @Getter @Setter private Integer codigo; @Getter @Setter private String nome; }
261
0.762452
0.762452
16
15.3125
12.79511
38
false
false
0
0
0
0
0
0
0.75
false
false
2
d7e88b22a68fd5dd06ec9d0062f120db6b44c141
2,920,577,777,550
d3b3b63357180b88dc3e17a2fa4a6c0e3bd24a03
/app/src/main/java/com/example/smalllee/myapplication/activity/LoadDataWithDataBindingActivity.java
832e57b40193faaf21e0e70db0985f72a33d1372
[]
no_license
SmallLee/MagicBook
https://github.com/SmallLee/MagicBook
1f9dc4e27fa41cbfc957be9fd37bb5c1050d45ca
12af8262e12dbe2500df19d181d8835321a129e2
refs/heads/master
2020-04-11T15:53:12.421000
2019-04-21T15:15:47
2019-04-21T15:15:47
161,906,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.smalllee.myapplication.activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.widget.Toast; import com.example.smalllee.myapplication.R; import com.example.smalllee.myapplication.adapter.BindAdapter; import com.example.smalllee.myapplication.databinding.ActivityLoadDataWithDataBindingBinding; import com.example.smalllee.myapplication.pojo.DataBean; import com.example.smalllee.myapplication.viewmodel.DataVM; import com.example.smalllee.myapplication.viewmodel.IDataView; import java.util.List; public class LoadDataWithDataBindingActivity extends AppCompatActivity implements IDataView { ActivityLoadDataWithDataBindingBinding binding; private BindAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_load_data_with_data_binding); initRecycleView(); DataVM dataVM = new DataVM(this); dataVM.requestData(); loadDataAsync(); } public void loadDataAsync() { // 异步加载数据完成 reportFullyDrawn(); } public void initRecycleView() { LinearLayoutManager layoutManager = new LinearLayoutManager(this); binding.recView.setLayoutManager(layoutManager); adapter = new BindAdapter(this); binding.recView.setAdapter(adapter); } @Override public void loadStart() { Toast.makeText(this,"加载开始",Toast.LENGTH_SHORT).show(); } @Override public void loadComplete() { Toast.makeText(this,"加载结束",Toast.LENGTH_SHORT).show(); } @Override public void onGetData(List<DataBean> beanList) { adapter.refreshData(beanList); } }
UTF-8
Java
1,919
java
LoadDataWithDataBindingActivity.java
Java
[]
null
[]
package com.example.smalllee.myapplication.activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.widget.Toast; import com.example.smalllee.myapplication.R; import com.example.smalllee.myapplication.adapter.BindAdapter; import com.example.smalllee.myapplication.databinding.ActivityLoadDataWithDataBindingBinding; import com.example.smalllee.myapplication.pojo.DataBean; import com.example.smalllee.myapplication.viewmodel.DataVM; import com.example.smalllee.myapplication.viewmodel.IDataView; import java.util.List; public class LoadDataWithDataBindingActivity extends AppCompatActivity implements IDataView { ActivityLoadDataWithDataBindingBinding binding; private BindAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_load_data_with_data_binding); initRecycleView(); DataVM dataVM = new DataVM(this); dataVM.requestData(); loadDataAsync(); } public void loadDataAsync() { // 异步加载数据完成 reportFullyDrawn(); } public void initRecycleView() { LinearLayoutManager layoutManager = new LinearLayoutManager(this); binding.recView.setLayoutManager(layoutManager); adapter = new BindAdapter(this); binding.recView.setAdapter(adapter); } @Override public void loadStart() { Toast.makeText(this,"加载开始",Toast.LENGTH_SHORT).show(); } @Override public void loadComplete() { Toast.makeText(this,"加载结束",Toast.LENGTH_SHORT).show(); } @Override public void onGetData(List<DataBean> beanList) { adapter.refreshData(beanList); } }
1,919
0.741918
0.740858
58
31.534483
26.289644
101
false
false
0
0
0
0
0
0
0.586207
false
false
2
78860def4a58d2804b58725e67f6e808bfff0732
26,465,588,529,769
8cb99653e405787b65f41ce68da883b71f9f6c57
/src/main/java/ucj/service/GameService.java
e6b5ff59e05c86665d880513e5c99956647a3e59
[]
no_license
aaadipop/ucj
https://github.com/aaadipop/ucj
0af9dfb2062a4d46215d51c575b023d184c32d5a
2bbc513e874eb895c675517f906b2cc298939186
refs/heads/master
2016-09-08T06:34:48.625000
2015-11-25T11:40:48
2015-11-25T11:41:13
35,539,917
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package ucj.service; import java.util.Date; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import ucj.component.DateConverter; import ucj.component.Parser; import ucj.component.SecurityService; import ucj.entity.Game; import ucj.entity.Notification; import ucj.entity.Team; import ucj.repository.GameRepository; import ucj.repository.NotificationRepository; @Service @Transactional public class GameService { @Autowired private GameRepository gameRepository; @Autowired private GuestService guestService; @Autowired private TeamService teamSerice; @Autowired private LocationService locationService; @Autowired private DateConverter dateConverter; @Autowired private NotificationService notificationService; @Autowired private NotificationRepository notificationRepository; @Autowired private Parser parser; @Autowired private SecurityService securityService; public void save(Game g) { gameRepository.save(g); } public void delete(int id) { Game g = gameRepository.getOne(id); gameRepository.deleteNotification(g); gameRepository.delete(id); } public void update(Game g) { gameRepository.save(g); } public void save(Game game, int guestId, int teamId, int locationId) { game.setGuest(guestService.findOne(guestId)); game.setLocation(locationService.findOne(locationId)); game.setTeam(teamSerice.findOne(teamId)); gameRepository.save(game); } public Page<Game> findAll(Pageable pageable) { return gameRepository.findAll(pageable); } public Game findOne(int id) { return gameRepository.findOne(id); } public List<Game> findAllUnnotified(Date date) { List<Game> games = gameRepository.findAllUnnotified(date); for (Game g : games) { g.setAwaitingNotification(false); gameRepository.save(g); } return games; } public void save(Game game, int guestId, int teamId, int locationId, String date) { game.setDate(dateConverter.convert(date)); System.out.println(dateConverter.convert(date)); game.setGuest(guestService.findOne(guestId)); game.setLocation(locationService.findOne(locationId)); game.setTeam(teamSerice.findOne(teamId)); gameRepository.save(game); } public List<Game> findLiveScores(Date today, Date yesterday) { List<Game> games = gameRepository.findLiveScores(today, yesterday); for (Game g : games) { g.setAwaitingNotification(false); gameRepository.save(g); } return games; } public List<Game> findByTeam(Team team, PageRequest pageRequest) { return gameRepository.findByTeam(team, pageRequest).getContent(); } public List<Game> findFinishedGamesByTeam(Team team, PageRequest pageRequest) { return gameRepository.findFinishedGamesByTeam(team, pageRequest) .getContent(); } public List<Game> findGamesBetween(Date d, Date dd) { // TODO Auto-generated method stub return gameRepository.findGamesBetween(d, dd); } public List<Game> findByTeam(Team team, PageRequest pageRequest, Date date) { return null; } public List<Game> findAllFinished(Pageable page) { List<Game> games = gameRepository.findAllFinished(page).getContent(); return games; } public List<Game> findAllUnfinishedDerbys(PageRequest pageRequest) { return gameRepository.findAllUnfinishedDerby(pageRequest).getContent(); } public List<Game> findAllFinishedGames(PageRequest pageRequest) { return gameRepository.findAllFinishedGames(pageRequest).getContent(); } public List<Game> findFutureGames(PageRequest pageRequest, Team team) { return gameRepository.findFutureGames(team, pageRequest).getContent(); } public List<Game> findFutureGames(PageRequest pageRequest) { return gameRepository.findFutureGames(pageRequest).getContent(); } public Game findLiveGame() { return gameRepository.findLiveGame(); } public List<Game> findAllUnfinished(PageRequest pageRequest) { return gameRepository.findAllUnfinished(pageRequest).getContent(); } public void save(Game game, int guestId, int teamId, int locationId, String date, String content) { game.setDate(dateConverter.convert(date)); System.out.println(dateConverter.convert(date)); game.setGuest(guestService.findOne(guestId)); game.setLocation(locationService.findOne(locationId)); game.setTeam(teamSerice.findOne(teamId)); game.setContent(content); game.setSubContent(parser.removeHtmlTags(content)); gameRepository.save(game); } public Page<Game> findAllForUser(PageRequest pageRequest) { int teamId = securityService.getSecurityUserTeamId(); return gameRepository.findAll(teamId,pageRequest); } }
UTF-8
Java
4,837
java
GameService.java
Java
[]
null
[]
package ucj.service; import java.util.Date; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import ucj.component.DateConverter; import ucj.component.Parser; import ucj.component.SecurityService; import ucj.entity.Game; import ucj.entity.Notification; import ucj.entity.Team; import ucj.repository.GameRepository; import ucj.repository.NotificationRepository; @Service @Transactional public class GameService { @Autowired private GameRepository gameRepository; @Autowired private GuestService guestService; @Autowired private TeamService teamSerice; @Autowired private LocationService locationService; @Autowired private DateConverter dateConverter; @Autowired private NotificationService notificationService; @Autowired private NotificationRepository notificationRepository; @Autowired private Parser parser; @Autowired private SecurityService securityService; public void save(Game g) { gameRepository.save(g); } public void delete(int id) { Game g = gameRepository.getOne(id); gameRepository.deleteNotification(g); gameRepository.delete(id); } public void update(Game g) { gameRepository.save(g); } public void save(Game game, int guestId, int teamId, int locationId) { game.setGuest(guestService.findOne(guestId)); game.setLocation(locationService.findOne(locationId)); game.setTeam(teamSerice.findOne(teamId)); gameRepository.save(game); } public Page<Game> findAll(Pageable pageable) { return gameRepository.findAll(pageable); } public Game findOne(int id) { return gameRepository.findOne(id); } public List<Game> findAllUnnotified(Date date) { List<Game> games = gameRepository.findAllUnnotified(date); for (Game g : games) { g.setAwaitingNotification(false); gameRepository.save(g); } return games; } public void save(Game game, int guestId, int teamId, int locationId, String date) { game.setDate(dateConverter.convert(date)); System.out.println(dateConverter.convert(date)); game.setGuest(guestService.findOne(guestId)); game.setLocation(locationService.findOne(locationId)); game.setTeam(teamSerice.findOne(teamId)); gameRepository.save(game); } public List<Game> findLiveScores(Date today, Date yesterday) { List<Game> games = gameRepository.findLiveScores(today, yesterday); for (Game g : games) { g.setAwaitingNotification(false); gameRepository.save(g); } return games; } public List<Game> findByTeam(Team team, PageRequest pageRequest) { return gameRepository.findByTeam(team, pageRequest).getContent(); } public List<Game> findFinishedGamesByTeam(Team team, PageRequest pageRequest) { return gameRepository.findFinishedGamesByTeam(team, pageRequest) .getContent(); } public List<Game> findGamesBetween(Date d, Date dd) { // TODO Auto-generated method stub return gameRepository.findGamesBetween(d, dd); } public List<Game> findByTeam(Team team, PageRequest pageRequest, Date date) { return null; } public List<Game> findAllFinished(Pageable page) { List<Game> games = gameRepository.findAllFinished(page).getContent(); return games; } public List<Game> findAllUnfinishedDerbys(PageRequest pageRequest) { return gameRepository.findAllUnfinishedDerby(pageRequest).getContent(); } public List<Game> findAllFinishedGames(PageRequest pageRequest) { return gameRepository.findAllFinishedGames(pageRequest).getContent(); } public List<Game> findFutureGames(PageRequest pageRequest, Team team) { return gameRepository.findFutureGames(team, pageRequest).getContent(); } public List<Game> findFutureGames(PageRequest pageRequest) { return gameRepository.findFutureGames(pageRequest).getContent(); } public Game findLiveGame() { return gameRepository.findLiveGame(); } public List<Game> findAllUnfinished(PageRequest pageRequest) { return gameRepository.findAllUnfinished(pageRequest).getContent(); } public void save(Game game, int guestId, int teamId, int locationId, String date, String content) { game.setDate(dateConverter.convert(date)); System.out.println(dateConverter.convert(date)); game.setGuest(guestService.findOne(guestId)); game.setLocation(locationService.findOne(locationId)); game.setTeam(teamSerice.findOne(teamId)); game.setContent(content); game.setSubContent(parser.removeHtmlTags(content)); gameRepository.save(game); } public Page<Game> findAllForUser(PageRequest pageRequest) { int teamId = securityService.getSecurityUserTeamId(); return gameRepository.findAll(teamId,pageRequest); } }
4,837
0.77486
0.77486
192
24.192709
24.375307
80
false
false
0
0
0
0
0
0
1.5
false
false
2
9ec1ee64251dd9e6a265be1515a11955acc3d5dc
3,341,484,574,618
caa278ba784f9d39ef8e7f07caa66c1f8660706e
/de.htwg.se.texasholdem/src/de/htwg/se/texasholdem/model/db4oDatabase.java
71d14a6a5e3f2d9c6e6d24245b5f064600d8e3f3
[]
no_license
japanske/SWAR
https://github.com/japanske/SWAR
32053e07af41f6e2999b80ee632ef8a203335c0b
5dd1c7173530a8bc89546ed1506c45b788189285
refs/heads/master
2016-08-10T19:32:18.429000
2016-04-01T10:50:26
2016-04-01T10:50:26
54,557,816
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.htwg.se.texasholdem.model; import com.db4o.Db4oEmbedded; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; public class db4oDatabase implements DAO{ //access db4o ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded .newConfiguration(), "Test_Database"); public void write(Object object) { try{ db.store(object); System.out.println("Stored " + object); } finally{ db.close(); } } public void read(ObjectSet<?> result) { try{ System.out.println(result.size());; while(result.hasNext()){ System.out.println(result.next()); } } finally { db.close(); } } public void update(Object object) { try{ db.store(object); System.out.println("Updated "+ object); }finally{ db.close(); } } public void delete(Object object) { try{ db.delete(object); System.out.println("Deleted "+ object.toString()); }finally{ db.close(); } } }
UTF-8
Java
986
java
db4oDatabase.java
Java
[]
null
[]
package de.htwg.se.texasholdem.model; import com.db4o.Db4oEmbedded; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; public class db4oDatabase implements DAO{ //access db4o ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded .newConfiguration(), "Test_Database"); public void write(Object object) { try{ db.store(object); System.out.println("Stored " + object); } finally{ db.close(); } } public void read(ObjectSet<?> result) { try{ System.out.println(result.size());; while(result.hasNext()){ System.out.println(result.next()); } } finally { db.close(); } } public void update(Object object) { try{ db.store(object); System.out.println("Updated "+ object); }finally{ db.close(); } } public void delete(Object object) { try{ db.delete(object); System.out.println("Deleted "+ object.toString()); }finally{ db.close(); } } }
986
0.621704
0.61359
52
16.961538
16.317713
56
false
false
0
0
0
0
0
0
2
false
false
2
662fb69131f9945a3734e915e6b3c824d6adc0b7
25,305,947,342,757
27c23b58bea012a982c9a8fec5120774fe790d08
/src/Implementations/ImplementationAbstract.java
09ea6b93cdfd2a6751158b2b86ff10b7c481a9c3
[]
no_license
GenericIndieGroup3/SpaceProj
https://github.com/GenericIndieGroup3/SpaceProj
19eaf985560b07f16d2a850ac1acd1de116c13eb
bf615dd63334690485d12ee89f2e8e3f9a44b208
refs/heads/master
2016-09-01T17:39:01.745000
2015-02-13T04:33:21
2015-02-13T04:33:21
30,556,086
1
0
null
false
2015-03-05T20:35:36
2015-02-09T20:14:12
2015-02-13T04:34:23
2015-03-05T20:35:36
460
1
0
0
Java
null
null
package Implementations; import Games.GameInterface; import Structs.Circle; import Structs.Point; import Structs.Polygon; import Structs.Shape; import Structs.Vector2; public abstract class ImplementationAbstract { protected Vector2 screenDimensions; protected double unitToPixelRatio; protected GameInterface game; protected int frameNum = 0; protected double deltaTime = 0.0001; protected boolean keepUpdating = true; public ImplementationAbstract(GameInterface game, Vector2 screenDimensions, double unitToPixelRatio){ this.screenDimensions = screenDimensions; this.unitToPixelRatio = unitToPixelRatio; this.game = game; create(); this.game.setup(); beginUpdating(); remove(); } public void beginUpdating(){ while(keepUpdating){ update(); //TODO add logic to skip draw cycles every now and then if lagging draw(this.game.drawShapes()); } } //If this is overriden, make sure to call it in the override method public void update(){ frameNum++; //TODO calculate deltaTime deltaTime = 0.0001; input(); game.update(frameNum, deltaTime); } public void draw(Shape[] shapes){ clear(); for(Shape s : shapes){ if( s instanceof Circle ) circle((Circle) s); else if(s instanceof Polygon) polygon((Polygon) s); else if(s instanceof Point) point((Point) s); else{ //unimplemented shape } } flip(); } public abstract void create(); //Somehowreaddata from this public abstract void input(); public abstract void remove(); public abstract void clear(); public abstract void point(Point p); public abstract void polygon(Polygon p); public abstract void circle(Circle c); public abstract void flip(); }
UTF-8
Java
1,723
java
ImplementationAbstract.java
Java
[]
null
[]
package Implementations; import Games.GameInterface; import Structs.Circle; import Structs.Point; import Structs.Polygon; import Structs.Shape; import Structs.Vector2; public abstract class ImplementationAbstract { protected Vector2 screenDimensions; protected double unitToPixelRatio; protected GameInterface game; protected int frameNum = 0; protected double deltaTime = 0.0001; protected boolean keepUpdating = true; public ImplementationAbstract(GameInterface game, Vector2 screenDimensions, double unitToPixelRatio){ this.screenDimensions = screenDimensions; this.unitToPixelRatio = unitToPixelRatio; this.game = game; create(); this.game.setup(); beginUpdating(); remove(); } public void beginUpdating(){ while(keepUpdating){ update(); //TODO add logic to skip draw cycles every now and then if lagging draw(this.game.drawShapes()); } } //If this is overriden, make sure to call it in the override method public void update(){ frameNum++; //TODO calculate deltaTime deltaTime = 0.0001; input(); game.update(frameNum, deltaTime); } public void draw(Shape[] shapes){ clear(); for(Shape s : shapes){ if( s instanceof Circle ) circle((Circle) s); else if(s instanceof Polygon) polygon((Polygon) s); else if(s instanceof Point) point((Point) s); else{ //unimplemented shape } } flip(); } public abstract void create(); //Somehowreaddata from this public abstract void input(); public abstract void remove(); public abstract void clear(); public abstract void point(Point p); public abstract void polygon(Polygon p); public abstract void circle(Circle c); public abstract void flip(); }
1,723
0.717353
0.709228
80
20.5375
18.23797
102
false
false
0
0
0
0
0
0
2.025
false
false
2
aad8ae9db8e256b070e6ac5a12eba8e2d32d0b36
6,150,393,190,383
203e03e74f217e42ee2fc337762dce8144fd91a9
/NextPosition.java
f01b535c018242792942a811b37ae01b692e2846
[]
no_license
yusuf-bahadur/Miner-Game
https://github.com/yusuf-bahadur/Miner-Game
d695154176df7df5178a7641e367d8de72722ad5
710938f324adeb13dcbe86e78214b3f5cd3f5eb0
refs/heads/master
2021-09-01T15:54:46.890000
2017-12-27T20:45:10
2017-12-27T20:45:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface NextPosition { }
UTF-8
Java
34
java
NextPosition.java
Java
[]
null
[]
public interface NextPosition { }
34
0.794118
0.794118
2
16
15
31
false
false
0
0
0
0
0
0
0
false
false
2
aca45f6c31089ec57703fa19eee7e238215f7fb2
28,475,633,202,183
5765c87fd41493dff2fde2a68f9dccc04c1ad2bd
/Variant Programs/1-5/3/looked/DayCaretaker.java
cdbb93275c78c2c4c38f843a4d1f1e1e47957e3a
[ "MIT" ]
permissive
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
https://github.com/hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
42e4c2061c3f8da0dfce760e168bb9715063645f
a42ced1d5a92963207e3565860cac0946312e1b3
refs/heads/master
2020-08-09T08:10:08.888000
2019-11-25T01:14:23
2019-11-25T01:14:23
214,041,532
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package looked; public class DayCaretaker { public DayCaretaker() { this.contemporaryMoment = 0; } public static looked.DayCaretaker relayedPeriodsManager = null; public static synchronized double topicalPeriod() { return startConcurredMinutesNurse().producePrevalentNow(); } public synchronized void soarTcs(double point) { this.contemporaryMoment = point; } public static synchronized looked.DayCaretaker startConcurredMinutesNurse() { if (relayedPeriodsManager == null) relayedPeriodsManager = new looked.DayCaretaker(); return relayedPeriodsManager; } public static synchronized void placeWeek(double pinpoint) { startConcurredMinutesNurse().soarTcs(pinpoint); } public double contemporaryMoment = 0.0; public synchronized double producePrevalentNow() { return this.contemporaryMoment; } }
UTF-8
Java
861
java
DayCaretaker.java
Java
[]
null
[]
package looked; public class DayCaretaker { public DayCaretaker() { this.contemporaryMoment = 0; } public static looked.DayCaretaker relayedPeriodsManager = null; public static synchronized double topicalPeriod() { return startConcurredMinutesNurse().producePrevalentNow(); } public synchronized void soarTcs(double point) { this.contemporaryMoment = point; } public static synchronized looked.DayCaretaker startConcurredMinutesNurse() { if (relayedPeriodsManager == null) relayedPeriodsManager = new looked.DayCaretaker(); return relayedPeriodsManager; } public static synchronized void placeWeek(double pinpoint) { startConcurredMinutesNurse().soarTcs(pinpoint); } public double contemporaryMoment = 0.0; public synchronized double producePrevalentNow() { return this.contemporaryMoment; } }
861
0.757259
0.753775
35
23.6
26.803198
89
false
false
0
0
0
0
0
0
0.285714
false
false
2
dad05b277c5e59852ae1635b552189e32b78e28b
27,444,841,084,364
9afd25c2ab1f83f13ffbf283439f13a5080c75cb
/WebQuiz/src/database/TableNames.java
717f3ae695baa5c90e09f072d04def563e8fa0b4
[]
no_license
shanshuo0918/QuizWebsite
https://github.com/shanshuo0918/QuizWebsite
ccfa2ab1544afab53977a393c5fa2e35e5e5a77b
cf3cba5b001aadfb84f72c5000819722e53ea06d
refs/heads/master
2016-09-06T05:16:59.881000
2015-08-31T21:13:57
2015-08-31T21:13:57
41,700,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package database; public class TableNames { public static final String ANNOUNCE_TB = "announcement"; public static final String QUIZ_SUM_TB = "quiz_summary"; public static final String QUIZ_HIST_TB = "quiz_history"; public static final String USERINFO_TB = "userinfo"; public static final String FRIEND_LIST_TB = "friend_list"; public static final String FRIEND_REQ_TB = "friend_request"; }
UTF-8
Java
408
java
TableNames.java
Java
[]
null
[]
package database; public class TableNames { public static final String ANNOUNCE_TB = "announcement"; public static final String QUIZ_SUM_TB = "quiz_summary"; public static final String QUIZ_HIST_TB = "quiz_history"; public static final String USERINFO_TB = "userinfo"; public static final String FRIEND_LIST_TB = "friend_list"; public static final String FRIEND_REQ_TB = "friend_request"; }
408
0.737745
0.737745
10
38.799999
23.944937
61
false
false
0
0
0
0
0
0
1.3
false
false
2
eec93aa158b5e9e4d880ef7058678a1eb9d316d2
29,265,907,211,358
d495cb1f56ad9eae635ac859b3125ab3151f39e4
/Apollo/ApolloTest/src/com/dnwiebe/apollo/util/CannedBitmapSource.java
5b21c0600fcf89ed7058aa689150dc39a3e6b33c
[]
no_license
dnwiebe/Apollo
https://github.com/dnwiebe/Apollo
064fc61b0f1a5c59a116f6340f22513cc9572250
db76696e7de6c5a2c4bf0433fa69b7b179e39015
HEAD
2016-09-09T19:57:25.518000
2015-04-16T02:55:00
2015-04-16T02:55:00
34,030,942
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dnwiebe.apollo.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.dnwiebe.apollo.model.hardware.BitmapSource; /** * Created by dnwiebe on 3/4/15. */ public class CannedBitmapSource implements BitmapSource { private Context context; private int[] resourceIds; private int idx; private Runnable onCompletion; public CannedBitmapSource (Context context, Runnable onCompletion, int... resourceIds) { this.context = context; this.resourceIds = resourceIds; this.idx = 0; this.onCompletion = onCompletion; } @Override public boolean open () {return true;} @Override public void close () {} @Override public Bitmap capture () { if (idx >= resourceIds.length) { if (onCompletion != null) { onCompletion.run (); onCompletion = null; return Bitmap.createBitmap (10, 10, Bitmap.Config.RGB_565); } else { throw new UnsupportedOperationException ("No more bitmaps"); } } Drawable drawable = context.getResources().getDrawable(resourceIds[idx++]); return ((BitmapDrawable) drawable).getBitmap(); } }
UTF-8
Java
1,436
java
CannedBitmapSource.java
Java
[ { "context": "lo.model.hardware.BitmapSource;\n\n/**\n * Created by dnwiebe on 3/4/15.\n */\npublic class CannedBitmapSource im", "end": 350, "score": 0.9996713399887085, "start": 343, "tag": "USERNAME", "value": "dnwiebe" } ]
null
[]
package com.dnwiebe.apollo.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.dnwiebe.apollo.model.hardware.BitmapSource; /** * Created by dnwiebe on 3/4/15. */ public class CannedBitmapSource implements BitmapSource { private Context context; private int[] resourceIds; private int idx; private Runnable onCompletion; public CannedBitmapSource (Context context, Runnable onCompletion, int... resourceIds) { this.context = context; this.resourceIds = resourceIds; this.idx = 0; this.onCompletion = onCompletion; } @Override public boolean open () {return true;} @Override public void close () {} @Override public Bitmap capture () { if (idx >= resourceIds.length) { if (onCompletion != null) { onCompletion.run (); onCompletion = null; return Bitmap.createBitmap (10, 10, Bitmap.Config.RGB_565); } else { throw new UnsupportedOperationException ("No more bitmaps"); } } Drawable drawable = context.getResources().getDrawable(resourceIds[idx++]); return ((BitmapDrawable) drawable).getBitmap(); } }
1,436
0.651811
0.643454
49
28.306122
23.04229
92
false
false
0
0
0
0
0
0
0.55102
false
false
2
2cd50540db223b52b1e355db881fc3ba7bc058e6
8,907,762,220,077
a63846f2390e77a64be8b579bf94fd0db788acca
/app/src/main/java/com/jim/robotos_v2/Utilities/Preferences.java
3573053f12f94c1281c9030077d4edf9b946cc65
[ "Apache-2.0" ]
permissive
DimitrisKaltzidis/Project-Diploma-Thesis
https://github.com/DimitrisKaltzidis/Project-Diploma-Thesis
bc59cf00a6da36917722b7fcfced07ef083efa19
ed08e43a79486793cad97d51859510a1efe20e50
refs/heads/master
2021-10-19T10:15:58.952000
2019-02-20T08:32:04
2019-02-20T08:32:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jim.robotos_v2.Utilities; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import java.util.ArrayList; import java.util.List; /** * Created by Jim on 25/1/2015. */ public class Preferences { /*AVAILABLE PREFERENCES * * //obstacle avoidance * OBSTACLE_AVOIDING_BEARING_ERROR_RANGE_DEGREES /// Moires pou prostithontai stin gwnia apofigis empodiou se periptwsi lathous * OBSTACLE_AVOIDING_MAP_ERROR_METERS /// metra pou prostithontai stin apostasi apofigis tou empodiou logo pithanis asimfwnias xarti pragmatikotitas * OBSTACLE_DETECTION_RANGE /// sta posa metra thewrw oti exw anixneusei ena empodio * * BEARING_RANGE /// Moires +/- tis gwnias stin opoia vriskete to epomeno simeio stin diadromi * DISTANCE_ERROR_RANGE /// Metra apoklisis tou xarti me tin pragmatikotita gia na theorisw oti exw episkeftei ena shmeio * * COMMUNICATION_LOOP_REPEAT_TIME /// xronos gia to pote to Thread pou apofasizei tin poreia prepei na ekteleite * BOTTOM_LINE_VALUE /// to ipsos tis grammis sto Color detection * DISTANCE_TO_STOP_FROM_OBSTACLE_CM /// Color detection activity distance to stop if an a object is in front of the sensor * * */ @SuppressLint("LongLogTag") static public void savePrefsString(String toBeSaved, String valueToBeSaved, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString(toBeSaved, valueToBeSaved); edit.commit(); // Log.e("Execute Preference Command", "SAVE STRING PREFERENCE '" + toBeSaved + "' WITH VALUE '" + valueToBeSaved + "'"); } @SuppressLint("LongLogTag") static public void savePrefsInt(String toBeSaved, int valueToBeSaved, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putInt(toBeSaved, valueToBeSaved); edit.commit(); // Log.e("Execute Preference Command", "SAVE INT PREFERENCE '" + toBeSaved + "' WITH VALUE '" + valueToBeSaved + "'"); } @SuppressLint("LongLogTag") static public void savePrefsFloat(String toBeSaved, float valueToBeSaved, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putFloat(toBeSaved, valueToBeSaved); edit.commit(); // Log.e("Execute Preference Command", "SAVE FLOAT PREFERENCE '" + toBeSaved + "' WITH VALUE '" + valueToBeSaved + "'"); } @SuppressLint("LongLogTag") static public float loadPrefsFloat(String name, float defaultValue, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); float value = sharedPreferences.getFloat(name, defaultValue); // Log.e("Execute Preference Command", "LOAD FLOAT PREFERENCE '" + name + "' WITH VALUE '" + value + "'"); return value; } @SuppressLint("LongLogTag") static public String loadPrefsString(String name, String defaultValue, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); String value = sharedPreferences.getString(name, defaultValue); // Log.e("Execute Preference Command", "LOAD STRING PREFERENCE '" + name + "' WITH VALUE '" + value + "'"); return value; } @SuppressLint("LongLogTag") static public int loadPrefsInt(String name, int defaultValue, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); int value = sharedPreferences.getInt(name, defaultValue); // Log.e("Execute Preference Command", "LOAD INT PREFERENCE '" + name + "' WITH VALUE '" + value + "'"); return value; } @SuppressLint("LongLogTag") public static void writeList(Context context, List<String> list, String prefix) { SharedPreferences prefs = context.getSharedPreferences( "com.tardis.ordersamos", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); int size = prefs.getInt(prefix + "_size", 0); // clear the previous data if exists for (int i = 0; i < size; i++) editor.remove(prefix + "_" + i); // write the current list for (int i = 0; i < list.size(); i++) editor.putString(prefix + "_" + i, list.get(i)); editor.putInt(prefix + "_size", list.size()); editor.commit(); // Log.e("Execute Preference Command", "WRITE LIST"); } @SuppressLint("LongLogTag") public static List<String> readList(Context context, String prefix) { SharedPreferences prefs = context.getSharedPreferences( "com.tardis.ordersamos", Context.MODE_PRIVATE); int size = prefs.getInt(prefix + "_size", 0); List<String> data = new ArrayList<String>(size); for (int i = 0; i < size; i++) data.add(prefs.getString(prefix + "_" + i, null)); // Log.e("Execute Preference Command", "READ LIST"); return data; } @SuppressLint("LongLogTag") public static void saveListIntValuesToPreferencesWithPrefix(Context context, List<String> listToBeSaved, String prefix) { for (int i = 0; i < listToBeSaved.size(); i++) { try { if ((Preferences.loadPrefsInt(listToBeSaved.get(i) + prefix, -1, context) == -1)) { Preferences.savePrefsInt(listToBeSaved.get(i) + prefix, 0, context); // Log.e("Execute Preference Command", "WRITE NAME "+listToBeSaved.get(i)+" FROM LIST WITH VALUE '0'"); } } catch (Exception e) { // Log.e("ERROR","Execute Preference Command from 'saveListIntValuesToPreferencesWithPrefix' Method"); } } } }
UTF-8
Java
6,506
java
Preferences.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Jim on 25/1/2015.\n */\npublic class Preferences {\n\n ", "end": 272, "score": 0.9936002492904663, "start": 269, "tag": "NAME", "value": "Jim" } ]
null
[]
package com.jim.robotos_v2.Utilities; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import java.util.ArrayList; import java.util.List; /** * Created by Jim on 25/1/2015. */ public class Preferences { /*AVAILABLE PREFERENCES * * //obstacle avoidance * OBSTACLE_AVOIDING_BEARING_ERROR_RANGE_DEGREES /// Moires pou prostithontai stin gwnia apofigis empodiou se periptwsi lathous * OBSTACLE_AVOIDING_MAP_ERROR_METERS /// metra pou prostithontai stin apostasi apofigis tou empodiou logo pithanis asimfwnias xarti pragmatikotitas * OBSTACLE_DETECTION_RANGE /// sta posa metra thewrw oti exw anixneusei ena empodio * * BEARING_RANGE /// Moires +/- tis gwnias stin opoia vriskete to epomeno simeio stin diadromi * DISTANCE_ERROR_RANGE /// Metra apoklisis tou xarti me tin pragmatikotita gia na theorisw oti exw episkeftei ena shmeio * * COMMUNICATION_LOOP_REPEAT_TIME /// xronos gia to pote to Thread pou apofasizei tin poreia prepei na ekteleite * BOTTOM_LINE_VALUE /// to ipsos tis grammis sto Color detection * DISTANCE_TO_STOP_FROM_OBSTACLE_CM /// Color detection activity distance to stop if an a object is in front of the sensor * * */ @SuppressLint("LongLogTag") static public void savePrefsString(String toBeSaved, String valueToBeSaved, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString(toBeSaved, valueToBeSaved); edit.commit(); // Log.e("Execute Preference Command", "SAVE STRING PREFERENCE '" + toBeSaved + "' WITH VALUE '" + valueToBeSaved + "'"); } @SuppressLint("LongLogTag") static public void savePrefsInt(String toBeSaved, int valueToBeSaved, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putInt(toBeSaved, valueToBeSaved); edit.commit(); // Log.e("Execute Preference Command", "SAVE INT PREFERENCE '" + toBeSaved + "' WITH VALUE '" + valueToBeSaved + "'"); } @SuppressLint("LongLogTag") static public void savePrefsFloat(String toBeSaved, float valueToBeSaved, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putFloat(toBeSaved, valueToBeSaved); edit.commit(); // Log.e("Execute Preference Command", "SAVE FLOAT PREFERENCE '" + toBeSaved + "' WITH VALUE '" + valueToBeSaved + "'"); } @SuppressLint("LongLogTag") static public float loadPrefsFloat(String name, float defaultValue, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); float value = sharedPreferences.getFloat(name, defaultValue); // Log.e("Execute Preference Command", "LOAD FLOAT PREFERENCE '" + name + "' WITH VALUE '" + value + "'"); return value; } @SuppressLint("LongLogTag") static public String loadPrefsString(String name, String defaultValue, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); String value = sharedPreferences.getString(name, defaultValue); // Log.e("Execute Preference Command", "LOAD STRING PREFERENCE '" + name + "' WITH VALUE '" + value + "'"); return value; } @SuppressLint("LongLogTag") static public int loadPrefsInt(String name, int defaultValue, Context context) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); int value = sharedPreferences.getInt(name, defaultValue); // Log.e("Execute Preference Command", "LOAD INT PREFERENCE '" + name + "' WITH VALUE '" + value + "'"); return value; } @SuppressLint("LongLogTag") public static void writeList(Context context, List<String> list, String prefix) { SharedPreferences prefs = context.getSharedPreferences( "com.tardis.ordersamos", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); int size = prefs.getInt(prefix + "_size", 0); // clear the previous data if exists for (int i = 0; i < size; i++) editor.remove(prefix + "_" + i); // write the current list for (int i = 0; i < list.size(); i++) editor.putString(prefix + "_" + i, list.get(i)); editor.putInt(prefix + "_size", list.size()); editor.commit(); // Log.e("Execute Preference Command", "WRITE LIST"); } @SuppressLint("LongLogTag") public static List<String> readList(Context context, String prefix) { SharedPreferences prefs = context.getSharedPreferences( "com.tardis.ordersamos", Context.MODE_PRIVATE); int size = prefs.getInt(prefix + "_size", 0); List<String> data = new ArrayList<String>(size); for (int i = 0; i < size; i++) data.add(prefs.getString(prefix + "_" + i, null)); // Log.e("Execute Preference Command", "READ LIST"); return data; } @SuppressLint("LongLogTag") public static void saveListIntValuesToPreferencesWithPrefix(Context context, List<String> listToBeSaved, String prefix) { for (int i = 0; i < listToBeSaved.size(); i++) { try { if ((Preferences.loadPrefsInt(listToBeSaved.get(i) + prefix, -1, context) == -1)) { Preferences.savePrefsInt(listToBeSaved.get(i) + prefix, 0, context); // Log.e("Execute Preference Command", "WRITE NAME "+listToBeSaved.get(i)+" FROM LIST WITH VALUE '0'"); } } catch (Exception e) { // Log.e("ERROR","Execute Preference Command from 'saveListIntValuesToPreferencesWithPrefix' Method"); } } } }
6,506
0.641254
0.638488
152
41.796051
37.076794
151
false
false
0
0
0
0
0
0
0.677632
false
false
2
fbcf5e08db289034b7be0d794302c2183ffd90d4
24,661,702,269,968
033240604a3c425d94990b65277ede4b804ca4fa
/src/main/java/com/medicine/service/impl/DiagnosisOfWeServiceImpl.java
debeb44158716ebe4fa82cb809e060d95d3b550c
[]
no_license
AndyDuFu/Medicine
https://github.com/AndyDuFu/Medicine
d624c47e8d5b6e199638131ef908211bc5fa9fad
f6d6adfa2ef209b9f995ea1c63fbeb29de7f5395
refs/heads/master
2022-08-10T23:02:40.193000
2019-10-09T12:32:08
2019-10-09T12:32:08
190,325,521
4
0
null
false
2022-07-06T20:56:41
2019-06-05T04:25:17
2022-02-09T10:17:44
2022-07-06T20:56:39
2,257
3
0
3
Java
false
false
package com.medicine.service.impl; import com.medicine.domain.attiendRecode.DiagnosisOfWe; import com.medicine.domain.repository.attiendRecode.DiagnosisOfWeRepository; import com.medicine.service.DiagnosisOfWeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DiagnosisOfWeServiceImpl implements DiagnosisOfWeService { @Autowired private DiagnosisOfWeRepository diagnosisOfWeRepository; @Override public DiagnosisOfWe save(DiagnosisOfWe diagnosisOfWe) { return diagnosisOfWeRepository.save(diagnosisOfWe); } }
UTF-8
Java
632
java
DiagnosisOfWeServiceImpl.java
Java
[]
null
[]
package com.medicine.service.impl; import com.medicine.domain.attiendRecode.DiagnosisOfWe; import com.medicine.domain.repository.attiendRecode.DiagnosisOfWeRepository; import com.medicine.service.DiagnosisOfWeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DiagnosisOfWeServiceImpl implements DiagnosisOfWeService { @Autowired private DiagnosisOfWeRepository diagnosisOfWeRepository; @Override public DiagnosisOfWe save(DiagnosisOfWe diagnosisOfWe) { return diagnosisOfWeRepository.save(diagnosisOfWe); } }
632
0.829114
0.829114
19
32.263157
27.831905
76
false
false
0
0
0
0
0
0
0.421053
false
false
2
eaa00a72c92362cb3077dad7ae515a8038e5dd5f
28,698,971,476,171
252ad9e1c9ad4c19636e0308a2e23948e897ad55
/src/main/java/com/example/demo/DemoApplication.java
317aad2c627929ec0c0be7ea2f7daa807b866e56
[]
no_license
longfeiwan1566/demo
https://github.com/longfeiwan1566/demo
17ab5758a90d8e770fa64f03c86ca940af1ebddb
807017ed690158aaf822bb0286927a5b2091f49f
refs/heads/master
2019-07-03T16:29:52.187000
2018-06-13T09:41:50
2018-06-13T09:41:50
123,056,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { // SpringApplication.run(DemoApplication.class, args); Double d1 = 1976.9; Double d2 = 1976.9; if(d1.doubleValue() != d2.doubleValue()){ System.out.println("1111111111111"); } } }
UTF-8
Java
438
java
DemoApplication.java
Java
[]
null
[]
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { // SpringApplication.run(DemoApplication.class, args); Double d1 = 1976.9; Double d2 = 1976.9; if(d1.doubleValue() != d2.doubleValue()){ System.out.println("1111111111111"); } } }
438
0.757991
0.696347
17
24.764706
21.253454
68
false
false
0
0
0
0
0
0
1.352941
false
false
2
ec33902066fa0d178449bac03a3cdcd8e87398b3
16,587,163,700,423
ecd487d029e793cbd0e2d57aa61993d61d56d9bc
/java/passc2Copy/src/stockMarket/ReplyPriceMessage.java
0ecd9eb8962007324ca50f69e10e3100f0be6017
[]
no_license
vladlep/licentavlad
https://github.com/vladlep/licentavlad
b0a445d20c340a3d21403ebe5f97adb678b3bda5
3501d004e923120a31cd66ab16238c7a92271d6c
refs/heads/master
2016-09-05T13:20:26.588000
2011-07-04T13:43:01
2011-07-04T13:43:01
32,319,175
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stockMarket; import utilities.Message; public class ReplyPriceMessage implements Message { private double price; public ReplyPriceMessage(double price) { this.price = price; } public String toString() { return this.getClass().getName()+"|"+price; } public double getPrice() { return price; } }
UTF-8
Java
352
java
ReplyPriceMessage.java
Java
[]
null
[]
package stockMarket; import utilities.Message; public class ReplyPriceMessage implements Message { private double price; public ReplyPriceMessage(double price) { this.price = price; } public String toString() { return this.getClass().getName()+"|"+price; } public double getPrice() { return price; } }
352
0.659091
0.659091
24
12.666667
15.211473
49
false
false
0
0
0
0
0
0
1.125
false
false
2
1e86039798d9f0a225fe7485e2d885e80499e6ff
26,843,545,647,734
da374a8c1b1104ab0179a544cbf0637458504a58
/mva-common/src/main/java/ch/hslu/swe/datastructures/Produkt.java
7c895b97df3363b010e066e688063d8b5ac4b849
[]
no_license
daveschafer/SWE-Project-FS18
https://github.com/daveschafer/SWE-Project-FS18
8a79e78bc6c60596c40be203e214030404d1e033
edfe15634c484874c1a68c3ae0c59bbe45e68397
refs/heads/master
2022-11-21T08:05:11.324000
2019-02-17T14:25:29
2019-02-17T14:25:29
141,566,085
0
0
null
false
2022-11-16T07:19:08
2018-07-19T10:49:25
2019-02-17T14:25:40
2022-11-16T07:19:05
1,965
0
0
7
Java
false
false
/* * 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 ch.hslu.swe.datastructures; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "ablageTablar", "beschreibung", "id", "maximalerBestand", "minimalerBestand", "name", "preis", "typCode" }) public class Produkt { @JsonProperty("ablageTablar") private AblageTablar ablageTablar; @JsonProperty("beschreibung") private String beschreibung; @JsonProperty("id") private Integer id; @JsonProperty("maximalerBestand") private Integer maximalerBestand; @JsonProperty("minimalerBestand") private Integer minimalerBestand; @JsonProperty("name") private String name; @JsonProperty("preis") private Integer preis; @JsonProperty("typCode") private String typCode; /** * * @param id ID * @param preis Preis * @param maximalerBestand Maximaler Bestand * @param ablageTablar Ablage Tablar (nr) * @param name Name * @param beschreibung Beschreibung * @param minimalerBestand minimaler Bestand * @param typCode Typcode (eindeutig) */ public Produkt(AblageTablar ablageTablar, String beschreibung, int id, int maximalerBestand, int minimalerBestand, String name, int preis, String typCode) { this.ablageTablar = ablageTablar; this.beschreibung = beschreibung; this.id = id; this.maximalerBestand = maximalerBestand; this.minimalerBestand = minimalerBestand; this.name = name; this.preis = preis; this.typCode = typCode; } //Dummy Constructor needed for JSONMapping public Produkt(){ } //Getter und Setter Methode @JsonProperty("ablageTablar") public AblageTablar getAblageTablar() { return ablageTablar; } @JsonProperty("ablageTablar") public void setAblageTablar(AblageTablar ablageTablar) { this.ablageTablar = ablageTablar; } @JsonProperty("beschreibung") public String getBeschreibung() { return beschreibung; } @JsonProperty("beschreibung") public void setBeschreibung(String beschreibung) { this.beschreibung = beschreibung; } @JsonProperty("id") public Integer getId() { return id; } @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("maximalerBestand") public Integer getMaximalerBestand() { return maximalerBestand; } @JsonProperty("maximalerBestand") public void setMaximalerBestand(Integer maximalerBestand) { this.maximalerBestand = maximalerBestand; } @JsonProperty("minimalerBestand") public Integer getMinimalerBestand() { return minimalerBestand; } @JsonProperty("minimalerBestand") public void setMinimalerBestand(Integer minimalerBestand) { this.minimalerBestand = minimalerBestand; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("preis") public int getPreis() { return preis; } @JsonProperty("preis") public void setPreis(int preis) { this.preis = preis; } @JsonProperty("typCode") public String getTypCode() { return typCode; } @JsonProperty("typCode") public void setTypCode(String typCode) { this.typCode = typCode; } }
UTF-8
Java
3,824
java
Produkt.java
Java
[]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.hslu.swe.datastructures; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "ablageTablar", "beschreibung", "id", "maximalerBestand", "minimalerBestand", "name", "preis", "typCode" }) public class Produkt { @JsonProperty("ablageTablar") private AblageTablar ablageTablar; @JsonProperty("beschreibung") private String beschreibung; @JsonProperty("id") private Integer id; @JsonProperty("maximalerBestand") private Integer maximalerBestand; @JsonProperty("minimalerBestand") private Integer minimalerBestand; @JsonProperty("name") private String name; @JsonProperty("preis") private Integer preis; @JsonProperty("typCode") private String typCode; /** * * @param id ID * @param preis Preis * @param maximalerBestand Maximaler Bestand * @param ablageTablar Ablage Tablar (nr) * @param name Name * @param beschreibung Beschreibung * @param minimalerBestand minimaler Bestand * @param typCode Typcode (eindeutig) */ public Produkt(AblageTablar ablageTablar, String beschreibung, int id, int maximalerBestand, int minimalerBestand, String name, int preis, String typCode) { this.ablageTablar = ablageTablar; this.beschreibung = beschreibung; this.id = id; this.maximalerBestand = maximalerBestand; this.minimalerBestand = minimalerBestand; this.name = name; this.preis = preis; this.typCode = typCode; } //Dummy Constructor needed for JSONMapping public Produkt(){ } //Getter und Setter Methode @JsonProperty("ablageTablar") public AblageTablar getAblageTablar() { return ablageTablar; } @JsonProperty("ablageTablar") public void setAblageTablar(AblageTablar ablageTablar) { this.ablageTablar = ablageTablar; } @JsonProperty("beschreibung") public String getBeschreibung() { return beschreibung; } @JsonProperty("beschreibung") public void setBeschreibung(String beschreibung) { this.beschreibung = beschreibung; } @JsonProperty("id") public Integer getId() { return id; } @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("maximalerBestand") public Integer getMaximalerBestand() { return maximalerBestand; } @JsonProperty("maximalerBestand") public void setMaximalerBestand(Integer maximalerBestand) { this.maximalerBestand = maximalerBestand; } @JsonProperty("minimalerBestand") public Integer getMinimalerBestand() { return minimalerBestand; } @JsonProperty("minimalerBestand") public void setMinimalerBestand(Integer minimalerBestand) { this.minimalerBestand = minimalerBestand; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("preis") public int getPreis() { return preis; } @JsonProperty("preis") public void setPreis(int preis) { this.preis = preis; } @JsonProperty("typCode") public String getTypCode() { return typCode; } @JsonProperty("typCode") public void setTypCode(String typCode) { this.typCode = typCode; } }
3,824
0.664749
0.664749
148
24.837837
20.834955
160
false
false
0
0
0
0
0
0
0.358108
false
false
2
14c427bf4daec7834387569d128fba4eb491112e
32,469,952,814,582
d15058fec18f4cd2c4d869f6a5e2fb5116215eb3
/src/main/java/com/tranzvision/gd/util/cms/entity/main/CmsChannel.java
2159a0a9ea16172484f4615c6ceb77f43516584f
[]
no_license
YujunWu-King/university
https://github.com/YujunWu-King/university
1c08118d753c870f4c3fa410f7127d910a4e3f2d
bac7c919f537153025bec9de2942f0c9890d1b7a
refs/heads/BaseLocal
2022-12-26T19:51:20.994000
2019-12-30T11:38:20
2019-12-30T11:38:20
231,065,763
0
0
null
false
2022-12-16T06:34:06
2019-12-31T09:43:56
2019-12-31T09:54:32
2022-12-16T06:34:03
72,452
0
0
16
Java
false
false
package com.tranzvision.gd.util.cms.entity.main; import com.tranzvision.gd.util.cms.entity.main.base.BaseChannel; public class CmsChannel extends BaseChannel { /** * */ private static final long serialVersionUID = 1L; }
UTF-8
Java
231
java
CmsChannel.java
Java
[]
null
[]
package com.tranzvision.gd.util.cms.entity.main; import com.tranzvision.gd.util.cms.entity.main.base.BaseChannel; public class CmsChannel extends BaseChannel { /** * */ private static final long serialVersionUID = 1L; }
231
0.748918
0.744589
12
18.25
23.941334
64
false
false
0
0
0
0
0
0
0.583333
false
false
2
56b011945609120e84b4189777d45c44b3bc5e67
16,269,336,175,778
6259a830a3d9e735e6779e41a678a71b4c27feb2
/anchor-plugin-io/src/main/java/org/anchoranalysis/plugin/io/bean/file/namer/patternspan/PatternElementOperations.java
9c61051f7dd5817d95bdfe890445127107e0fec0
[ "MIT", "Apache-2.0" ]
permissive
anchoranalysis/anchor-plugins
https://github.com/anchoranalysis/anchor-plugins
103168052419b1072d0f8cd0201dabfb7dc84f15
5817d595d171b8598ab9c0195586c5d1f83ad92e
refs/heads/master
2023-07-24T02:38:11.667000
2023-07-18T07:51:10
2023-07-18T07:51:10
240,064,307
2
0
MIT
false
2023-07-18T07:51:12
2020-02-12T16:48:04
2023-02-11T07:28:08
2023-07-18T07:51:11
197,378
2
0
6
Java
false
false
/*- * #%L * anchor-plugin-io * %% * Copyright (C) 2010 - 2021 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * 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. * #L% */ package org.anchoranalysis.plugin.io.bean.file.namer.patternspan; import com.owenfeehan.pathpatternfinder.Pattern; import com.owenfeehan.pathpatternfinder.patternelements.PatternElement; import lombok.AccessLevel; import lombok.NoArgsConstructor; /** * Operations on the elements of a pattern. * * @author Owen Feehan */ @NoArgsConstructor(access = AccessLevel.PRIVATE) class PatternElementOperations { /** * Count the number of variable-elements in the pattern. * * @param pattern the pattern whose elements are iterated over. * @return the number of elements in the pattern that are variable (i.e. not constant). */ public static int countVariableElements(Pattern pattern) { int count = 0; for (int i = 0; i < pattern.size(); i++) { if (!pattern.get(i).hasConstantValue()) { count++; } } return count; } /** * Index of the left-most variable-element in the pattern. * * @param pattern the pattern whose elements are searched * @return the index (zero-indexed) of the left-most variable element or -1 if no variable * elements exist. */ public static int indexLeftMostVariableElement(Pattern pattern) { return indexLeftMostVariableElement(pattern, 0); } /** * Index of the <code>n</code>th left-most variable-element in the pattern. * * @param pattern the pattern whose elements are searched * @param n (beginning at 0) is an index of all variable elements in the pattern * @return the index (zero-indexed) of the <code>n</code>th left-most variable element or -1 if * insufficient variable elements exist. */ public static int indexLeftMostVariableElement(Pattern pattern, int n) { int count = 0; for (int i = 0; i < pattern.size(); i++) { if (!pattern.get(i).hasConstantValue() && count++ == n) { return i; } } return -1; } /** * Index of the right-most variable-element in the pattern. * * @param pattern the pattern whose elements are searched * @return the index (zero-indexed) of the right-most variable element or -1 if no variable * elements exist. */ public static int indexRightMostVariableElement(Pattern pattern) { for (int i = (pattern.size() - 1); i >= 0; i--) { if (!pattern.get(i).hasConstantValue()) { return i; } } return -1; } /** * Extracts the constant elements greater and equal to index. * * @param index all constant elements with indices greater or equal to {@code index} are * selected * @return the selected constant elements, concatenated together as a string. */ public static String extractConstantElementsAfter(Pattern pattern, int index) { StringBuilder sb = new StringBuilder(); for (int i = index + 1; i < pattern.size(); i++) { PatternElement element = pattern.get(i); assert (element.hasConstantValue()); // The value is the same for all indexes, so we use 0 sb.append(element.valueAt(0)); } return sb.toString(); } }
UTF-8
Java
4,509
java
PatternElementOperations.java
Java
[ { "context": "nchor-plugin-io\n * %%\n * Copyright (C) 2010 - 2021 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Ro", "end": 77, "score": 0.9998825788497925, "start": 66, "tag": "NAME", "value": "Owen Feehan" }, { "context": "021 Owen Feehan, ETH Zurich, University of Zu...
null
[]
/*- * #%L * anchor-plugin-io * %% * Copyright (C) 2010 - 2021 <NAME>, ETH Zurich, University of Zurich, Hoffmann-<NAME> * %% * 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. * #L% */ package org.anchoranalysis.plugin.io.bean.file.namer.patternspan; import com.owenfeehan.pathpatternfinder.Pattern; import com.owenfeehan.pathpatternfinder.patternelements.PatternElement; import lombok.AccessLevel; import lombok.NoArgsConstructor; /** * Operations on the elements of a pattern. * * @author <NAME> */ @NoArgsConstructor(access = AccessLevel.PRIVATE) class PatternElementOperations { /** * Count the number of variable-elements in the pattern. * * @param pattern the pattern whose elements are iterated over. * @return the number of elements in the pattern that are variable (i.e. not constant). */ public static int countVariableElements(Pattern pattern) { int count = 0; for (int i = 0; i < pattern.size(); i++) { if (!pattern.get(i).hasConstantValue()) { count++; } } return count; } /** * Index of the left-most variable-element in the pattern. * * @param pattern the pattern whose elements are searched * @return the index (zero-indexed) of the left-most variable element or -1 if no variable * elements exist. */ public static int indexLeftMostVariableElement(Pattern pattern) { return indexLeftMostVariableElement(pattern, 0); } /** * Index of the <code>n</code>th left-most variable-element in the pattern. * * @param pattern the pattern whose elements are searched * @param n (beginning at 0) is an index of all variable elements in the pattern * @return the index (zero-indexed) of the <code>n</code>th left-most variable element or -1 if * insufficient variable elements exist. */ public static int indexLeftMostVariableElement(Pattern pattern, int n) { int count = 0; for (int i = 0; i < pattern.size(); i++) { if (!pattern.get(i).hasConstantValue() && count++ == n) { return i; } } return -1; } /** * Index of the right-most variable-element in the pattern. * * @param pattern the pattern whose elements are searched * @return the index (zero-indexed) of the right-most variable element or -1 if no variable * elements exist. */ public static int indexRightMostVariableElement(Pattern pattern) { for (int i = (pattern.size() - 1); i >= 0; i--) { if (!pattern.get(i).hasConstantValue()) { return i; } } return -1; } /** * Extracts the constant elements greater and equal to index. * * @param index all constant elements with indices greater or equal to {@code index} are * selected * @return the selected constant elements, concatenated together as a string. */ public static String extractConstantElementsAfter(Pattern pattern, int index) { StringBuilder sb = new StringBuilder(); for (int i = index + 1; i < pattern.size(); i++) { PatternElement element = pattern.get(i); assert (element.hasConstantValue()); // The value is the same for all indexes, so we use 0 sb.append(element.valueAt(0)); } return sb.toString(); } }
4,497
0.654912
0.64959
120
36.575001
31.034567
99
false
false
0
0
0
0
0
0
0.475
false
false
2
b17f2d5dbf110de0071b28bc0771658855961193
27,642,409,576,995
56e5b09528081d048507dfb1fff3015c2449848a
/src/LigaNacionalMain.java
a94aba802aa7da4bf0fc2e881c4fd82dea9c3e60
[]
no_license
DavidUlloa99/LigaNacional-Futbol
https://github.com/DavidUlloa99/LigaNacional-Futbol
40c5fc8af484592220e8260a234784a79402af99
5075fe77806d7e804181ebc45491470a6d857423
refs/heads/master
2020-04-11T14:10:20.922000
2018-12-14T21:51:42
2018-12-14T21:51:42
161,844,089
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; /* * 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. */ /** * * @author ulloa */ public class LigaNacionalMain { public static void main(String[] args) { Scanner lea=new Scanner(System.in); lea.useDelimiter("\n"); int elec=0; Equipo var= new Equipo(); do { try{ System.out.println("------------------P R O G R A M A D E L A L I G A N A C I O N A L ----------------------------"); System.out.println("INGRESE EL NUMERO DE SU ELECION: "); System.out.println("1. AGREGAR UN EQUIPO \n2. AGREGAR UN JUGADOR \n3.MODIFICAR O ELIMINAR UN EQUIPO \n4.REPORTES \n5.SALIR"); elec=lea.nextInt(); switch(elec){ case 1 : System.out.println("AGREGAR UN EQUIPO"); System.out.println("Ingrese el nombre del Equipo: "); String eNombre= lea.nextLine(); System.out.println("Ingrese el nombre de la ciudad sede del equipo: "); String ciudad= lea.nextLine(); System.out.println("Ingrese la capacidad de aficionados del estadio del equipo: "); int capacidad= lea.nextInt(); var.equipos(eNombre,ciudad,capacidad); System.out.println("Equipo Agregado Exitosamente: "); break; case 2: System.out.println("AGREGAR UN JUGADOR"); System.out.println("Ingrese el codigo del equipo al que pertenecera el jugador: "); int codEquipo = lea.nextInt(); System.out.println("Ingrese el nombre completo del Jugador: "); String JugaNombre = lea.nextLine(); System.out.println("Ingrese el dorsal del jugador: "); int dorsal = lea.nextInt(); System.out.println("En que posicion jugara "+JugaNombre+"?"); System.out.println("Ingrese el numero de su eleccion: "); System.out.println("1.Delantero , 2.Defensa, 3.MedioCampista, 4.Portero "); int posi= lea.nextInt(); String posicion=""; if (posi==1) { posicion="Del"; }if (posi==2) { posicion="Def"; }if (posi==3) { posicion="Med"; }if (posi==4) { posicion="Po"; } System.out.println("Ingrese la edad del Jugador: "); int edad = lea.nextInt(); System.out.println("Ingrese la nacionalidad de "+JugaNombre); String nacio = lea.nextLine(); System.out.println("Su jugador ha sido agregado exitosamente"); var.jugadores(codEquipo,JugaNombre,dorsal,posicion,edad,nacio); break; case 3: System.out.println("MODIFICAR O ELIMINAR UN EQUIPO"); int elecBravo=0; do{ System.out.println("Ingrese una de las siguientes opciones: "); System.out.println("1.Modificar Equipo \n2.Eliminar un Equipo \n3.Salir"); elecBravo = lea.nextInt(); switch(elecBravo){ case 1: System.out.println("Modicar Equipo"); break; case 2: System.out.println("Eliminar un equipo: "); System.out.println("Ingrese el codigo del equipo: "); int codigoequipp = lea.nextInt(); var.eliminarEquipo(codigoequipp); } }while(elecBravo!=3); break; case 4: int elec2=0; do{ System.out.println("REPORTES : "); System.out.println("Ingrese una de las siguientes opciones del reporte a elaborar: "); System.out.println("1.Listado de los Equipos \n2.Listado de todos los Jugadores \n3.Listar Equipos con Jugadores \n4.Mostrar los jugadores de determinada posicion \n5. Atributos de Equipos"); elec2= lea.nextInt(); switch(elec2){ case 1: System.out.println("Listado de los Equipos"); var.equipos.seek(0); } }while(elec2!=6); break; case 5: System.out.println("SALIENDO . . . . ."); } }catch(Exception e){ } } while (elec!=4); } }
UTF-8
Java
5,558
java
LigaNacionalMain.java
Java
[ { "context": "emplate in the editor.\r\n */\r\n\r\n/**\r\n *\r\n * @author ulloa\r\n */\r\npublic class LigaNacionalMain {\r\n public", "end": 248, "score": 0.9993277192115784, "start": 243, "tag": "USERNAME", "value": "ulloa" } ]
null
[]
import java.util.Scanner; /* * 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. */ /** * * @author ulloa */ public class LigaNacionalMain { public static void main(String[] args) { Scanner lea=new Scanner(System.in); lea.useDelimiter("\n"); int elec=0; Equipo var= new Equipo(); do { try{ System.out.println("------------------P R O G R A M A D E L A L I G A N A C I O N A L ----------------------------"); System.out.println("INGRESE EL NUMERO DE SU ELECION: "); System.out.println("1. AGREGAR UN EQUIPO \n2. AGREGAR UN JUGADOR \n3.MODIFICAR O ELIMINAR UN EQUIPO \n4.REPORTES \n5.SALIR"); elec=lea.nextInt(); switch(elec){ case 1 : System.out.println("AGREGAR UN EQUIPO"); System.out.println("Ingrese el nombre del Equipo: "); String eNombre= lea.nextLine(); System.out.println("Ingrese el nombre de la ciudad sede del equipo: "); String ciudad= lea.nextLine(); System.out.println("Ingrese la capacidad de aficionados del estadio del equipo: "); int capacidad= lea.nextInt(); var.equipos(eNombre,ciudad,capacidad); System.out.println("Equipo Agregado Exitosamente: "); break; case 2: System.out.println("AGREGAR UN JUGADOR"); System.out.println("Ingrese el codigo del equipo al que pertenecera el jugador: "); int codEquipo = lea.nextInt(); System.out.println("Ingrese el nombre completo del Jugador: "); String JugaNombre = lea.nextLine(); System.out.println("Ingrese el dorsal del jugador: "); int dorsal = lea.nextInt(); System.out.println("En que posicion jugara "+JugaNombre+"?"); System.out.println("Ingrese el numero de su eleccion: "); System.out.println("1.Delantero , 2.Defensa, 3.MedioCampista, 4.Portero "); int posi= lea.nextInt(); String posicion=""; if (posi==1) { posicion="Del"; }if (posi==2) { posicion="Def"; }if (posi==3) { posicion="Med"; }if (posi==4) { posicion="Po"; } System.out.println("Ingrese la edad del Jugador: "); int edad = lea.nextInt(); System.out.println("Ingrese la nacionalidad de "+JugaNombre); String nacio = lea.nextLine(); System.out.println("Su jugador ha sido agregado exitosamente"); var.jugadores(codEquipo,JugaNombre,dorsal,posicion,edad,nacio); break; case 3: System.out.println("MODIFICAR O ELIMINAR UN EQUIPO"); int elecBravo=0; do{ System.out.println("Ingrese una de las siguientes opciones: "); System.out.println("1.Modificar Equipo \n2.Eliminar un Equipo \n3.Salir"); elecBravo = lea.nextInt(); switch(elecBravo){ case 1: System.out.println("Modicar Equipo"); break; case 2: System.out.println("Eliminar un equipo: "); System.out.println("Ingrese el codigo del equipo: "); int codigoequipp = lea.nextInt(); var.eliminarEquipo(codigoequipp); } }while(elecBravo!=3); break; case 4: int elec2=0; do{ System.out.println("REPORTES : "); System.out.println("Ingrese una de las siguientes opciones del reporte a elaborar: "); System.out.println("1.Listado de los Equipos \n2.Listado de todos los Jugadores \n3.Listar Equipos con Jugadores \n4.Mostrar los jugadores de determinada posicion \n5. Atributos de Equipos"); elec2= lea.nextInt(); switch(elec2){ case 1: System.out.println("Listado de los Equipos"); var.equipos.seek(0); } }while(elec2!=6); break; case 5: System.out.println("SALIENDO . . . . ."); } }catch(Exception e){ } } while (elec!=4); } }
5,558
0.430551
0.423354
119
44.689075
32.668118
216
false
false
0
0
0
0
0
0
0.663866
false
false
2
448d12727ec50238e1be2ad0608c21f24db33523
16,037,407,945,423
9ff39e163277c03c0bc41543bf715016f6603fd2
/src/ThroughCollection/Enums/Code.java
4ae756945e19e3cc070a491a48346ec4d66a4d16
[]
no_license
Odevol/Phonebook
https://github.com/Odevol/Phonebook
20033c41f6bba0f1950b356dac9f721af1b745a3
904368e06858c7b6ddb1ab35900d25bc639347da
refs/heads/master
2022-11-29T17:54:50.984000
2020-08-03T13:53:52
2020-08-03T13:53:52
284,713,100
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ThroughCollection.Enums; import java.util.Random; public enum Code { MTS, Tele2, Beeline, Megafon; public static String getRandomCode(){ Code[] values = Code.values(); int length = values.length; int randIndex = new Random().nextInt(length); String code; switch (String.valueOf(values[randIndex])) { case "MTS": code = "912"; case "Tele2": code = "900"; case "Beeline": code = "906"; case "Megafon": code = "922"; break; default: code = "3519"; } return code; } }
UTF-8
Java
700
java
Code.java
Java
[]
null
[]
package ThroughCollection.Enums; import java.util.Random; public enum Code { MTS, Tele2, Beeline, Megafon; public static String getRandomCode(){ Code[] values = Code.values(); int length = values.length; int randIndex = new Random().nextInt(length); String code; switch (String.valueOf(values[randIndex])) { case "MTS": code = "912"; case "Tele2": code = "900"; case "Beeline": code = "906"; case "Megafon": code = "922"; break; default: code = "3519"; } return code; } }
700
0.472857
0.447143
29
23.137932
14.404799
53
false
false
0
0
0
0
0
0
0.586207
false
false
2
b6bb3591a0ee13a90e0a71cd5f18d1fc1a5d13d3
12,051,678,257,329
f18750bb07e8c26861f0027f9bb32c37fdffcb3e
/springboot2-server/src/main/java/com/demo/libraryManagement/serviceImpl/PublisherServiceImpl.java
7e2263c947bb249c3767c9d35acafda1a2ca04fd
[]
no_license
EdwinRepository/libraryManagement
https://github.com/EdwinRepository/libraryManagement
32e58bd5770eaa2cac48b7475aebaf44418a460a
9a698651a795c19e3d8952396cc0d6721b110a88
refs/heads/master
2022-12-28T10:48:37.238000
2020-10-14T16:27:58
2020-10-14T16:27:58
300,191,382
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.libraryManagement.serviceImpl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.demo.libraryManagement.dao.AuthorDao; import com.demo.libraryManagement.dao.PublisherDao; import com.demo.libraryManagement.model.Publisher; import com.demo.libraryManagement.service.PublisherService; @Service public class PublisherServiceImpl implements PublisherService{ @Autowired private PublisherDao publisherDao; @Override public Publisher createOrUpdatePublisher(Publisher publisher) { // TODO Auto-generated method stub return publisherDao.createOrUpdatePublisher(publisher); } @Override public Optional<Publisher> getPublisherById(Long publisherId) { // TODO Auto-generated method stub return publisherDao.getPublisherById(publisherId); } @Override public void deletePublisher(Publisher publisher) { // TODO Auto-generated method stub publisherDao.deleteAuthor(publisher); } @Override public List<Publisher> getAllPublisher() { // TODO Auto-generated method stub return publisherDao.getAllPublisher(); } }
UTF-8
Java
1,213
java
PublisherServiceImpl.java
Java
[]
null
[]
package com.demo.libraryManagement.serviceImpl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.demo.libraryManagement.dao.AuthorDao; import com.demo.libraryManagement.dao.PublisherDao; import com.demo.libraryManagement.model.Publisher; import com.demo.libraryManagement.service.PublisherService; @Service public class PublisherServiceImpl implements PublisherService{ @Autowired private PublisherDao publisherDao; @Override public Publisher createOrUpdatePublisher(Publisher publisher) { // TODO Auto-generated method stub return publisherDao.createOrUpdatePublisher(publisher); } @Override public Optional<Publisher> getPublisherById(Long publisherId) { // TODO Auto-generated method stub return publisherDao.getPublisherById(publisherId); } @Override public void deletePublisher(Publisher publisher) { // TODO Auto-generated method stub publisherDao.deleteAuthor(publisher); } @Override public List<Publisher> getAllPublisher() { // TODO Auto-generated method stub return publisherDao.getAllPublisher(); } }
1,213
0.78648
0.78648
41
27.585365
22.958048
64
false
false
0
0
0
0
0
0
1.073171
false
false
2
1b4ee7e008beab4628483d21bfbf172129e42aaf
18,769,007,097,891
0fe7e3c52515264db97caa3deb9aacfd9d881ad6
/Amazon/amazonpackages/AmazonPackages.java
da13597dc358a175dae7b014e6b39dd0f7f19132
[]
no_license
sylabtechnologies/demo_DP
https://github.com/sylabtechnologies/demo_DP
be983c56fc840ee772882a3914ae32947bc56038
b964b62c274f8f58eba8c6e6a7f45ca3deefee5a
refs/heads/master
2021-03-30T22:07:09.049000
2021-03-07T20:14:58
2021-03-07T20:14:58
124,622,179
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package amazonpackages; import java.util.ArrayList; import java.util.Arrays; public class Amazonpackages { public static void main(String[] args) { Solution obj = new Solution(); ArrayList<Integer> test = new ArrayList<>(Arrays.asList(1, 10, 25, 35, 60)); System.out.println(obj.IDsOfPackages(90, test)); } }
UTF-8
Java
351
java
AmazonPackages.java
Java
[]
null
[]
package amazonpackages; import java.util.ArrayList; import java.util.Arrays; public class Amazonpackages { public static void main(String[] args) { Solution obj = new Solution(); ArrayList<Integer> test = new ArrayList<>(Arrays.asList(1, 10, 25, 35, 60)); System.out.println(obj.IDsOfPackages(90, test)); } }
351
0.660969
0.62963
14
24.071428
23.78314
84
false
false
0
0
0
0
0
0
0.785714
false
false
2
58d887a4a4b8813d60c3eb4c5f783008f9367041
11,003,706,275,244
82b33edb1beaa3f8e3c0a1b3c01a173aff41e608
/src/test/junit/FusionTestJUnit.java
f9bbb3e84b0579124caefc45c93be40ea392c037
[]
no_license
alvihnketremindie/filrouge_msisic
https://github.com/alvihnketremindie/filrouge_msisic
bd38901f93ee7be9021a7df9158c3b63489ada37
f668604c627f235d4e9ce77d6daa384799e0f91d
refs/heads/master
2020-03-08T16:53:42.279000
2018-04-05T19:22:40
2018-04-05T19:22:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.junit; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses( { test.junit.alvihn.AllTestJUnit.class, test.junit.sekou.SocialNetworkTest.class } ) public class FusionTestJUnit { }
UTF-8
Java
318
java
FusionTestJUnit.java
Java
[]
null
[]
package test.junit; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses( { test.junit.alvihn.AllTestJUnit.class, test.junit.sekou.SocialNetworkTest.class } ) public class FusionTestJUnit { }
318
0.72327
0.72327
19
14.842105
16.387617
44
false
false
0
0
0
0
0
0
0.789474
false
false
2
076cf6fe083c189de433bab78ddf0e05d417e15b
18,227,841,230,451
1d5b73fbd91859b375ea12c71dfa855e50fbf601
/fjnu/src/main/java/com/fjnu/fjnu/bean/Article.java
a186f6cd0f07b8dd8b8ae8659b1ee6816ca307cd
[]
no_license
hopforagooddream/project
https://github.com/hopforagooddream/project
b383c79f5fd2450c17f2e4d8f971a0bf63e832d2
1a105638d3f8a683e23594c8e9aa2ca797bb92d6
refs/heads/master
2022-11-14T04:54:12.110000
2020-07-08T13:33:16
2020-07-08T13:33:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fjnu.fjnu.bean; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.sql.Date; @TableName("t_article") public class Article { //主键 @TableId(value = "id",type = IdType.AUTO) private Integer id; private String title; private String scontent; private int pinglun; private int glance; private String author; private String hpic; public Article(Integer id, String title, String scontent, int pinglun, int glance, String author, String hpic, Date published) { this.id = id; this.title = title; this.scontent = scontent; this.pinglun = pinglun; this.glance = glance; this.author = author; this.hpic = hpic; this.published = published; } public String getHpic() { return hpic; } public void setHpic(String hpic) { this.hpic = hpic; } public void setPublished(Date published) { this.published = published; } private Date published; public int getPinglun() { return pinglun; } public void setPinglun(int pinglun) { this.pinglun = pinglun; } public int getGlance() { return glance; } public void setGlance(int glance) { this.glance = glance; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Article() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getScontent() { return scontent; } public void setScontent(String scontent) { this.scontent = scontent; } }
UTF-8
Java
1,994
java
Article.java
Java
[]
null
[]
package com.fjnu.fjnu.bean; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.sql.Date; @TableName("t_article") public class Article { //主键 @TableId(value = "id",type = IdType.AUTO) private Integer id; private String title; private String scontent; private int pinglun; private int glance; private String author; private String hpic; public Article(Integer id, String title, String scontent, int pinglun, int glance, String author, String hpic, Date published) { this.id = id; this.title = title; this.scontent = scontent; this.pinglun = pinglun; this.glance = glance; this.author = author; this.hpic = hpic; this.published = published; } public String getHpic() { return hpic; } public void setHpic(String hpic) { this.hpic = hpic; } public void setPublished(Date published) { this.published = published; } private Date published; public int getPinglun() { return pinglun; } public void setPinglun(int pinglun) { this.pinglun = pinglun; } public int getGlance() { return glance; } public void setGlance(int glance) { this.glance = glance; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Article() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getScontent() { return scontent; } public void setScontent(String scontent) { this.scontent = scontent; } }
1,994
0.606533
0.606533
105
17.952381
19.051001
132
false
false
0
0
0
0
0
0
0.419048
false
false
2
d301865bc40de9595462f65be586c0086f1e9b99
4,440,996,251,185
d54ee3fad23c4bc6cd21c11ef2beb25c804ce8b6
/src/com/whai/blog/model/Article.java
dc65aef919996f1c9fff6d83356674c99ca7a401
[ "Apache-2.0" ]
permissive
whai362/MyBlog
https://github.com/whai362/MyBlog
231ce97b95f1a303dc52d11547f245b805522aa2
d4f96bf6e973fc1c558093d9fc5705c86d4158a9
refs/heads/master
2018-01-11T20:50:22.630000
2015-12-03T17:05:00
2015-12-03T17:05:00
45,124,042
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whai.blog.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.stereotype.Component; @Component("article") @Entity @Table public class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String title; private String content; private String tags; private String author; private String createdate; private String updatedate; private String contenthtml; private String precontenthtml; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCreatedate() { return createdate; } public void setCreatedate(String createdate) { this.createdate = createdate; } public String getUpdatedate() { return updatedate; } public void setUpdatedate(String updatedate) { this.updatedate = updatedate; } public String getContenthtml() { return contenthtml; } public void setContenthtml(String contenthtml) { this.contenthtml = contenthtml; } public String getPrecontenthtml() { return precontenthtml; } public void setPrecontenthtml(String precontenthtml) { this.precontenthtml = precontenthtml; } }
UTF-8
Java
1,754
java
Article.java
Java
[]
null
[]
package com.whai.blog.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.stereotype.Component; @Component("article") @Entity @Table public class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String title; private String content; private String tags; private String author; private String createdate; private String updatedate; private String contenthtml; private String precontenthtml; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCreatedate() { return createdate; } public void setCreatedate(String createdate) { this.createdate = createdate; } public String getUpdatedate() { return updatedate; } public void setUpdatedate(String updatedate) { this.updatedate = updatedate; } public String getContenthtml() { return contenthtml; } public void setContenthtml(String contenthtml) { this.contenthtml = contenthtml; } public String getPrecontenthtml() { return precontenthtml; } public void setPrecontenthtml(String precontenthtml) { this.precontenthtml = precontenthtml; } }
1,754
0.738312
0.738312
99
16.717173
15.78008
55
false
false
0
0
0
0
0
0
1.20202
false
false
2
1701b29fa6651d54c307803cb26376d0123f8214
27,633,819,615,739
cf6521b7bbd70e56a9c32b89413a6b8f0b28c86f
/billingstack-client/src/main/java/org/billingstack/CustomerPaymentMethod.java
c891a27d5121584245986927a1fbe1e660e94eaf
[]
no_license
billingstack/billingstack-java-sdk
https://github.com/billingstack/billingstack-java-sdk
dbbe77445d0c27843987c19220eb8a1d7d178fc3
fe0760878fddae6f03a123dd261972478baaa023
refs/heads/master
2020-03-26T05:26:23.272000
2013-06-04T19:42:50
2013-06-04T19:42:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.billingstack; import java.util.Map; import org.codehaus.jackson.annotate.JsonProperty; public class CustomerPaymentMethod { private String id; @JsonProperty("method_id") private String method; private String customer; private Map<String, Object> metadata; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } }
UTF-8
Java
784
java
CustomerPaymentMethod.java
Java
[]
null
[]
package org.billingstack; import java.util.Map; import org.codehaus.jackson.annotate.JsonProperty; public class CustomerPaymentMethod { private String id; @JsonProperty("method_id") private String method; private String customer; private Map<String, Object> metadata; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } }
784
0.711735
0.711735
50
14.68
15.904012
56
false
false
0
0
0
0
0
0
1.16
false
false
2
29258da07cb0eaefbec4f55ae7eefc635ffd62f0
28,338,194,273,223
b79678a9c7f839dcb23cac3a135ab5905e346201
/src/task_3/com/epam/training/inner/bean/taskFile/taskFileCreator/ICreator.java
b18be316909b0072c6df781d030b7ddaf41a9629
[]
no_license
OsadchyRoman/CalculatorAndCoin
https://github.com/OsadchyRoman/CalculatorAndCoin
7856ecce806c7a250bfe17c7e12c8d15ec8bd676
70a5070fd444cb964fba4c1e41467deabe072340
refs/heads/master
2020-04-01T23:51:28.436000
2018-10-29T13:24:48
2018-10-29T13:24:48
153,776,305
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package task_3.com.epam.training.inner.bean.taskFile.taskFileCreator; import task_3.com.epam.training.inner.bean.taskFile.TaskFile; import task_3.com.epam.training.inner.utils.validator.fileValidator.IFileCharacterValidator; import java.io.IOException; public interface ICreator { TaskFile createTaskFile(IFileCharacterValidator iFileCharacterValidator) throws IOException; }
UTF-8
Java
383
java
ICreator.java
Java
[]
null
[]
package task_3.com.epam.training.inner.bean.taskFile.taskFileCreator; import task_3.com.epam.training.inner.bean.taskFile.TaskFile; import task_3.com.epam.training.inner.utils.validator.fileValidator.IFileCharacterValidator; import java.io.IOException; public interface ICreator { TaskFile createTaskFile(IFileCharacterValidator iFileCharacterValidator) throws IOException; }
383
0.840731
0.832898
10
37.299999
37.024452
96
false
false
0
0
0
0
0
0
0.5
false
false
2
7763d92432495ecc50edc8ef09d9ae87e41dcf3f
7,550,552,512,941
d48e724b77d5548734e19b9f440f6e414cfa2f8c
/app/src/main/java/com/fly/viewdemo/practice1/XfermodeFragment.java
16ba0ed11a4fe74b82f72315a0a21fde69c94da2
[ "Apache-2.0" ]
permissive
kco0910/ViewDemo
https://github.com/kco0910/ViewDemo
4a26a8f90d84c7033ddc4280ef6d84965e38020f
d8df7c93d1e634b1161b2b356905564520d61d53
refs/heads/master
2023-08-21T23:22:13.942000
2021-09-26T10:02:59
2021-09-26T10:02:59
125,468,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fly.viewdemo.practice1; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.fly.viewdemo.R; import com.fly.viewdemo.base.BaseView; /** * Created by Fj on 2018/3/29. */ public class XfermodeFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return new XfermodeView(getActivity()); } private class XfermodeView extends BaseView{ private Bitmap mBlue; private Bitmap mWoniu2; public XfermodeView(Context context) { super(context); } public XfermodeView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public XfermodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void init() { super.init(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; mBlue = BitmapFactory.decodeResource(getResources(), R.drawable.blue,options); mWoniu2 = BitmapFactory.decodeResource(getResources(), R.drawable.woniu_2); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //要想使用 setXfermode() 正常绘制,必须使用离屏缓存 (Off-screen Buffer) 把内容绘制在额外的层上,再把绘制好的内容贴回 View 中 //setup1 int saved = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG); canvas.drawBitmap(mBlue,0,0,mPaint); PorterDuffXfermode porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN); mPaint.setXfermode(porterDuffXfermode); canvas.drawBitmap(mWoniu2,100,100,mPaint); mPaint.setXfermode(null); //setup2 canvas.restoreToCount(saved); } } }
UTF-8
Java
2,462
java
XfermodeFragment.java
Java
[ { "context": "com.fly.viewdemo.base.BaseView;\n\n/**\n * Created by Fj on 2018/3/29.\n */\n\npublic class XfermodeFragment ", "end": 577, "score": 0.999378502368927, "start": 575, "tag": "USERNAME", "value": "Fj" } ]
null
[]
package com.fly.viewdemo.practice1; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.fly.viewdemo.R; import com.fly.viewdemo.base.BaseView; /** * Created by Fj on 2018/3/29. */ public class XfermodeFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return new XfermodeView(getActivity()); } private class XfermodeView extends BaseView{ private Bitmap mBlue; private Bitmap mWoniu2; public XfermodeView(Context context) { super(context); } public XfermodeView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public XfermodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void init() { super.init(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; mBlue = BitmapFactory.decodeResource(getResources(), R.drawable.blue,options); mWoniu2 = BitmapFactory.decodeResource(getResources(), R.drawable.woniu_2); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //要想使用 setXfermode() 正常绘制,必须使用离屏缓存 (Off-screen Buffer) 把内容绘制在额外的层上,再把绘制好的内容贴回 View 中 //setup1 int saved = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG); canvas.drawBitmap(mBlue,0,0,mPaint); PorterDuffXfermode porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN); mPaint.setXfermode(porterDuffXfermode); canvas.drawBitmap(mWoniu2,100,100,mPaint); mPaint.setXfermode(null); //setup2 canvas.restoreToCount(saved); } } }
2,462
0.675483
0.665407
79
29.151899
27.952078
123
false
false
0
0
0
0
0
0
0.683544
false
false
2
5b051acc7ad77877482586b6ffc6bab564570e75
20,074,677,161,781
eb801d942f7361a87d5b79dd03b0b611493d12a6
/renren-spilder/src/it/renren/spilder/util/file/TranDir.java
57d7c9927914d4466ee03923c7b694be54f7d3ad
[]
no_license
fenglibin/renren-spilder
https://github.com/fenglibin/renren-spilder
fa78c00859f544f851ec0dc0a15cb001d121f415
d1a0b8cd773a5edc36707cb4d7589e1f5c982c92
refs/heads/master
2021-01-10T19:54:21.351000
2014-08-06T14:23:52
2014-08-06T14:23:52
33,022,581
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.renren.spilder.util.file; import it.renren.spilder.util.FileUtil; import it.renren.spilder.util.FontUtil; import java.io.File; /** * 类TranDir.java的实现描述:将指定文件夹下面的文件内容,全部翻译成其它语言,如简体翻译为繁体 * * @author fenglibin 2011-8-9 下午01:31:43 */ public class TranDir { private static String charset = "utf-8"; private static final String[] fileTypes = { "php", "html", "txt", "htm" }; private static final int JIAN_FAN = 1; // 值为1表示简体转为繁体,值为0表示繁体转换为简体 private static void tranDir(String dir) throws Exception { File fileDir = new File(dir); File[] files = fileDir.listFiles(); for (File file : files) { if (file.isDirectory()) { tranDir(file.getAbsolutePath()); } else { tranFile(file.getAbsolutePath()); } } } private static void tranFile(String file) throws Exception { if (!isTranFile(file)) { return; } System.out.println("Tran:" + file); String content = FileUtil.getFileContent(file, charset); if (JIAN_FAN == 1) { content = FontUtil.jian2fan(content); } else if (JIAN_FAN == 0) { content = FontUtil.fan2jian(content); } FileUtil.writeFile(file, content, charset); } private static boolean isTranFile(String file) { boolean is = Boolean.FALSE; for (String type : fileTypes) { if (file.endsWith(type)) { is = Boolean.TRUE; break; } } return is; } private static void trandir() throws Exception { String dir = ""; charset = "gbk"; dir = "/usr/fenglibin/api_bg5/t"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/c++"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/DHTML"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/Hibernate3.2"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/j2me"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/JavaScript"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/Spring2.5"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/tsql2.1"; tranDir(dir); charset = "utf-8"; dir = "/usr/fenglibin/api_bg5/css3.0"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/Ext3"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/jQuery1.3"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/mysql5.1zh"; tranDir(dir); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { trandir(); } }
GB18030
Java
2,879
java
TranDir.java
Java
[ { "context": "描述:将指定文件夹下面的文件内容,全部翻译成其它语言,如简体翻译为繁体\n * \n * @author fenglibin 2011-8-9 下午01:31:43\n */\npublic class TranDir {\n\n ", "end": 224, "score": 0.9985286593437195, "start": 215, "tag": "USERNAME", "value": "fenglibin" } ]
null
[]
package it.renren.spilder.util.file; import it.renren.spilder.util.FileUtil; import it.renren.spilder.util.FontUtil; import java.io.File; /** * 类TranDir.java的实现描述:将指定文件夹下面的文件内容,全部翻译成其它语言,如简体翻译为繁体 * * @author fenglibin 2011-8-9 下午01:31:43 */ public class TranDir { private static String charset = "utf-8"; private static final String[] fileTypes = { "php", "html", "txt", "htm" }; private static final int JIAN_FAN = 1; // 值为1表示简体转为繁体,值为0表示繁体转换为简体 private static void tranDir(String dir) throws Exception { File fileDir = new File(dir); File[] files = fileDir.listFiles(); for (File file : files) { if (file.isDirectory()) { tranDir(file.getAbsolutePath()); } else { tranFile(file.getAbsolutePath()); } } } private static void tranFile(String file) throws Exception { if (!isTranFile(file)) { return; } System.out.println("Tran:" + file); String content = FileUtil.getFileContent(file, charset); if (JIAN_FAN == 1) { content = FontUtil.jian2fan(content); } else if (JIAN_FAN == 0) { content = FontUtil.fan2jian(content); } FileUtil.writeFile(file, content, charset); } private static boolean isTranFile(String file) { boolean is = Boolean.FALSE; for (String type : fileTypes) { if (file.endsWith(type)) { is = Boolean.TRUE; break; } } return is; } private static void trandir() throws Exception { String dir = ""; charset = "gbk"; dir = "/usr/fenglibin/api_bg5/t"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/c++"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/DHTML"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/Hibernate3.2"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/j2me"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/JavaScript"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/Spring2.5"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/tsql2.1"; tranDir(dir); charset = "utf-8"; dir = "/usr/fenglibin/api_bg5/css3.0"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/Ext3"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/jQuery1.3"; tranDir(dir); dir = "/usr/fenglibin/api_bg5/mysql5.1zh"; tranDir(dir); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { trandir(); } }
2,879
0.543044
0.525972
95
27.978947
20.940004
105
false
false
0
0
0
0
0
0
0.578947
false
false
2
2e1e001e202efcf0a3a3122163d1298382960370
9,216,999,869,658
a926918d72d2a8917b40752950d2904e4ac2c44c
/design-model/src/main/java/strategy/StrategyTest.java
48cf43125eb6bbbdc4e989e59093107f692cdd91
[]
no_license
lureSky/sourceCode
https://github.com/lureSky/sourceCode
28fe1895e87c7823a26b9eb991369063bb95976b
5ce146b9ea57154e8aeffde052f26c89297477f1
refs/heads/main
2023-02-01T11:04:47.661000
2020-12-17T09:21:16
2020-12-17T09:21:16
319,292,618
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package strategy; import org.junit.Test; /** * 测试类 * * @author think * */ public class StrategyTest { @Test public void test() { // 抽象策略类 PersonContext person = new PersonContext(); // 太远了,需要做飞机 person.travel(10000); // 不太远,飞机太贵,选择火车 person.travel(100); // 很近,直接选择自行车 person.travel(1); } }
UTF-8
Java
401
java
StrategyTest.java
Java
[ { "context": "\nimport org.junit.Test;\n\n/**\n * 测试类\n * \n * @author think\n *\n */\npublic class StrategyTest {\n\n\t@Test\n\tpubli", "end": 74, "score": 0.9942564964294434, "start": 69, "tag": "USERNAME", "value": "think" } ]
null
[]
package strategy; import org.junit.Test; /** * 测试类 * * @author think * */ public class StrategyTest { @Test public void test() { // 抽象策略类 PersonContext person = new PersonContext(); // 太远了,需要做飞机 person.travel(10000); // 不太远,飞机太贵,选择火车 person.travel(100); // 很近,直接选择自行车 person.travel(1); } }
401
0.626168
0.598131
27
10.888889
11.066577
45
false
false
0
0
0
0
0
0
0.925926
false
false
2
7b0f66a1a61b196f1bd7fa5f820e4b2251af80d6
24,352,464,594,381
7ac8e9294a6623dca494ababe6a142f5ca60fa13
/javaproject_1/src/liuenci/cn/package_10/Demo1.java
1139e20362efce448cfc97f28eb8e76e679c3bcd
[]
no_license
liuenci/JavaDemo
https://github.com/liuenci/JavaDemo
44f973d55bd3277c6626fea834548e802de17a25
edc0a6d0e82efcac7ccc3de9e901cf9aef5416a2
refs/heads/master
2021-04-27T16:43:27.263000
2018-02-21T08:12:45
2018-02-21T08:12:45
122,308,380
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package liuenci.cn.package_10; public class Demo1 { public static void main(String[] args) { // TODO Auto-generated method stub //创建父类对象 Animal a0 = new Animal(); a0.walk(); System.out.println("========="); //创建子类对象 Bird a1 = new Bird(); a1.walk(); Snake a2 = new Snake(); a2.walk(); Person a3 = new Person(); a3.walk(); Dog a4 = new Dog(); a4.walk(); } }
GB18030
Java
413
java
Demo1.java
Java
[]
null
[]
package liuenci.cn.package_10; public class Demo1 { public static void main(String[] args) { // TODO Auto-generated method stub //创建父类对象 Animal a0 = new Animal(); a0.walk(); System.out.println("========="); //创建子类对象 Bird a1 = new Bird(); a1.walk(); Snake a2 = new Snake(); a2.walk(); Person a3 = new Person(); a3.walk(); Dog a4 = new Dog(); a4.walk(); } }
413
0.588689
0.55527
22
16.681818
12.226597
41
false
false
0
0
0
0
0
0
1.909091
false
false
2
c7e7109b9d05149ca7a13e4470d004692b9c98a3
919,123,042,915
6060966ccf453f1ac9c18a9a417eb8b559435749
/recommended-repository/src/main/java/com/jianke/repository/recommended/db/mybatis/mallportal/saledetail/ProductDao.java
c7abf0ad63de92450aceb4b43b1e58fbc3135a27
[]
no_license
hymagic/jianke-recommended-api
https://github.com/hymagic/jianke-recommended-api
250142940b19354cea3481053c3c32a5b81cfd86
2719dea6669e2bb71b7391e11ba4bd79ee2a7613
refs/heads/master
2017-11-11T16:51:04.030000
2017-03-14T08:25:31
2017-03-14T08:25:31
84,047,018
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jianke.repository.recommended.db.mybatis.mallportal.saledetail; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.MapKey; import org.apache.ibatis.annotations.Param; import com.jianke.client.recommended.common.DataVO; /** * * @author lizhuquan * */ public interface ProductDao { // @DataSource("mssql") public Integer getTotalCount(); // @DataSource("mssql") public List<DataVO> getPageProductList(@Param("currentPage") Integer currentPage, @Param("pageSize") Integer pageSize); @MapKey(value="productCode") public Map<Object, DataVO> getPageForIndex(@Param("currentPage") Integer currentPage, @Param("pageSize") Integer pageSize); }
UTF-8
Java
737
java
ProductDao.java
Java
[ { "context": "recommended.common.DataVO;\r\n\r\n/**\r\n * \r\n * @author lizhuquan\r\n *\r\n */\r\npublic interface ProductDao\r\n{\r\n // @", "end": 306, "score": 0.9991834759712219, "start": 297, "tag": "USERNAME", "value": "lizhuquan" } ]
null
[]
package com.jianke.repository.recommended.db.mybatis.mallportal.saledetail; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.MapKey; import org.apache.ibatis.annotations.Param; import com.jianke.client.recommended.common.DataVO; /** * * @author lizhuquan * */ public interface ProductDao { // @DataSource("mssql") public Integer getTotalCount(); // @DataSource("mssql") public List<DataVO> getPageProductList(@Param("currentPage") Integer currentPage, @Param("pageSize") Integer pageSize); @MapKey(value="productCode") public Map<Object, DataVO> getPageForIndex(@Param("currentPage") Integer currentPage, @Param("pageSize") Integer pageSize); }
737
0.721845
0.721845
25
27.559999
34.63187
127
false
false
0
0
0
0
0
0
0.48
false
false
2
f7b350660ca9924f695125143212f056b317683b
6,476,810,748,977
22ff3e2077345fed2a6d688534af2e8b3d7aab29
/Chapter11/src/System/Class/Instance/Action.java
c8175b982788c15b74b9eb864d183b7169d1cfd4
[]
no_license
pandora0667/JAVA
https://github.com/pandora0667/JAVA
ae67f09d1fffbf5c6d17b2da781575686977c0fd
524f55b4af67478b9244e00e496466bda8e2f334
refs/heads/master
2021-01-13T03:01:31.847000
2017-04-03T15:00:41
2017-04-03T15:00:41
77,054,434
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package System.Class.Instance; /** * Created by jusk2 on 2017-02-02. */ public interface Action { public void execute(); }
UTF-8
Java
128
java
Action.java
Java
[ { "context": "package System.Class.Instance;\n\n/**\n * Created by jusk2 on 2017-02-02.\n */\npublic interface Action {\n pu", "end": 55, "score": 0.9995393753051758, "start": 50, "tag": "USERNAME", "value": "jusk2" } ]
null
[]
package System.Class.Instance; /** * Created by jusk2 on 2017-02-02. */ public interface Action { public void execute(); }
128
0.6875
0.617188
8
15
13.583077
34
false
false
0
0
0
0
0
0
0.25
false
false
2
c10f483f99261e5c815c043629dc10bd301bc74f
28,329,604,303,079
58d5f510c9a376270f7341cca091cb8f00cc4395
/src/main/java/com/yt/framework/controller/admin/AdminLeagueScorerController.java
557ee5e990a52bb45f53ff36429a60c652738817
[]
no_license
yanziyang2016/yrtweb
https://github.com/yanziyang2016/yrtweb
c7ba17c50ebf6a78426d7d4d6af1aa5d1f964ccb
139c63688f14c1f628d3a34d438116ca8ca8da1a
refs/heads/master
2021-01-22T17:28:51.336000
2017-03-21T09:17:44
2017-03-21T09:17:44
85,017,070
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yt.framework.controller.admin; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.yt.framework.controller.BaseController; import com.yt.framework.persistent.entity.League; import com.yt.framework.persistent.entity.LeagueGroup; import com.yt.framework.persistent.entity.LeagueScorer; import com.yt.framework.persistent.entity.User; import com.yt.framework.service.UserService; import com.yt.framework.service.admin.AdminLeagueGroupService; import com.yt.framework.service.admin.AdminLeagueScorerService; import com.yt.framework.utils.AjaxMsg; import com.yt.framework.utils.PageModel; import com.yt.framework.utils.UUIDGenerator; /** * 联赛射手榜 * @author gl * */ @Controller @RequestMapping(value="/admin/leagueScorer") public class AdminLeagueScorerController extends BaseController { private static Logger logger = LogManager.getLogger(AdminLeagueScorerController.class); @Autowired private AdminLeagueScorerService adminLeagueScorerService; @Autowired private AdminLeagueGroupService adminLeagueGroupService; @Autowired private UserService userService; @RequestMapping(value="") public String index(HttpServletRequest request,PageModel pageModel){ String username = request.getParameter("username"); String league_id = request.getParameter("league_id"); String group_id = request.getParameter("group_id"); Map<String, Object> params = new HashMap<String,Object>(); if(StringUtils.isNotBlank(group_id)) params.put("group_id", group_id); if(StringUtils.isNotBlank(league_id)) params.put("league_id", league_id); if(StringUtils.isNotBlank(username)) params.put("username", username); AjaxMsg msg = adminLeagueScorerService.queryForPageForMap(params, pageModel); //List<League> leagues = adminLeagueGroupService.getLeagues(); List<LeagueGroup> groups = adminLeagueGroupService.getGroupsByLid(league_id); request.setAttribute("page", msg.getData("page")); request.setAttribute("params",params); request.setAttribute("league_id",league_id); request.setAttribute("groups",groups); return "admin/leaguescorer/leaguescorer"; } @RequestMapping(value="/formJsp") public String formJsp(HttpServletRequest request){ String id = request.getParameter("id"); LeagueScorer scorer = new LeagueScorer(); User user = new User(); if(StringUtils.isNotBlank(id)){ scorer = adminLeagueScorerService.getEntityById(id); user = userService.getEntityById(scorer.getUser_id()); } List<League> leagues = adminLeagueGroupService.getLeagues(); request.setAttribute("scorer", scorer); request.setAttribute("leagues", leagues); request.setAttribute("user", user); return "admin/leaguescorer/form"; } @RequestMapping(value="/queryLeagueGroups") @ResponseBody public String queryLeagueGroups(HttpServletRequest request){ String league_id = request.getParameter("league_id"); List<LeagueGroup> groups = adminLeagueGroupService.getGroupsByLid(league_id); return AjaxMsg.newSuccess().addData("groups", groups).toJson(); } @RequestMapping(value="/saveOrUpdate") @ResponseBody public String saveOrUpdate(HttpServletRequest request,LeagueScorer scorer){ AjaxMsg msg = AjaxMsg.newError(); if(StringUtils.isNotBlank(scorer.getId())){ LeagueScorer s = adminLeagueScorerService.getEntityById(scorer.getId()); s.setS_sort(scorer.getS_sort()); msg = adminLeagueScorerService.update(s); }else{ scorer.setId(UUIDGenerator.getUUID()); msg = adminLeagueScorerService.save(scorer); } return msg.toJson(); } @RequestMapping(value="/delete") @ResponseBody public String delete(HttpServletRequest request){ String id = request.getParameter("id"); AjaxMsg msg = adminLeagueScorerService.delete(id); return msg.toJson(); } @RequestMapping(value="/userDialog") public String userDialog(HttpServletRequest request){ return "admin/leaguescorer/user_dialog"; } @RequestMapping(value="/recordDialog") public String recordDialog(HttpServletRequest request){ String league_id = request.getParameter("league_id"); request.setAttribute("league_id", league_id); return "admin/leaguescorer/record_dialog"; } /** * 更新射手榜 * @param request * @return */ @RequestMapping(value="/updateScorer") @ResponseBody public String updateScorer(HttpServletRequest request){ String league_id = request.getParameter("league_id"); try { AjaxMsg msg = adminLeagueScorerService.updateScorer(league_id); return msg.toJson(); } catch (Exception e) { logger.error(e); return AjaxMsg.newError().toJson(); } } }
UTF-8
Java
5,106
java
AdminLeagueScorerController.java
Java
[ { "context": ".utils.UUIDGenerator;\r\n\r\n/**\r\n * 联赛射手榜\r\n * @author gl\r\n *\r\n */\r\n@Controller\r\n@RequestMapping(value=\"/ad", "end": 1127, "score": 0.9367445111274719, "start": 1125, "tag": "USERNAME", "value": "gl" }, { "context": "odel){\r\n\t\tString username = request....
null
[]
package com.yt.framework.controller.admin; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.yt.framework.controller.BaseController; import com.yt.framework.persistent.entity.League; import com.yt.framework.persistent.entity.LeagueGroup; import com.yt.framework.persistent.entity.LeagueScorer; import com.yt.framework.persistent.entity.User; import com.yt.framework.service.UserService; import com.yt.framework.service.admin.AdminLeagueGroupService; import com.yt.framework.service.admin.AdminLeagueScorerService; import com.yt.framework.utils.AjaxMsg; import com.yt.framework.utils.PageModel; import com.yt.framework.utils.UUIDGenerator; /** * 联赛射手榜 * @author gl * */ @Controller @RequestMapping(value="/admin/leagueScorer") public class AdminLeagueScorerController extends BaseController { private static Logger logger = LogManager.getLogger(AdminLeagueScorerController.class); @Autowired private AdminLeagueScorerService adminLeagueScorerService; @Autowired private AdminLeagueGroupService adminLeagueGroupService; @Autowired private UserService userService; @RequestMapping(value="") public String index(HttpServletRequest request,PageModel pageModel){ String username = request.getParameter("username"); String league_id = request.getParameter("league_id"); String group_id = request.getParameter("group_id"); Map<String, Object> params = new HashMap<String,Object>(); if(StringUtils.isNotBlank(group_id)) params.put("group_id", group_id); if(StringUtils.isNotBlank(league_id)) params.put("league_id", league_id); if(StringUtils.isNotBlank(username)) params.put("username", username); AjaxMsg msg = adminLeagueScorerService.queryForPageForMap(params, pageModel); //List<League> leagues = adminLeagueGroupService.getLeagues(); List<LeagueGroup> groups = adminLeagueGroupService.getGroupsByLid(league_id); request.setAttribute("page", msg.getData("page")); request.setAttribute("params",params); request.setAttribute("league_id",league_id); request.setAttribute("groups",groups); return "admin/leaguescorer/leaguescorer"; } @RequestMapping(value="/formJsp") public String formJsp(HttpServletRequest request){ String id = request.getParameter("id"); LeagueScorer scorer = new LeagueScorer(); User user = new User(); if(StringUtils.isNotBlank(id)){ scorer = adminLeagueScorerService.getEntityById(id); user = userService.getEntityById(scorer.getUser_id()); } List<League> leagues = adminLeagueGroupService.getLeagues(); request.setAttribute("scorer", scorer); request.setAttribute("leagues", leagues); request.setAttribute("user", user); return "admin/leaguescorer/form"; } @RequestMapping(value="/queryLeagueGroups") @ResponseBody public String queryLeagueGroups(HttpServletRequest request){ String league_id = request.getParameter("league_id"); List<LeagueGroup> groups = adminLeagueGroupService.getGroupsByLid(league_id); return AjaxMsg.newSuccess().addData("groups", groups).toJson(); } @RequestMapping(value="/saveOrUpdate") @ResponseBody public String saveOrUpdate(HttpServletRequest request,LeagueScorer scorer){ AjaxMsg msg = AjaxMsg.newError(); if(StringUtils.isNotBlank(scorer.getId())){ LeagueScorer s = adminLeagueScorerService.getEntityById(scorer.getId()); s.setS_sort(scorer.getS_sort()); msg = adminLeagueScorerService.update(s); }else{ scorer.setId(UUIDGenerator.getUUID()); msg = adminLeagueScorerService.save(scorer); } return msg.toJson(); } @RequestMapping(value="/delete") @ResponseBody public String delete(HttpServletRequest request){ String id = request.getParameter("id"); AjaxMsg msg = adminLeagueScorerService.delete(id); return msg.toJson(); } @RequestMapping(value="/userDialog") public String userDialog(HttpServletRequest request){ return "admin/leaguescorer/user_dialog"; } @RequestMapping(value="/recordDialog") public String recordDialog(HttpServletRequest request){ String league_id = request.getParameter("league_id"); request.setAttribute("league_id", league_id); return "admin/leaguescorer/record_dialog"; } /** * 更新射手榜 * @param request * @return */ @RequestMapping(value="/updateScorer") @ResponseBody public String updateScorer(HttpServletRequest request){ String league_id = request.getParameter("league_id"); try { AjaxMsg msg = adminLeagueScorerService.updateScorer(league_id); return msg.toJson(); } catch (Exception e) { logger.error(e); return AjaxMsg.newError().toJson(); } } }
5,106
0.753244
0.752851
140
34.328571
23.84996
88
false
false
0
0
0
0
0
0
1.857143
false
false
2
9e7fad2c760350230c27fe9977d685e01912af86
22,333,830,008,216
dea7b1e67ba6da9632cb73041b9ad7ec82699774
/src/main/java/com/ltsllc/miranda/operations/Operation.java
bea53e9082011ba938d760556493d59d182dd566
[ "Apache-2.0" ]
permissive
miranda-messaging/miranda
https://github.com/miranda-messaging/miranda
fb7637e6b84a04a9cfc3b481087a113d3fffbd09
cda603f6ae41d2b9c953f1526e2cd7d908c33af5
refs/heads/master
2022-07-08T23:17:14.457000
2019-08-12T20:40:04
2019-08-12T20:40:04
96,714,204
2
1
Apache-2.0
false
2022-07-07T20:57:12
2017-07-09T22:06:55
2019-08-12T20:40:30
2022-07-07T20:57:10
19,597
2
1
8
Java
false
false
/* * Copyright 2017 Long Term Software LLC * * 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.ltsllc.miranda.operations; import com.ltsllc.miranda.Consumer; import com.ltsllc.miranda.Message; import com.ltsllc.miranda.clientinterface.MirandaException; import com.ltsllc.miranda.session.Session; import java.util.UUID; import java.util.concurrent.BlockingQueue; /** * Created by Clark on 4/16/2017. */ public class Operation extends Consumer { protected Session session; private BlockingQueue<Message> requester; private UUID uuid; public String getUUIDString () { if (null == uuid) { uuid = UUID.randomUUID(); } return uuid.toString(); } public BlockingQueue<Message> getRequester() { return requester; } public Operation(String name, BlockingQueue<Message> requester, Session session) throws MirandaException { super(name); this.requester = requester; this.session = session; } public Operation(String name, BlockingQueue<Message> requester) { super(name); this.requester = requester; } public Session getSession() { return session; } }
UTF-8
Java
1,719
java
Operation.java
Java
[ { "context": ".util.concurrent.BlockingQueue;\n\n/**\n * Created by Clark on 4/16/2017.\n */\npublic class Operation extends ", "end": 912, "score": 0.9935973882675171, "start": 907, "tag": "NAME", "value": "Clark" } ]
null
[]
/* * Copyright 2017 Long Term Software LLC * * 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.ltsllc.miranda.operations; import com.ltsllc.miranda.Consumer; import com.ltsllc.miranda.Message; import com.ltsllc.miranda.clientinterface.MirandaException; import com.ltsllc.miranda.session.Session; import java.util.UUID; import java.util.concurrent.BlockingQueue; /** * Created by Clark on 4/16/2017. */ public class Operation extends Consumer { protected Session session; private BlockingQueue<Message> requester; private UUID uuid; public String getUUIDString () { if (null == uuid) { uuid = UUID.randomUUID(); } return uuid.toString(); } public BlockingQueue<Message> getRequester() { return requester; } public Operation(String name, BlockingQueue<Message> requester, Session session) throws MirandaException { super(name); this.requester = requester; this.session = session; } public Operation(String name, BlockingQueue<Message> requester) { super(name); this.requester = requester; } public Session getSession() { return session; } }
1,719
0.69808
0.689354
62
26.725807
25.224264
110
false
false
0
0
0
0
0
0
0.435484
false
false
2
e04094f3f2a3256eb49ae0a806dd0d151a74a9eb
31,052,613,572,809
48c9bd96bcd49dde636ef6abc66e3bb3237b1369
/src/com/carlosrobertofreire/whiteboard/algorithm/BinarySearch.java
e15011a1706ae0ff0e1d005d7576fc9de7b991dc
[]
no_license
carlosrvff/whiteboard
https://github.com/carlosrvff/whiteboard
b5ed42bfe6124276f8d3cd541ea84e5165fbaae2
96e263349cbad95a2ec5dbe693f3841d110ae643
refs/heads/master
2020-04-16T10:50:41.044000
2019-03-19T18:39:21
2019-03-19T18:39:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.carlosrobertofreire.whiteboard.algorithm; /** * @author carlosrobertofreire * */ public class BinarySearch { /** * O(log n) - Logarithmic */ public boolean searchRecursive(int[] array, int key) { if (array == null || array.length == 0) { throw new IllegalArgumentException("Array must have values!"); } return searchRecursive(array, key, 0, array.length - 1); } private boolean searchRecursive(int[] array, int key, int startIndex, int endIndex) { if (startIndex > endIndex) { return false; } int middleIndex = (startIndex + endIndex) / 2; if (array[middleIndex] > key) { return searchRecursive(array, key, startIndex, middleIndex - 1); } else if (array[middleIndex] < key) { return searchRecursive(array, key, middleIndex + 1, endIndex); } else { return true; } } /** * O(log n) - Logarithmic */ public boolean searchIterative(int[] array, int key) { if (array == null || array.length == 0) { throw new IllegalArgumentException("Array must have values!"); } int startIndex = 0; int endIndex = array.length - 1; while (startIndex <= endIndex) { int middleIndex = (startIndex + endIndex) / 2; if (array[middleIndex] > key) { endIndex = middleIndex - 1; } else if (array[middleIndex] < key) { startIndex = middleIndex + 1; } else { return true; } } return false; } }
UTF-8
Java
1,380
java
BinarySearch.java
Java
[ { "context": "obertofreire.whiteboard.algorithm;\n\n/**\n * @author carlosrobertofreire\n *\n */\npublic class BinarySearch {\n\n\t/**\n\t * O(lo", "end": 89, "score": 0.9988827705383301, "start": 70, "tag": "USERNAME", "value": "carlosrobertofreire" } ]
null
[]
package com.carlosrobertofreire.whiteboard.algorithm; /** * @author carlosrobertofreire * */ public class BinarySearch { /** * O(log n) - Logarithmic */ public boolean searchRecursive(int[] array, int key) { if (array == null || array.length == 0) { throw new IllegalArgumentException("Array must have values!"); } return searchRecursive(array, key, 0, array.length - 1); } private boolean searchRecursive(int[] array, int key, int startIndex, int endIndex) { if (startIndex > endIndex) { return false; } int middleIndex = (startIndex + endIndex) / 2; if (array[middleIndex] > key) { return searchRecursive(array, key, startIndex, middleIndex - 1); } else if (array[middleIndex] < key) { return searchRecursive(array, key, middleIndex + 1, endIndex); } else { return true; } } /** * O(log n) - Logarithmic */ public boolean searchIterative(int[] array, int key) { if (array == null || array.length == 0) { throw new IllegalArgumentException("Array must have values!"); } int startIndex = 0; int endIndex = array.length - 1; while (startIndex <= endIndex) { int middleIndex = (startIndex + endIndex) / 2; if (array[middleIndex] > key) { endIndex = middleIndex - 1; } else if (array[middleIndex] < key) { startIndex = middleIndex + 1; } else { return true; } } return false; } }
1,380
0.651449
0.642754
55
24.09091
22.890469
86
false
false
0
0
0
0
0
0
2.272727
false
false
2
c3ae62f45b1ad5bd53c289e08fe1ddabf32499b1
31,052,613,572,271
a6093ea778f22dedd56e85d6746acf2c97595e38
/00-code/zl-maindir/zl-basics-order/src/main/java/com/ebeijia/zl/shop/dao/order/service/ITbEcomPayOrderService.java
382d6103f06396e19b041fc409ced65131ddb1e1
[]
no_license
wang-shun/zhiliaoqifu
https://github.com/wang-shun/zhiliaoqifu
16f51ab0d2a2526e1d068740626adcb4fa245f48
3ad62e59842b0b53807dd568c12e867de70cde62
refs/heads/master
2022-01-17T09:03:35.538000
2019-02-19T09:51:35
2019-02-19T09:51:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ebeijia.zl.shop.dao.order.service; import com.ebeijia.zl.shop.dao.order.domain.TbEcomPayOrder; import com.baomidou.mybatisplus.extension.service.IService; /** * * 渠道支付交易表 Service 接口类 * * @User zl_shop * @Date 2018-12-26 */ public interface ITbEcomPayOrderService extends IService<TbEcomPayOrder> { }
UTF-8
Java
341
java
ITbEcomPayOrderService.java
Java
[ { "context": "ervice;\n\n/**\n *\n * 渠道支付交易表 Service 接口类\n *\n * @User zl_shop\n * @Date 2018-12-26\n */\npublic interface ITbEcomP", "end": 218, "score": 0.9994717836380005, "start": 211, "tag": "USERNAME", "value": "zl_shop" } ]
null
[]
package com.ebeijia.zl.shop.dao.order.service; import com.ebeijia.zl.shop.dao.order.domain.TbEcomPayOrder; import com.baomidou.mybatisplus.extension.service.IService; /** * * 渠道支付交易表 Service 接口类 * * @User zl_shop * @Date 2018-12-26 */ public interface ITbEcomPayOrderService extends IService<TbEcomPayOrder> { }
341
0.76324
0.738318
15
20.4
25.085985
74
false
false
0
0
0
0
0
0
0.2
false
false
2
3b998d7dd8814b2a712077bbacfa38a979990575
17,282,948,412,324
d7cc3ed73c3d0286c8bf2b063c81f393d6ba450d
/ZPOLab3zad1Gradle/src/main/java/Main.java
cf293502fd2461b57fcc9fdec73878929a025490
[]
no_license
ArtemisiaN7/ZPOLab3
https://github.com/ArtemisiaN7/ZPOLab3
b52184966590c2a89d6f6a36bf5e1e1469840661
fa5069ba4d5f2a8e4bbaa5560030027f5dbf6c13
refs/heads/master
2020-08-29T18:26:01.991000
2019-10-28T19:27:55
2019-10-28T19:27:55
218,127,618
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com.opencsv.bean.ColumnPositionMappingStrategy; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; public class Main { public static int earningsAboveQty ( ArrayList <LancasterWorker> workersList, int aboveHowMuch){ int count = 0; for (int i = 0; i <= workersList.size()-1; i++){ if(workersList.get(i).getSalary()>aboveHowMuch) count ++; } return count; } public static int earningsBelowQty ( ArrayList <LancasterWorker> workersList, int belowHowMuch){ int count = 0; for (int i = 0; i <= workersList.size()-1; i++){ if(workersList.get(i).getSalary()<belowHowMuch) count ++; } return count; } public static void averageSalary ( ArrayList <LancasterWorker> workersList){ double salarySum = 0; int count = 0; for (int i = 0; i <= workersList.size()-1; i++){ if(workersList.get(i).getSalary()>0) { salarySum += workersList.get(i).getSalary(); count++; } } double avg = salarySum/count; System.out.println("Średnia pensji wynosi: " + avg); } public static int howManyDistrict ( ArrayList <LancasterWorker> workersList){ Set<String> set = new HashSet<>(); for(int i = 0; i<workersList.size()-1; i++) set.add(workersList.get(i).getDistrict()); return set.size(); } public static void main(String[] args) throws IOException { String fileName = "src\\main\\resources\\Lancaster_County_School_Salaries.csv"; try(Reader reader = Files.newBufferedReader(Paths.get(fileName))){ ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy(); strategy.setType(CSVReaderStrategy.class); String [] memberFieldsToBindTo = {"name", "surname","salary","district","position"}; strategy.setColumnMapping(memberFieldsToBindTo); CsvToBean<CSVReaderStrategy> csvToBean = new CsvToBeanBuilder(reader).withMappingStrategy(strategy) .withSkipLines(1) .withIgnoreLeadingWhiteSpace(true).build(); Iterator<CSVReaderStrategy> iterator = csvToBean.iterator(); ArrayList <LancasterWorker> workersList = new ArrayList<>(); while (iterator.hasNext()){ CSVReaderStrategy item = iterator.next(); LancasterWorker w = new LancasterWorker(item.getName(),item.getSurname(), item.getSalary(), item.getDistrict(), item.getPosition()); workersList.add(w); } for (int i=0; i<=workersList.size()-1;i++){ System.out.println(workersList.get(i).toString()); } System.out.println("Pensji powyżej 25000 jest: " + earningsAboveQty(workersList,25000) ); System.out.println("Pensji poniżej 25000 jest: " + earningsBelowQty(workersList,25000) ); averageSalary(workersList); System.out.println("Liczba dystryktów: " + howManyDistrict(workersList)); } } }
UTF-8
Java
3,487
java
Main.java
Java
[ { "context": " String [] memberFieldsToBindTo = {\"name\", \"surname\",\"salary\",\"district\",\"position\"};\r\n ", "end": 2093, "score": 0.70991051197052, "start": 2089, "tag": "NAME", "value": "name" }, { "context": " String [] memberFieldsToBindTo = {\"name\...
null
[]
import com.opencsv.bean.ColumnPositionMappingStrategy; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; public class Main { public static int earningsAboveQty ( ArrayList <LancasterWorker> workersList, int aboveHowMuch){ int count = 0; for (int i = 0; i <= workersList.size()-1; i++){ if(workersList.get(i).getSalary()>aboveHowMuch) count ++; } return count; } public static int earningsBelowQty ( ArrayList <LancasterWorker> workersList, int belowHowMuch){ int count = 0; for (int i = 0; i <= workersList.size()-1; i++){ if(workersList.get(i).getSalary()<belowHowMuch) count ++; } return count; } public static void averageSalary ( ArrayList <LancasterWorker> workersList){ double salarySum = 0; int count = 0; for (int i = 0; i <= workersList.size()-1; i++){ if(workersList.get(i).getSalary()>0) { salarySum += workersList.get(i).getSalary(); count++; } } double avg = salarySum/count; System.out.println("Średnia pensji wynosi: " + avg); } public static int howManyDistrict ( ArrayList <LancasterWorker> workersList){ Set<String> set = new HashSet<>(); for(int i = 0; i<workersList.size()-1; i++) set.add(workersList.get(i).getDistrict()); return set.size(); } public static void main(String[] args) throws IOException { String fileName = "src\\main\\resources\\Lancaster_County_School_Salaries.csv"; try(Reader reader = Files.newBufferedReader(Paths.get(fileName))){ ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy(); strategy.setType(CSVReaderStrategy.class); String [] memberFieldsToBindTo = {"name", "surname","salary","district","position"}; strategy.setColumnMapping(memberFieldsToBindTo); CsvToBean<CSVReaderStrategy> csvToBean = new CsvToBeanBuilder(reader).withMappingStrategy(strategy) .withSkipLines(1) .withIgnoreLeadingWhiteSpace(true).build(); Iterator<CSVReaderStrategy> iterator = csvToBean.iterator(); ArrayList <LancasterWorker> workersList = new ArrayList<>(); while (iterator.hasNext()){ CSVReaderStrategy item = iterator.next(); LancasterWorker w = new LancasterWorker(item.getName(),item.getSurname(), item.getSalary(), item.getDistrict(), item.getPosition()); workersList.add(w); } for (int i=0; i<=workersList.size()-1;i++){ System.out.println(workersList.get(i).toString()); } System.out.println("Pensji powyżej 25000 jest: " + earningsAboveQty(workersList,25000) ); System.out.println("Pensji poniżej 25000 jest: " + earningsBelowQty(workersList,25000) ); averageSalary(workersList); System.out.println("Liczba dystryktów: " + howManyDistrict(workersList)); } } }
3,487
0.582544
0.572208
86
38.476746
33.220451
115
false
false
0
0
0
0
0
0
0.709302
false
false
2
ce7715df36de600b309214f4b52bf4590d79a6a1
21,380,347,236,435
88e44207335d2781310ad108d8a48bac2a521509
/LabFX/src/org/ilpider/labfx/model/Giocatore.java
99d5d6225257c1f6f0d4912a46e22e909af22068
[]
no_license
nmesisca/LabFX
https://github.com/nmesisca/LabFX
b8a23669976aa1465c66e88b8aaf64bb62ca5194
6526b002c85cd8220ebc42f2ee90158a5e47a4dc
refs/heads/master
2020-07-21T15:37:44.729000
2015-10-05T12:53:00
2015-10-05T12:53:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ilpider.labfx.model; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.ilpider.labfx.view.ControllerLayoutGiocatore; import javafx.fxml.FXMLLoader; import javafx.scene.layout.GridPane; public class Giocatore { private int IDGiocatore; private String nomeGiocatore; private int puntiGiocatore; private int puntiCaricati; private GridPane viewGiocatore; private ControllerLayoutGiocatore controllerLayoutGiocatore; private boolean tuttoChiuso; private boolean winner; private int numeri = 21; // quanti sono i "numeri" sul tabellone - - DEFAULT 21 private Partita partitaModel; private List<RigaNumero> listRigaNumero; private RigaNumero rigaNumeroFix; /* * Costruttori */ public Giocatore(int IDGiocatore) { super(); this.setIDGiocatore(IDGiocatore); this.puntiGiocatore = 0; this.puntiCaricati = 0; this.setTuttoChiuso(false); // this.setWinner(false); setViewGiocatore(); creaListRigaNumero(); } /* * metodi */ public void contaAperti() { listRigaNumero.forEach(n -> System.out.println(n.getNumero() + "" + n.isChiuso())); Stream<RigaNumero> righeAperte = listRigaNumero.stream().filter( n -> !n.isChiuso()); // righeAperte.forEach(r -> System.out.println(r.puntiDaAperte())); // controllerLayoutGiocatore.setTxtPunti(getPuntiGiocatore() + " totalizza: " ); righeAperte.forEach(a -> puntiGiocatore = puntiGiocatore + a.puntiDaAperte()); } /* * getters e setters */ public int getIDGiocatore() { return IDGiocatore; } public void setIDGiocatore(int iDGiocatore) { IDGiocatore = iDGiocatore; } public String getNomeGiocatore() { return nomeGiocatore; } public void setNomeGiocatore(String nomeGiocatore) { this.nomeGiocatore = nomeGiocatore; controllerLayoutGiocatore.setTxtNome(this.nomeGiocatore); } public int getPuntiGiocatore() { return puntiGiocatore; } public void setPuntiGiocatore(int i) { this.puntiGiocatore = i; controllerLayoutGiocatore.setTxtPunti("" + i); } public int getPuntiCaricati() { return puntiCaricati; } public void setPuntiCaricati(int puntiCaricati) { this.puntiCaricati = puntiCaricati; controllerLayoutGiocatore.setLblPuntiCaricati(puntiCaricati); } public GridPane getViewGiocatore() { return viewGiocatore; } private void setViewGiocatore() { try { FXMLLoader loaderViewGiocatore = new FXMLLoader(); loaderViewGiocatore.setLocation(getClass().getResource( "/org/ilpider/labfx/view/LayoutGiocatore.fxml")); this.viewGiocatore = loaderViewGiocatore.load(); controllerLayoutGiocatore = loaderViewGiocatore.getController(); controllerLayoutGiocatore.setGiocatoreModel(this); } catch (Exception e) { e.printStackTrace(); } } public boolean isTuttoChiuso() { if (listRigaNumero.stream().allMatch(n -> n.isChiuso())) { tuttoChiuso = true; return tuttoChiuso; } else { tuttoChiuso = false; return tuttoChiuso; } } public void setTuttoChiuso(boolean tuttoChiuso) { this.tuttoChiuso = tuttoChiuso; } public boolean isWinner() { winner = partitaModel.esisteWinner(); return winner; } public void setWinner(boolean winner) { this.winner = winner; } public List<RigaNumero> getListRigaNumero() { return listRigaNumero; } public void creaListRigaNumero() { listRigaNumero = new ArrayList<RigaNumero>(); for (int i = 0; i < numeri; i++) { rigaNumeroFix = new RigaNumero(i); rigaNumeroFix.setGiocatoreModel(this); rigaNumeroFix.getLayoutRigaNumero().autosize(); listRigaNumero.add(rigaNumeroFix); viewGiocatore.add(rigaNumeroFix.getLayoutRigaNumero(), 0, 3 + i); } } public Partita getPartitaModel() { return partitaModel; } public void setPartitaModel(Partita partitaModel) { this.partitaModel = partitaModel; } public void scriviPuntiFinali(int puntiGiocatore) { controllerLayoutGiocatore.setLblPuntiFinali(puntiGiocatore); } // public ControllerLayoutGiocatore getControllerLayoutGiocatore() { // return controllerLayoutGiocatore; // } }
UTF-8
Java
4,069
java
Giocatore.java
Java
[]
null
[]
package org.ilpider.labfx.model; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.ilpider.labfx.view.ControllerLayoutGiocatore; import javafx.fxml.FXMLLoader; import javafx.scene.layout.GridPane; public class Giocatore { private int IDGiocatore; private String nomeGiocatore; private int puntiGiocatore; private int puntiCaricati; private GridPane viewGiocatore; private ControllerLayoutGiocatore controllerLayoutGiocatore; private boolean tuttoChiuso; private boolean winner; private int numeri = 21; // quanti sono i "numeri" sul tabellone - - DEFAULT 21 private Partita partitaModel; private List<RigaNumero> listRigaNumero; private RigaNumero rigaNumeroFix; /* * Costruttori */ public Giocatore(int IDGiocatore) { super(); this.setIDGiocatore(IDGiocatore); this.puntiGiocatore = 0; this.puntiCaricati = 0; this.setTuttoChiuso(false); // this.setWinner(false); setViewGiocatore(); creaListRigaNumero(); } /* * metodi */ public void contaAperti() { listRigaNumero.forEach(n -> System.out.println(n.getNumero() + "" + n.isChiuso())); Stream<RigaNumero> righeAperte = listRigaNumero.stream().filter( n -> !n.isChiuso()); // righeAperte.forEach(r -> System.out.println(r.puntiDaAperte())); // controllerLayoutGiocatore.setTxtPunti(getPuntiGiocatore() + " totalizza: " ); righeAperte.forEach(a -> puntiGiocatore = puntiGiocatore + a.puntiDaAperte()); } /* * getters e setters */ public int getIDGiocatore() { return IDGiocatore; } public void setIDGiocatore(int iDGiocatore) { IDGiocatore = iDGiocatore; } public String getNomeGiocatore() { return nomeGiocatore; } public void setNomeGiocatore(String nomeGiocatore) { this.nomeGiocatore = nomeGiocatore; controllerLayoutGiocatore.setTxtNome(this.nomeGiocatore); } public int getPuntiGiocatore() { return puntiGiocatore; } public void setPuntiGiocatore(int i) { this.puntiGiocatore = i; controllerLayoutGiocatore.setTxtPunti("" + i); } public int getPuntiCaricati() { return puntiCaricati; } public void setPuntiCaricati(int puntiCaricati) { this.puntiCaricati = puntiCaricati; controllerLayoutGiocatore.setLblPuntiCaricati(puntiCaricati); } public GridPane getViewGiocatore() { return viewGiocatore; } private void setViewGiocatore() { try { FXMLLoader loaderViewGiocatore = new FXMLLoader(); loaderViewGiocatore.setLocation(getClass().getResource( "/org/ilpider/labfx/view/LayoutGiocatore.fxml")); this.viewGiocatore = loaderViewGiocatore.load(); controllerLayoutGiocatore = loaderViewGiocatore.getController(); controllerLayoutGiocatore.setGiocatoreModel(this); } catch (Exception e) { e.printStackTrace(); } } public boolean isTuttoChiuso() { if (listRigaNumero.stream().allMatch(n -> n.isChiuso())) { tuttoChiuso = true; return tuttoChiuso; } else { tuttoChiuso = false; return tuttoChiuso; } } public void setTuttoChiuso(boolean tuttoChiuso) { this.tuttoChiuso = tuttoChiuso; } public boolean isWinner() { winner = partitaModel.esisteWinner(); return winner; } public void setWinner(boolean winner) { this.winner = winner; } public List<RigaNumero> getListRigaNumero() { return listRigaNumero; } public void creaListRigaNumero() { listRigaNumero = new ArrayList<RigaNumero>(); for (int i = 0; i < numeri; i++) { rigaNumeroFix = new RigaNumero(i); rigaNumeroFix.setGiocatoreModel(this); rigaNumeroFix.getLayoutRigaNumero().autosize(); listRigaNumero.add(rigaNumeroFix); viewGiocatore.add(rigaNumeroFix.getLayoutRigaNumero(), 0, 3 + i); } } public Partita getPartitaModel() { return partitaModel; } public void setPartitaModel(Partita partitaModel) { this.partitaModel = partitaModel; } public void scriviPuntiFinali(int puntiGiocatore) { controllerLayoutGiocatore.setLblPuntiFinali(puntiGiocatore); } // public ControllerLayoutGiocatore getControllerLayoutGiocatore() { // return controllerLayoutGiocatore; // } }
4,069
0.740968
0.738756
173
22.520231
21.311504
81
false
false
0
0
0
0
0
0
1.699422
false
false
2
d5c80090869b9e5e710f2ed383046f8608385b82
13,632,226,230,268
ef732e6b1d52d93edf111f07b871c5e40f2ebe75
/TicketClient.java
38c9185324b1c195310d671d3d1709e7308b8655
[]
no_license
susandriskill/itc-115-assignment-10
https://github.com/susandriskill/itc-115-assignment-10
8b6b7027880d125b27e3f6a8fb53dd98ba6245fd
292a9eeb6d506d51473367d4c5921e5bb049a4c3
refs/heads/master
2021-04-21T08:55:44.615000
2020-03-24T20:00:11
2020-03-24T20:00:11
249,767,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//------------------------------------------------------------------------------ //A Client to test the Ticket, WalkupTicket, and AdvanceTicket Classes. public class TicketClient { public static void main(String[] args) { WalkupTicket(); AdvanceTicket(); } //Test walk-up ticket sale. public static void WalkupTicket() { for (int i = 1001; i <= 1005; i++) { WalkupTicket ticket = new WalkupTicket (i); System.out.println(ticket); } } //Test advance ticket sale with the two different prices. public static void AdvanceTicket() { int numberOfDaysInAdvance = 1; for (int i = 200; i <= 220; i++) { AdvanceTicket ticket = new AdvanceTicket(i, numberOfDaysInAdvance); System.out.println(ticket); numberOfDaysInAdvance += 1; } } }
UTF-8
Java
770
java
TicketClient.java
Java
[]
null
[]
//------------------------------------------------------------------------------ //A Client to test the Ticket, WalkupTicket, and AdvanceTicket Classes. public class TicketClient { public static void main(String[] args) { WalkupTicket(); AdvanceTicket(); } //Test walk-up ticket sale. public static void WalkupTicket() { for (int i = 1001; i <= 1005; i++) { WalkupTicket ticket = new WalkupTicket (i); System.out.println(ticket); } } //Test advance ticket sale with the two different prices. public static void AdvanceTicket() { int numberOfDaysInAdvance = 1; for (int i = 200; i <= 220; i++) { AdvanceTicket ticket = new AdvanceTicket(i, numberOfDaysInAdvance); System.out.println(ticket); numberOfDaysInAdvance += 1; } } }
770
0.612987
0.592208
30
24.700001
23.448029
80
false
false
0
0
0
0
0
0
1.833333
false
false
2
74cf8c52066ec2d6f8e373f5fc59314aaf338640
8,392,366,123,575
91041c3aa66e3c14d7b23e516eed052b5cf121a5
/src/main/java/com/mypj/entity/Result.java
ec4badae84edcfd066aff7da41440caaf1155096
[]
no_license
jikeMisma/travels
https://github.com/jikeMisma/travels
f24acf1bbc7d99fe4112545c1a619fd445adb1bc
6dbd73bb6421f1a38531f5a9a1afeccd68938266
refs/heads/master
2023-03-10T07:17:35.519000
2020-06-11T07:07:08
2020-06-11T07:07:08
270,231,098
3
0
null
false
2023-02-22T08:28:37
2020-06-07T07:37:32
2022-01-20T12:47:47
2023-02-22T08:28:36
309
1
0
1
HTML
false
false
package com.mypj.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * @author mazhicheng * @date 2020/6/6 - 14:48 */ @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) public class Result { private Boolean states = true; private String mag; private String userId; }
UTF-8
Java
390
java
Result.java
Java
[ { "context": "ort lombok.experimental.Accessors;\n\n/**\n * @author mazhicheng\n * @date 2020/6/6 - 14:48\n */\n\n@Data\n@AllArgsCons", "end": 177, "score": 0.9989614486694336, "start": 167, "tag": "USERNAME", "value": "mazhicheng" } ]
null
[]
package com.mypj.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * @author mazhicheng * @date 2020/6/6 - 14:48 */ @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) public class Result { private Boolean states = true; private String mag; private String userId; }
390
0.746154
0.720513
22
16.727272
12.497933
37
false
false
0
0
0
0
0
0
0.363636
false
false
2
ed5b565766858688ee0af77bfad299a401963579
21,285,857,937,250
95adaee4ed8fc885b344eaa11758879848effafc
/Mosdan/Moadan3/MosdanOpening/src/ui/Tx_Perference.java
ee5d5e6c088d558863214a57ca5bb7b1ecdb7eca
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LinZap/Mosdan_VW
https://github.com/LinZap/Mosdan_VW
1a3f57b5206cb027ff453418f78a1041622cd75a
33f96471af7ca88cc89063943d9af4f67ce2d434
refs/heads/master
2016-09-05T18:42:53.424000
2013-08-30T08:22:07
2013-08-30T08:22:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ui; import Data.Data; import Internet.Turbo_View; import TV.Mosdan2.R; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; public class Tx_Perference extends PreferenceFragment implements OnSharedPreferenceChangeListener { private ListPreference tx_mode, ati_mode; private EditTextPreference name, explain; private Preference ip, mac, port; public Tx_Perference(int i) { Data.index_tx = i; } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.france2); // find element name = (EditTextPreference) findPreference("name"); explain = (EditTextPreference) findPreference("hint"); tx_mode = (ListPreference) findPreference("tx_mode"); ati_mode = (ListPreference) findPreference("ati_mode"); ip = findPreference("ipaddress"); mac = findPreference("macaddress"); port = findPreference("port"); if (Data.Tx_status[Data.index_tx] == R.drawable.not_connection) { name.setEnabled(false); explain.setEnabled(false); tx_mode.setEnabled(false); ati_mode.setEnabled(false); } name.setSummary(Data.Tx_name[Data.index_tx]); name.setText(Data.Tx_name[Data.index_tx]); explain.setSummary(Data.Tx_explain[Data.index_tx]); explain.setText(Data.Tx_explain[Data.index_tx]); // information ok ip.setSummary(Data.Tx_ip[Data.index_tx]); mac.setSummary(Data.Tx_mac[Data.index_tx]); port.setSummary("unknow"); tx_mode.setSummary(Data.Tx_mode[Data.index_tx]); ati_mode.setSummary(Data.Tx_ati_mode[Data.index_tx]); tx_mode.setValue(Data.Tx_mode[Data.index_tx]); ati_mode.setValue(Data.Tx_ati_mode[Data.index_tx]); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO Auto-generated method stub if (key.equals("name")) { String s = name.getEditText().getText().toString(); new Mycommand() { @Override public void command() { Turbo_View t = new Turbo_View(); t.TR_rename(Data.Tx_mac[Data.index_tx], name.getEditText() .getText().toString()); } }.start(); for (int i = 0; i < Data.Situation_srctx.length; i++) if (Data.Tx_name[Data.index_tx].equals(Data.Situation_srctx[i])) Data.Situation_srctx[i] = s; Data.Tx_name[Data.index_tx] = s; name.setSummary(s); } else if (key.equals("hint")) { new Mycommand() { @Override public void command() { Turbo_View t = new Turbo_View(); t.TR_explain(Data.Tx_mac[Data.index_tx], explain .getEditText().getText().toString()); } }.start(); Data.Tx_explain[Data.index_tx] = explain.getEditText().getText() .toString(); explain.setSummary(explain.getEditText().getText().toString()); } else if (key.equals("tx_mode")) { new Mycommand() { @Override public void command() { Turbo_View t = new Turbo_View(); t.Tx_setMode(Data.Tx_mac[Data.index_tx], tx_mode.getValue() .toString().equals("Graphic") ? 0 : 1); } }.start(); Data.Tx_mode[Data.index_tx] = tx_mode.getValue().toString(); tx_mode.setSummary(tx_mode.getValue()); } else if (key.equals("ati_mode")) { new Mycommand() { @Override public void command() { int i = 0; String ati = ati_mode.getValue().toString(); if (ati.equals("OFF")) i = 0; else if (ati.equals("Type 1")) i = 1; else i = 2; Turbo_View t = new Turbo_View(); t.Tx_setATIMode(Data.Tx_mac[Data.index_tx], i); } }.start(); Data.Tx_ati_mode[Data.index_tx] = ati_mode.getValue().toString(); ati_mode.setSummary(ati_mode.getValue()); } } @Override public void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } }
UTF-8
Java
4,343
java
Tx_Perference.java
Java
[ { "context": "mode.getValue());\n\n\t\t}\n\n\t\telse if (key.equals(\"ati_mode\")) {\n\n\t\t\tnew Mycommand() {\n\t\t\t\t@Override\n\t\t\t\tpubl", "end": 3442, "score": 0.6963486075401306, "start": 3438, "tag": "KEY", "value": "mode" } ]
null
[]
package ui; import Data.Data; import Internet.Turbo_View; import TV.Mosdan2.R; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; public class Tx_Perference extends PreferenceFragment implements OnSharedPreferenceChangeListener { private ListPreference tx_mode, ati_mode; private EditTextPreference name, explain; private Preference ip, mac, port; public Tx_Perference(int i) { Data.index_tx = i; } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.france2); // find element name = (EditTextPreference) findPreference("name"); explain = (EditTextPreference) findPreference("hint"); tx_mode = (ListPreference) findPreference("tx_mode"); ati_mode = (ListPreference) findPreference("ati_mode"); ip = findPreference("ipaddress"); mac = findPreference("macaddress"); port = findPreference("port"); if (Data.Tx_status[Data.index_tx] == R.drawable.not_connection) { name.setEnabled(false); explain.setEnabled(false); tx_mode.setEnabled(false); ati_mode.setEnabled(false); } name.setSummary(Data.Tx_name[Data.index_tx]); name.setText(Data.Tx_name[Data.index_tx]); explain.setSummary(Data.Tx_explain[Data.index_tx]); explain.setText(Data.Tx_explain[Data.index_tx]); // information ok ip.setSummary(Data.Tx_ip[Data.index_tx]); mac.setSummary(Data.Tx_mac[Data.index_tx]); port.setSummary("unknow"); tx_mode.setSummary(Data.Tx_mode[Data.index_tx]); ati_mode.setSummary(Data.Tx_ati_mode[Data.index_tx]); tx_mode.setValue(Data.Tx_mode[Data.index_tx]); ati_mode.setValue(Data.Tx_ati_mode[Data.index_tx]); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO Auto-generated method stub if (key.equals("name")) { String s = name.getEditText().getText().toString(); new Mycommand() { @Override public void command() { Turbo_View t = new Turbo_View(); t.TR_rename(Data.Tx_mac[Data.index_tx], name.getEditText() .getText().toString()); } }.start(); for (int i = 0; i < Data.Situation_srctx.length; i++) if (Data.Tx_name[Data.index_tx].equals(Data.Situation_srctx[i])) Data.Situation_srctx[i] = s; Data.Tx_name[Data.index_tx] = s; name.setSummary(s); } else if (key.equals("hint")) { new Mycommand() { @Override public void command() { Turbo_View t = new Turbo_View(); t.TR_explain(Data.Tx_mac[Data.index_tx], explain .getEditText().getText().toString()); } }.start(); Data.Tx_explain[Data.index_tx] = explain.getEditText().getText() .toString(); explain.setSummary(explain.getEditText().getText().toString()); } else if (key.equals("tx_mode")) { new Mycommand() { @Override public void command() { Turbo_View t = new Turbo_View(); t.Tx_setMode(Data.Tx_mac[Data.index_tx], tx_mode.getValue() .toString().equals("Graphic") ? 0 : 1); } }.start(); Data.Tx_mode[Data.index_tx] = tx_mode.getValue().toString(); tx_mode.setSummary(tx_mode.getValue()); } else if (key.equals("ati_mode")) { new Mycommand() { @Override public void command() { int i = 0; String ati = ati_mode.getValue().toString(); if (ati.equals("OFF")) i = 0; else if (ati.equals("Type 1")) i = 1; else i = 2; Turbo_View t = new Turbo_View(); t.Tx_setATIMode(Data.Tx_mac[Data.index_tx], i); } }.start(); Data.Tx_ati_mode[Data.index_tx] = ati_mode.getValue().toString(); ati_mode.setSummary(ati_mode.getValue()); } } @Override public void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } }
4,343
0.683629
0.681326
163
25.644173
21.362394
75
false
false
0
0
0
0
0
0
2.588957
false
false
2
e051262f9351fd57f9f3d729cf26509474508acf
30,167,850,314,589
4f02c381c2b5ec266315b8854eb3912a31cb87ac
/app/src/main/java/com/example/crypto/Intermediate.java
e54854ecd328b35678d8c9d27cedccf546cb79ad
[ "MIT" ]
permissive
DoodlePain/CryptoApp
https://github.com/DoodlePain/CryptoApp
7960f04fc6f7d038a0a165b8f55c2cfafadef328
00774833c7eff91ced2e2500e527a3727f914472
refs/heads/master
2020-06-27T08:10:30.590000
2019-09-15T18:08:01
2019-09-15T18:08:01
199,894,233
0
0
MIT
false
2019-09-15T18:08:02
2019-07-31T16:43:18
2019-09-14T13:40:06
2019-09-15T18:08:01
1,095
0
0
0
Java
false
false
package com.example.crypto; import android.content.Intent; import android.graphics.Typeface; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Intermediate extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intermediate); Typeface fontFamily = Typeface.createFromAsset(getAssets(), "fonts/montserrat_light.ttf"); TextView t1 = findViewById(R.id.textView11); t1.setTypeface(fontFamily); TextView t2 = findViewById(R.id.textView12); t2.setTypeface(fontFamily); Button b = findViewById(R.id.button3); b.setTypeface(fontFamily); } public void login(View view) { Intent intent = new Intent(this, LoginScreen.class); startActivity(intent); finish(); } }
UTF-8
Java
1,008
java
Intermediate.java
Java
[]
null
[]
package com.example.crypto; import android.content.Intent; import android.graphics.Typeface; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Intermediate extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intermediate); Typeface fontFamily = Typeface.createFromAsset(getAssets(), "fonts/montserrat_light.ttf"); TextView t1 = findViewById(R.id.textView11); t1.setTypeface(fontFamily); TextView t2 = findViewById(R.id.textView12); t2.setTypeface(fontFamily); Button b = findViewById(R.id.button3); b.setTypeface(fontFamily); } public void login(View view) { Intent intent = new Intent(this, LoginScreen.class); startActivity(intent); finish(); } }
1,008
0.710317
0.701389
33
29.545454
22.888519
98
false
false
0
0
0
0
0
0
0.666667
false
false
2
65a70cc21144bbca44d51845e85addde11813067
25,074,019,111,290
c40dc32332c4d46fd7a1bce993f04e7fca705513
/src/test/java/edu/stanford/irt/laneweb/servlet/ValidParameterFilterTest.java
9841ee80400a40221b2f8fdbca60ae8438eaa2b5
[]
no_license
Lane-Library/laneweb
https://github.com/Lane-Library/laneweb
016b79e4f694cbcc090787e7244dc3106f27524a
881282cd6f0eefc453f07e08da26a95e2ea080ad
refs/heads/main
2023-03-03T09:14:41.658000
2023-02-22T21:50:38
2023-02-22T21:50:38
34,027,243
1
1
null
false
2023-02-22T22:25:52
2015-04-16T01:16:01
2022-04-08T23:03:10
2023-02-22T22:25:15
30,998
1
0
0
JavaScript
false
false
package edu.stanford.irt.laneweb.servlet; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.mock; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.io.IOException; import java.util.Collections; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; public class ValidParameterFilterTest { private FilterChain chain; private ValidParameterFilter filter; private HttpServletRequest request; private HttpServletResponse response; @Before public void setUp() throws Exception { this.filter = new ValidParameterFilter(); this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); this.chain = mock(FilterChain.class); } @Test public void testInternalDoFilterEmptyParameterMap() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(Collections.emptyMap()); this.chain.doFilter(this.request, this.response); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } @Test public void testInternalDoFilterInvalidParameter() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(Collections.singletonMap("invalid", new String[] { "value" })); this.response.setStatus(400); this.chain.doFilter(isA(HttpServletRequestWrapper.class), eq(this.response)); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } @Test public void testInternalDoFilterNullParameterMap() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(null); this.chain.doFilter(this.request, this.response); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } @Test public void testInternalDoFilterValidParameter() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(Collections.singletonMap("page", new String[] { "1" })); this.chain.doFilter(this.request, this.response); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } }
UTF-8
Java
2,991
java
ValidParameterFilterTest.java
Java
[]
null
[]
package edu.stanford.irt.laneweb.servlet; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.mock; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.io.IOException; import java.util.Collections; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; public class ValidParameterFilterTest { private FilterChain chain; private ValidParameterFilter filter; private HttpServletRequest request; private HttpServletResponse response; @Before public void setUp() throws Exception { this.filter = new ValidParameterFilter(); this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); this.chain = mock(FilterChain.class); } @Test public void testInternalDoFilterEmptyParameterMap() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(Collections.emptyMap()); this.chain.doFilter(this.request, this.response); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } @Test public void testInternalDoFilterInvalidParameter() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(Collections.singletonMap("invalid", new String[] { "value" })); this.response.setStatus(400); this.chain.doFilter(isA(HttpServletRequestWrapper.class), eq(this.response)); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } @Test public void testInternalDoFilterNullParameterMap() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(null); this.chain.doFilter(this.request, this.response); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } @Test public void testInternalDoFilterValidParameter() throws IOException, ServletException { expect(this.request.getParameterMap()).andReturn(Collections.singletonMap("page", new String[] { "1" })); this.chain.doFilter(this.request, this.response); replay(this.request, this.response, this.chain); this.filter.internalDoFilter(this.request, this.response, this.chain); verify(this.request, this.response, this.chain); } }
2,991
0.735874
0.734537
76
38.355263
30.810843
120
false
false
0
0
0
0
0
0
1.039474
false
false
2
9be1c052a406a69d39ea703bb6585fca0b5c0323
16,793,322,153,781
9a25396727f8fb7bd1430ed38dd8ad385c6bd84a
/src/echanges/Octet.java
e8b2376c2584fc5f7ebc5ff9484fb9ed60344996
[]
no_license
ExLuor/TP1
https://github.com/ExLuor/TP1
675d52049c57eb0369daa187ceb0b5e07547adb0
526ae77d4ba04bafdca36abd231ad14a43af0214
refs/heads/master
2020-04-26T20:54:32.158000
2019-03-06T21:59:01
2019-03-06T21:59:01
173,825,867
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Octet.java // Description: Classe qui représente un octet // Auteurs: // Boulanger, Sammy - 18 058 904 // Durand-Chorel, Michael - 17 141 086 // Leroux, Jérémie - 16 186 994 // Date de fin: 6 mars 2019 // Cours : IFT585 // Entrées du programme : - // Sorties du programme : - package echanges; /** * représentation d'un octet L'objet échangé entre les couches de niveau 1 et 2. * */ public class Octet { private byte value; public Octet() { value = 0; } public Octet(byte octet) { value = octet; } public Octet clone() { return new Octet(value); } public byte getValue() { return this.value; } public void changeBit(int position, boolean bitValue) { if (bitValue) { value |= (1 << position); } else { value &= ~(1 << position); } } public int getBit(int position) { return this.value >> position & 1; } @Override public boolean equals(Object obj) { Octet m = (Octet) obj; if (m == null) { return false; } return (value == m.value); } @Override public String toString() { return String.format("%8s", Integer.toBinaryString(value & 0xFF)).replace(' ', '0'); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
UTF-8
Java
1,501
java
Octet.java
Java
[ { "context": "on: Classe qui représente un octet\n\n// Auteurs:\n// Boulanger, Sammy - 18 058 904\n// Durand-Chorel, Michael - 17", "end": 86, "score": 0.8804598450660706, "start": 77, "tag": "NAME", "value": "Boulanger" }, { "context": "qui représente un octet\n\n// Auteurs:\n// Bou...
null
[]
// Octet.java // Description: Classe qui représente un octet // Auteurs: // Boulanger, Sammy - 18 058 904 // Durand-Chorel, Michael - 17 141 086 // Leroux, Jérémie - 16 186 994 // Date de fin: 6 mars 2019 // Cours : IFT585 // Entrées du programme : - // Sorties du programme : - package echanges; /** * représentation d'un octet L'objet échangé entre les couches de niveau 1 et 2. * */ public class Octet { private byte value; public Octet() { value = 0; } public Octet(byte octet) { value = octet; } public Octet clone() { return new Octet(value); } public byte getValue() { return this.value; } public void changeBit(int position, boolean bitValue) { if (bitValue) { value |= (1 << position); } else { value &= ~(1 << position); } } public int getBit(int position) { return this.value >> position & 1; } @Override public boolean equals(Object obj) { Octet m = (Octet) obj; if (m == null) { return false; } return (value == m.value); } @Override public String toString() { return String.format("%8s", Integer.toBinaryString(value & 0xFF)).replace(' ', '0'); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1,501
0.481928
0.454485
115
12
16.196081
92
false
false
0
0
0
0
0
0
0.173913
false
false
2
7f5e024c8d20cedeb68cdb932f5dd5f213f16036
6,554,120,106,927
062de606d63640f28f04f6a6c9181c58cbb7a8c4
/WLPProject/src/au/wow/WLPmain/tests/DailyDeptMainClass.java
4788ded097726657a90e50f32bb7965b8900ab21
[]
no_license
Joel-Babu/CLR-HigherLevelScreens
https://github.com/Joel-Babu/CLR-HigherLevelScreens
334f0675f22f2163cad83591dae24a30ec330b7f
81ce8980238930b25e1a0e553aa0145a3b760b68
refs/heads/master
2020-09-30T17:29:26.837000
2019-12-11T10:59:31
2019-12-11T10:59:31
227,336,206
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package au.wow.WLPmain.tests; import java.awt.AWTException; import org.testng.ITestContext; import org.testng.annotations.*; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; import com.relevantcodes.extentreports.ExtentReports; import au.wow.WLPmain.objects.DailyPlanningMainObjects; import au.wow.WLPmain.pages.CommonFunctions; import au.wow.WLPmain.pages.DailyPlanningMainPage; import au.wow.WLPmain.pages.WoWLoginPage; import au.wow.wlp.utils.BasePage; import au.wow.wlp.utils.CustomExtentReports; import au.wow.wlp.utils.ExtentReportsScreenshotCode; import au.wow.wlp.utils.SQLWrapper; import au.wow.wlp.utils.TestBase; import au.wow.wlp.utils.TestStatus; import au.wow.wlp.utils.XMLDataReader; public class DailyDeptMainClass extends TestBase { private Logger log = LogManager.getLogger(DailyDeptMainClass.class); TestStatus status; SQLWrapper sql = new SQLWrapper(log); ExtentReportsScreenshotCode ScreenShotUtil; WoWLoginPage loginPage; DailyPlanningMainPage pageDailyItemPrice; DailyPlanningMainPage pageDailyCustomers; DailyPlanningMainPage pageDailyItems; DailyPlanningMainPage pageDailySales; DailyPlanningMainPage pageDailyPaidHours; DailyPlanningMainPage pageDailyWages; // ArticleDetailsPage pageartDetails; DailyPlanningMainPage pageartDetails; DailyPlanningMainObjects objDailyItemPrice; DailyPlanningMainObjects objDailyCustomers; DailyPlanningMainObjects objDailyItems; DailyPlanningMainObjects objDailySales; DailyPlanningMainObjects objDailyPaidHours; DailyPlanningMainObjects objDailyWages; BasePage BaseObj; CommonFunctions common; StoreProperties storeprop; public DailyDeptMainClass() { super.log = log; } /** * AL_1 Verifying Department Hierarchy and Paginations * * @throws Exception */ @Test(description = "Daily Planning Item Price") public void ItemPrice() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); navToDailyDeptPlanItemPrice(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyItemPrice.dropdonw, "8"); click(objDailyItemPrice.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyItemPrice.dailyplan, "Item Price"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyItemPrice.fnCheckOutItemPriceTotal(objDailyItemPrice, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeptPlanItemPrice(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, getReport(), getReportLogger(), WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyItemPrice = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Customers") public void Customers() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntCustomers(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyCustomers.dropdonw, "8"); click(objDailyCustomers.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyCustomers.dailyplan, "Customers"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyCustomers.fnlCheckOutCustomersTotal(objDailyCustomers, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntCustomers(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyCustomers = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Items") public void Items() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntItems(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyItems.dropdonw, "8"); click(objDailyItems.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyItems.dailyplan, "Items"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyItems.fnlCheckOutItemsTotal(objDailyItems, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntItems(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyItems = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Sales") public void Sales() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntSales(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailySales.dropdonw, "8"); click(objDailySales.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailySales.dailyplan, "Sales"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailySales.fnlCheckOutCustomersTotal(objDailySales, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntSales(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailySales = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Paid Hours") public void PaidHours() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntPaidHours(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyPaidHours.dropdonw, "8"); click(objDailyPaidHours.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyPaidHours.dailyplan, "Paid Hours"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyPaidHours.fnlPaidHoursTotal(objDailyPaidHours, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntPaidHours(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyPaidHours = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Wages") public void Wages() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntWages(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyWages.dropdonw, "8"); click(objDailyWages.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyWages.dailyplan, "Wages"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyWages.fnlWagesTotal(objDailyWages, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntWages(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyWages = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @BeforeMethod public void setUpItemPrice(Method m, ITestContext testcontext) throws IOException { System.out.println("test1 - beforemethod"); mName = m.getName().toString().trim(); System.out.println(m.getName().toString().trim()); if (!methodList.contains(m.getName().toString().trim())) { methodList.add(m.getName().toString().trim()); extentTest = report.startTest(m.getName().toString().trim()); } System.out.println(methodList.size()); // initializeTestcontext(); System.out.println("test1 - beforemethod"); log.info("Loading Testdata for the test case: " + m.getName().toString()); data.getTCNameFromChildren(m.getName().toString().trim()); testcontext.setAttribute("WebDriver", getDriver()); testcontext.setAttribute("Customreports", this.customreport); customreport.startTest(m.getName().toString()); initializeTestStatus(); reportPath = new File(getContext().getStringProperty("reportPath")); moduledesc = m.getName().toString().trim(); dtmoduledesc = m.getAnnotation(Test.class).description(); testcasesttime = new Date(); objDailyItemPrice = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyCustomers = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyItems = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailySales = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyPaidHours = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyWages = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); BaseObj = PageFactory.initElements(this.getDriver(), BasePage.class); common = PageFactory.initElements(this.getDriver(), CommonFunctions.class); storeprop = PageFactory.initElements(this.getDriver(), StoreProperties.class); ScreenShotUtil = PageFactory.initElements(this.getDriver(), ExtentReportsScreenshotCode.class); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy_hmmss"); String formattedDate = sdf.format(date); System.out.println(formattedDate); // 12/01/2011 4:48:16 PM DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String formattedDate1 = dateFormat.format(date); System.out.println(formattedDate1); // 12/01/2011 4:48:16 PM String dat = formattedDate1; Report_Header("testcase", reportPath, moduledesc, dat); } @BeforeClass public void loadXMLFile() { cName = this.getClass().getSimpleName(); reportPath = new File(getContext().getStringProperty("reportPath")); report = new ExtentReports( getContext().getStringProperty("reportPath") + "\\" + this.getClass().getSimpleName() + ".html"); classList.add(this.getClass().getSimpleName()); initializeTestcontext(); System.out.println("test1 - Beforeclass"); data = new XMLDataReader(log); customreport = new CustomExtentReports(); createDriver(getContext().getStringProperty("WLPUrl"), getContext().getStringProperty("browser"), cName, mName, extentTest, driver1); log.info("Loading data for the class: "); data.loadTestDataXML(System.getProperty("user.dir") + "\\TestData\\NGBO\\articledetail.xml"); customreport.createExtentReport(); } }
UTF-8
Java
17,430
java
DailyDeptMainClass.java
Java
[ { "context": "bel' and @id ='form1:text1']\")).sendKeys(\r\n\t\t * \"1412store\"); driver1.findElement(By.\r\n\t\t * xpath(\"//input[@", "end": 4468, "score": 0.5823758840560913, "start": 4460, "tag": "PASSWORD", "value": "412store" }, { "context": "el' and @id ='form1:secret1']\"))....
null
[]
package au.wow.WLPmain.tests; import java.awt.AWTException; import org.testng.ITestContext; import org.testng.annotations.*; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; import com.relevantcodes.extentreports.ExtentReports; import au.wow.WLPmain.objects.DailyPlanningMainObjects; import au.wow.WLPmain.pages.CommonFunctions; import au.wow.WLPmain.pages.DailyPlanningMainPage; import au.wow.WLPmain.pages.WoWLoginPage; import au.wow.wlp.utils.BasePage; import au.wow.wlp.utils.CustomExtentReports; import au.wow.wlp.utils.ExtentReportsScreenshotCode; import au.wow.wlp.utils.SQLWrapper; import au.wow.wlp.utils.TestBase; import au.wow.wlp.utils.TestStatus; import au.wow.wlp.utils.XMLDataReader; public class DailyDeptMainClass extends TestBase { private Logger log = LogManager.getLogger(DailyDeptMainClass.class); TestStatus status; SQLWrapper sql = new SQLWrapper(log); ExtentReportsScreenshotCode ScreenShotUtil; WoWLoginPage loginPage; DailyPlanningMainPage pageDailyItemPrice; DailyPlanningMainPage pageDailyCustomers; DailyPlanningMainPage pageDailyItems; DailyPlanningMainPage pageDailySales; DailyPlanningMainPage pageDailyPaidHours; DailyPlanningMainPage pageDailyWages; // ArticleDetailsPage pageartDetails; DailyPlanningMainPage pageartDetails; DailyPlanningMainObjects objDailyItemPrice; DailyPlanningMainObjects objDailyCustomers; DailyPlanningMainObjects objDailyItems; DailyPlanningMainObjects objDailySales; DailyPlanningMainObjects objDailyPaidHours; DailyPlanningMainObjects objDailyWages; BasePage BaseObj; CommonFunctions common; StoreProperties storeprop; public DailyDeptMainClass() { super.log = log; } /** * AL_1 Verifying Department Hierarchy and Paginations * * @throws Exception */ @Test(description = "Daily Planning Item Price") public void ItemPrice() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); navToDailyDeptPlanItemPrice(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyItemPrice.dropdonw, "8"); click(objDailyItemPrice.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyItemPrice.dailyplan, "Item Price"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyItemPrice.fnCheckOutItemPriceTotal(objDailyItemPrice, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeptPlanItemPrice(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, getReport(), getReportLogger(), WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyItemPrice = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Customers") public void Customers() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1<PASSWORD>"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "<PASSWORD>"); */ navToDailyDeprtmntCustomers(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyCustomers.dropdonw, "8"); click(objDailyCustomers.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyCustomers.dailyplan, "Customers"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyCustomers.fnlCheckOutCustomersTotal(objDailyCustomers, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntCustomers(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyCustomers = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Items") public void Items() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntItems(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyItems.dropdonw, "8"); click(objDailyItems.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyItems.dailyplan, "Items"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyItems.fnlCheckOutItemsTotal(objDailyItems, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntItems(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyItems = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Sales") public void Sales() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east<PASSWORD>"); */ navToDailyDeprtmntSales(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailySales.dropdonw, "8"); click(objDailySales.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailySales.dailyplan, "Sales"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailySales.fnlCheckOutCustomersTotal(objDailySales, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntSales(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailySales = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Paid Hours") public void PaidHours() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntPaidHours(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyPaidHours.dropdonw, "8"); click(objDailyPaidHours.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyPaidHours.dailyplan, "Paid Hours"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyPaidHours.fnlPaidHoursTotal(objDailyPaidHours, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntPaidHours(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyPaidHours = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @Test(description = "Daily Planning Wages") public void Wages() throws Exception { TestStatus status = getTestStatus(); System.out.println("Testing"); /* * driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:text1']")).sendKeys( * "1412store"); driver1.findElement(By. * xpath("//input[@class = 'clsLabel' and @id ='form1:secret1']")).sendKeys( * "east1234"); */ navToDailyDeprtmntWages(status); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[1]"))); selectByValue(objDailyWages.dropdonw, "8"); click(objDailyWages.linkGo); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame("BOTTOM"); selectByValue(objDailyWages.dailyplan, "Wages"); waitFor(2); driver1.switchTo().defaultContent(); driver1.switchTo().frame(driver1.findElement(By.xpath("//html//frameset//frame[2]"))); waitFor(2); pageDailyWages.fnlWagesTotal(objDailyWages, extentTest); driver1.switchTo().defaultContent(); status.assertAll(); } public void navToDailyDeprtmntWages(TestStatus status) throws Exception { log.info("---------------Login into Application--------------------"); Report_AddStep("testcase", "---------------Login into Application--------------------", "", "", "Pass"); loginPage = new WoWLoginPage().createPage(getDriver(), getContext(), log, status, data, report, extentTest, WoWLoginPage.class); Report_AddStep("testcase", "Login with the Store : " + getContext().getStringProperty("store"), "", "", "Pass"); pageDailyWages = loginPage.navToDailyDept(getContext().getStringProperty("store")); // log.info("-------------Navigate to Order Roster Report Page------------"); // Report_AddStep("testcase", "---------------Navigate to Order Roster Report // Page--------------------","","", "Pass"); // orderReportPage.clickOnOrderRoasterReport(objOrderRoaster); } @BeforeMethod public void setUpItemPrice(Method m, ITestContext testcontext) throws IOException { System.out.println("test1 - beforemethod"); mName = m.getName().toString().trim(); System.out.println(m.getName().toString().trim()); if (!methodList.contains(m.getName().toString().trim())) { methodList.add(m.getName().toString().trim()); extentTest = report.startTest(m.getName().toString().trim()); } System.out.println(methodList.size()); // initializeTestcontext(); System.out.println("test1 - beforemethod"); log.info("Loading Testdata for the test case: " + m.getName().toString()); data.getTCNameFromChildren(m.getName().toString().trim()); testcontext.setAttribute("WebDriver", getDriver()); testcontext.setAttribute("Customreports", this.customreport); customreport.startTest(m.getName().toString()); initializeTestStatus(); reportPath = new File(getContext().getStringProperty("reportPath")); moduledesc = m.getName().toString().trim(); dtmoduledesc = m.getAnnotation(Test.class).description(); testcasesttime = new Date(); objDailyItemPrice = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyCustomers = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyItems = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailySales = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyPaidHours = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); objDailyWages = PageFactory.initElements(this.getDriver(), DailyPlanningMainObjects.class); BaseObj = PageFactory.initElements(this.getDriver(), BasePage.class); common = PageFactory.initElements(this.getDriver(), CommonFunctions.class); storeprop = PageFactory.initElements(this.getDriver(), StoreProperties.class); ScreenShotUtil = PageFactory.initElements(this.getDriver(), ExtentReportsScreenshotCode.class); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy_hmmss"); String formattedDate = sdf.format(date); System.out.println(formattedDate); // 12/01/2011 4:48:16 PM DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String formattedDate1 = dateFormat.format(date); System.out.println(formattedDate1); // 12/01/2011 4:48:16 PM String dat = formattedDate1; Report_Header("testcase", reportPath, moduledesc, dat); } @BeforeClass public void loadXMLFile() { cName = this.getClass().getSimpleName(); reportPath = new File(getContext().getStringProperty("reportPath")); report = new ExtentReports( getContext().getStringProperty("reportPath") + "\\" + this.getClass().getSimpleName() + ".html"); classList.add(this.getClass().getSimpleName()); initializeTestcontext(); System.out.println("test1 - Beforeclass"); data = new XMLDataReader(log); customreport = new CustomExtentReports(); createDriver(getContext().getStringProperty("WLPUrl"), getContext().getStringProperty("browser"), cName, mName, extentTest, driver1); log.info("Loading data for the class: "); data.loadTestDataXML(System.getProperty("user.dir") + "\\TestData\\NGBO\\articledetail.xml"); customreport.createExtentReport(); } }
17,440
0.684165
0.673265
425
39.011765
31.446049
114
false
false
0
0
0
0
0
0
2.364706
false
false
2
590cbdc9bddf86b36ccd9c37c5b9b85d86adccb5
14,362,370,643,956
f8257f9b2a6c169436692a5cc62be3c24b949e3f
/solid/single-responsability-exercise/src/test/java/com/dev/core/EmployeeTest.java
b46bd6685ac973aee24869d53658f52bcba37302
[]
no_license
EdCornejo/design-patterns
https://github.com/EdCornejo/design-patterns
0174c549e0fafa6d17011703ef77ea20a3d2a0a5
4fc965e1d508b67d711c55731b7976bbf1acd9d5
refs/heads/master
2022-11-30T17:23:33.334000
2020-08-17T04:31:32
2020-08-17T04:31:32
288,080,472
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * This Java source file was generated by the Gradle 'init' task. */ package com.dev.core; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class EmployeeTest { @Test public void testEmployee() { String name = "dev"; String position = "developer"; Employee employee = new Employee(name, position); assertNotNull(name + " " + position, employee.printTimeSheetReport()); } }
UTF-8
Java
438
java
EmployeeTest.java
Java
[ { "context": " public void testEmployee() {\n\t\tString name = \"dev\";\n\t\tString position = \"developer\";\n\t\t\n\t\tEmployee ", "end": 260, "score": 0.9175029993057251, "start": 257, "tag": "USERNAME", "value": "dev" } ]
null
[]
/* * This Java source file was generated by the Gradle 'init' task. */ package com.dev.core; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class EmployeeTest { @Test public void testEmployee() { String name = "dev"; String position = "developer"; Employee employee = new Employee(name, position); assertNotNull(name + " " + position, employee.printTimeSheetReport()); } }
438
0.684932
0.684932
20
20.9
22.890827
78
false
false
0
0
0
0
0
0
0.9
false
false
2
e82d13ca1eb805b4add96a187f690f7a39f8d61a
12,232,066,918,870
9e57aa70143e2a55a181d05565ccc151359fd46e
/app/src/main/java/com/jack/carebaby/ui/DailyTripActivity.java
03b602a00a44262e16839856e6937c74f91eec22
[]
no_license
babycareorg/Main
https://github.com/babycareorg/Main
7419afb0ae0cf727a2c3aea709b1157d92da3445
bc7e990e2783a5768fa4865b02bdd8bd4a3ba912
refs/heads/master
2020-07-04T02:24:22.604000
2019-10-10T12:25:27
2019-10-10T12:25:27
202,121,470
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jack.carebaby.ui; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.webkit.WebView; import android.widget.Toast; import com.jack.carebaby.R; import com.jack.carebaby.base.BasePage; import com.jack.carebaby.utils.WebViewFragmentUtil; public class DailyTripActivity extends BasePage { private WebView trip_webview; private String url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_daily_trip); trip_webview=findViewById(R.id.trip_webview); url="https://m.ctrip.com/html5/?sourceid=497&allianceid=4897&sid=182042&sepopup=150"; trip_webview.loadUrl(url); WebViewFragmentUtil webViewFragmentUtil=new WebViewFragmentUtil(); webViewFragmentUtil.WebViewUtil(trip_webview); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.trip_menu,menu); return true; } //监听菜单点击 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.trip1: url="https://m.tuniu.com/?p=14820&cmpid=mkt_03033903&utm_source=m.baidu.com&utm_campaign=baidupz&utm_medium=baidupz"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载途牛...", Toast.LENGTH_LONG).show(); break; case R.id.trip2: url="https://m.mafengwo.cn/"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载马蜂窝...", Toast.LENGTH_LONG).show(); break; case R.id.trip3: url="https://m.qyer.com/"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载穷游...", Toast.LENGTH_LONG).show(); break; case R.id.trip4: url="https://m.ly.com/"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载同城...", Toast.LENGTH_LONG).show(); break; case R.id.trip5: url="https://m.lvmama.com/?losc=019926&utm_source=baidu&utm_medium=zhuanqu&utm_campaign=wap"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载驴妈妈...", Toast.LENGTH_LONG).show(); break; case R.id.trip6: DailyTripActivity.this.finish(); break; } return super.onOptionsItemSelected(item); } }
UTF-8
Java
2,842
java
DailyTripActivity.java
Java
[]
null
[]
package com.jack.carebaby.ui; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.webkit.WebView; import android.widget.Toast; import com.jack.carebaby.R; import com.jack.carebaby.base.BasePage; import com.jack.carebaby.utils.WebViewFragmentUtil; public class DailyTripActivity extends BasePage { private WebView trip_webview; private String url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_daily_trip); trip_webview=findViewById(R.id.trip_webview); url="https://m.ctrip.com/html5/?sourceid=497&allianceid=4897&sid=182042&sepopup=150"; trip_webview.loadUrl(url); WebViewFragmentUtil webViewFragmentUtil=new WebViewFragmentUtil(); webViewFragmentUtil.WebViewUtil(trip_webview); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.trip_menu,menu); return true; } //监听菜单点击 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.trip1: url="https://m.tuniu.com/?p=14820&cmpid=mkt_03033903&utm_source=m.baidu.com&utm_campaign=baidupz&utm_medium=baidupz"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载途牛...", Toast.LENGTH_LONG).show(); break; case R.id.trip2: url="https://m.mafengwo.cn/"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载马蜂窝...", Toast.LENGTH_LONG).show(); break; case R.id.trip3: url="https://m.qyer.com/"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载穷游...", Toast.LENGTH_LONG).show(); break; case R.id.trip4: url="https://m.ly.com/"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载同城...", Toast.LENGTH_LONG).show(); break; case R.id.trip5: url="https://m.lvmama.com/?losc=019926&utm_source=baidu&utm_medium=zhuanqu&utm_campaign=wap"; trip_webview.loadUrl(url); Toast.makeText(DailyTripActivity.this, "加载驴妈妈...", Toast.LENGTH_LONG).show(); break; case R.id.trip6: DailyTripActivity.this.finish(); break; } return super.onOptionsItemSelected(item); } }
2,842
0.610912
0.595836
93
28.956989
29.071257
133
false
false
0
0
0
0
0
0
0.612903
false
false
2
198dca38aa47f028090f5646b633ca2fe4851192
24,833,500,953,254
080244428032b18f27ed14d1e42a700a0f0f69a4
/javaNetworkTest/src/kr/or/ddit/tcp/Sender.java
d5bab1ba65f78da7547dfb19b4113c1f2f3eed75
[]
no_license
oh-suyeon/Study_JavaHigh
https://github.com/oh-suyeon/Study_JavaHigh
329c5cb228997010ead870c75d0e49b12fab2b14
d8fbf358dee1bcee94142f313731e43ded9bc9e0
refs/heads/master
2023-06-15T20:31:46.484000
2021-07-07T11:09:44
2021-07-07T11:09:44
381,695,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.or.ddit.tcp; import java.io.DataOutputStream; import java.net.Socket; import java.util.Scanner; /** * 소켓을 통해서 메시지를 보내는 역할 담당 * @author PC-08 * */ public class Sender extends Thread{ private Scanner scan; private String name; private DataOutputStream dos; public Sender(Socket socket) { name = "[" + socket.getInetAddress() + " : " + socket.getLocalPort() + "]"; scan = new Scanner(System.in); try { dos = new DataOutputStream(socket.getOutputStream()); }catch(Exception ex) { ex.printStackTrace(); } } @Override public void run() { while(dos != null) { try { dos.writeUTF(name + " >>> " + scan.nextLine()); // 엔터로 값이 한 줄씩 들어올 때마다 실행된다. } catch (Exception e) { e.printStackTrace(); } } } }
UTF-8
Java
838
java
Sender.java
Java
[ { "context": "Scanner;\n\n/**\n * 소켓을 통해서 메시지를 보내는 역할 담당\n * @author PC-08\n *\n */\n\npublic class Sender extends Thread{\n\t\n\tpr", "end": 155, "score": 0.9996379017829895, "start": 150, "tag": "USERNAME", "value": "PC-08" } ]
null
[]
package kr.or.ddit.tcp; import java.io.DataOutputStream; import java.net.Socket; import java.util.Scanner; /** * 소켓을 통해서 메시지를 보내는 역할 담당 * @author PC-08 * */ public class Sender extends Thread{ private Scanner scan; private String name; private DataOutputStream dos; public Sender(Socket socket) { name = "[" + socket.getInetAddress() + " : " + socket.getLocalPort() + "]"; scan = new Scanner(System.in); try { dos = new DataOutputStream(socket.getOutputStream()); }catch(Exception ex) { ex.printStackTrace(); } } @Override public void run() { while(dos != null) { try { dos.writeUTF(name + " >>> " + scan.nextLine()); // 엔터로 값이 한 줄씩 들어올 때마다 실행된다. } catch (Exception e) { e.printStackTrace(); } } } }
838
0.628906
0.626302
42
17.285715
17.331894
81
false
false
0
0
0
0
0
0
1.619048
false
false
2
b7be7af3526849c9365cb92f150dbf2e6bf4e5c3
4,990,752,038,413
e4f3a40cfa72716ec1f5b9dfe70b55b48cdc620a
/src/main/java/top/jessehzx/web/SeckillController.java
8c6f62eb57258962da656cf74b0b739a602a28a7
[]
no_license
jessehzx/seckill
https://github.com/jessehzx/seckill
effffd25c71aef050d986035429ea19463545654
44fe0c16539a0b3501c387c0afe9eba764f74992
refs/heads/master
2022-12-26T00:27:21.704000
2020-04-06T06:12:31
2020-04-06T06:12:31
133,052,546
0
0
null
false
2022-12-16T07:51:03
2018-05-11T14:49:31
2020-04-06T06:12:34
2022-12-16T07:51:00
13,996
1
0
8
Java
false
false
package top.jessehzx.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import top.jessehzx.dto.Exposer; import top.jessehzx.dto.SeckillExcution; import top.jessehzx.dto.SeckillResult; import top.jessehzx.entity.Seckill; import top.jessehzx.enums.SeckillStatEnum; import top.jessehzx.exception.RepeatKillException; import top.jessehzx.exception.SeckillCloseException; import top.jessehzx.exception.SeckillException; import top.jessehzx.service.SeckillService; import java.util.Date; import java.util.List; /** * @author jessehzx * @date 2018/5/14 */ @Controller @RequestMapping("/seckill") // url:模块/资源/{id}/细分 如:/seckill/list public class SeckillController { private final Logger logger = LoggerFactory.getLogger(SeckillController.class); @Autowired private SeckillService seckillService; @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(Model model) { // 获取列表页 List<Seckill> seckillList = seckillService.getSeckillList(); model.addAttribute("list", seckillList); // list.jsp + model = ModelAndView return "list"; // WEB_INF/list.jsp } @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET) public String detail(@PathVariable("seckillId") Long seckillId, Model model) { // 假如seckillId为空,重定向到列表页 if (null == seckillId) { return "redirect:/seckill/list"; } Seckill seckill = seckillService.getById(seckillId); // 假如seckillId不合法,转发到列表页 if (null == seckill) { return "forward:/seckill/list"; } model.addAttribute("seckill", seckill); return "detail"; } @RequestMapping(value = "/{seckillId}/exposer", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST) @ResponseBody // 表示返回的是json格式的数据 public SeckillResult<Exposer> exposer(@PathVariable("seckillId") Long seckillId) { SeckillResult<Exposer> result; try { Exposer exposer = seckillService.exportSeckillUrl(seckillId); result = new SeckillResult<Exposer>(true, exposer); } catch (Exception e) { result = new SeckillResult<Exposer>(false, e.getMessage()); } return result; } @RequestMapping(value = "/{seckillId}/{md5}/execution", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST) @ResponseBody /** 参数killPhone是从浏览器的cookie中获取到的。 Spring MVC默认required=true,它要求必传,没有传值就直接报错。 那我们把它设置为false,就是没有传不让Spring MVC报错,而是交于我们的代码逻辑中去判断 **/ public SeckillResult<SeckillExcution> excutor(@PathVariable("seckillId") Long seckillId, @CookieValue(value = "killPhone", required = false) Long killPhone, @PathVariable("md5") String md5) { // 验证手机号 if (null == killPhone) { return new SeckillResult<SeckillExcution>(false, "未注册"); } SeckillResult<SeckillExcution> result; try { // 使用存储过程 SeckillExcution seckillExcution = seckillService.excuteSeckillProcedure(seckillId, killPhone, md5); result = new SeckillResult<SeckillExcution>(true, seckillExcution); } catch (RepeatKillException e1) { SeckillExcution seckillExcution = new SeckillExcution(seckillId, SeckillStatEnum.REPEAT_KILL); return new SeckillResult<SeckillExcution>(true, seckillExcution); } catch (SeckillCloseException e2) { SeckillExcution seckillExcution = new SeckillExcution(seckillId, SeckillStatEnum.END); return new SeckillResult<SeckillExcution>(true, seckillExcution); } catch (SeckillException e) { SeckillExcution seckillExcution = new SeckillExcution(seckillId, SeckillStatEnum.INNER_KILL); result = new SeckillResult<SeckillExcution>(true, seckillExcution); } return result; } @RequestMapping(value = "/time/now", method=RequestMethod.GET) @ResponseBody public SeckillResult<Long> time() { Date data = new Date(); return new SeckillResult<Long>(true, data.getTime()); } }
UTF-8
Java
4,693
java
SeckillController.java
Java
[ { "context": ".util.Date;\nimport java.util.List;\n\n/**\n * @author jessehzx\n * @date 2018/5/14\n */\n@Controller\n@RequestMappin", "end": 743, "score": 0.9997174143791199, "start": 735, "tag": "USERNAME", "value": "jessehzx" } ]
null
[]
package top.jessehzx.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import top.jessehzx.dto.Exposer; import top.jessehzx.dto.SeckillExcution; import top.jessehzx.dto.SeckillResult; import top.jessehzx.entity.Seckill; import top.jessehzx.enums.SeckillStatEnum; import top.jessehzx.exception.RepeatKillException; import top.jessehzx.exception.SeckillCloseException; import top.jessehzx.exception.SeckillException; import top.jessehzx.service.SeckillService; import java.util.Date; import java.util.List; /** * @author jessehzx * @date 2018/5/14 */ @Controller @RequestMapping("/seckill") // url:模块/资源/{id}/细分 如:/seckill/list public class SeckillController { private final Logger logger = LoggerFactory.getLogger(SeckillController.class); @Autowired private SeckillService seckillService; @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(Model model) { // 获取列表页 List<Seckill> seckillList = seckillService.getSeckillList(); model.addAttribute("list", seckillList); // list.jsp + model = ModelAndView return "list"; // WEB_INF/list.jsp } @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET) public String detail(@PathVariable("seckillId") Long seckillId, Model model) { // 假如seckillId为空,重定向到列表页 if (null == seckillId) { return "redirect:/seckill/list"; } Seckill seckill = seckillService.getById(seckillId); // 假如seckillId不合法,转发到列表页 if (null == seckill) { return "forward:/seckill/list"; } model.addAttribute("seckill", seckill); return "detail"; } @RequestMapping(value = "/{seckillId}/exposer", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST) @ResponseBody // 表示返回的是json格式的数据 public SeckillResult<Exposer> exposer(@PathVariable("seckillId") Long seckillId) { SeckillResult<Exposer> result; try { Exposer exposer = seckillService.exportSeckillUrl(seckillId); result = new SeckillResult<Exposer>(true, exposer); } catch (Exception e) { result = new SeckillResult<Exposer>(false, e.getMessage()); } return result; } @RequestMapping(value = "/{seckillId}/{md5}/execution", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST) @ResponseBody /** 参数killPhone是从浏览器的cookie中获取到的。 Spring MVC默认required=true,它要求必传,没有传值就直接报错。 那我们把它设置为false,就是没有传不让Spring MVC报错,而是交于我们的代码逻辑中去判断 **/ public SeckillResult<SeckillExcution> excutor(@PathVariable("seckillId") Long seckillId, @CookieValue(value = "killPhone", required = false) Long killPhone, @PathVariable("md5") String md5) { // 验证手机号 if (null == killPhone) { return new SeckillResult<SeckillExcution>(false, "未注册"); } SeckillResult<SeckillExcution> result; try { // 使用存储过程 SeckillExcution seckillExcution = seckillService.excuteSeckillProcedure(seckillId, killPhone, md5); result = new SeckillResult<SeckillExcution>(true, seckillExcution); } catch (RepeatKillException e1) { SeckillExcution seckillExcution = new SeckillExcution(seckillId, SeckillStatEnum.REPEAT_KILL); return new SeckillResult<SeckillExcution>(true, seckillExcution); } catch (SeckillCloseException e2) { SeckillExcution seckillExcution = new SeckillExcution(seckillId, SeckillStatEnum.END); return new SeckillResult<SeckillExcution>(true, seckillExcution); } catch (SeckillException e) { SeckillExcution seckillExcution = new SeckillExcution(seckillId, SeckillStatEnum.INNER_KILL); result = new SeckillResult<SeckillExcution>(true, seckillExcution); } return result; } @RequestMapping(value = "/time/now", method=RequestMethod.GET) @ResponseBody public SeckillResult<Long> time() { Date data = new Date(); return new SeckillResult<Long>(true, data.getTime()); } }
4,693
0.674859
0.671026
110
39.31818
31.413063
135
false
false
0
0
0
0
0
0
0.672727
false
false
2
b36603ce194d75abaa0748aed68794c30afd3b2d
7,043,746,435,743
39f500600b40c4c5e8ae7cfee39bcb6da2661d31
/HappyCoding/src/test/java/com/test/LinkedListsTest/DeleteMiddleNodeTest.java
d2faa566c7af6f34a0a1cb87a5fad9a721840be5
[]
no_license
shiyaoeating/happycoding
https://github.com/shiyaoeating/happycoding
2d6056267dc2cbeb512cfbbb3ff121b4cce47769
383779ef27d42af04a2eaf16dce725d692d44d50
refs/heads/master
2021-01-21T04:50:19.234000
2016-06-29T03:19:12
2016-06-29T03:19:12
51,701,144
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test.LinkedListsTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import com.Algorithms.LinkedLists.DeleteMiddleNode; import com.Exceptions.InvalidInputException; import com.Utils.Node; public class DeleteMiddleNodeTest { @Test public void testGet() { Node a = new Node(1); a.appendToTail(2); a.appendToTail(3); try { assertEquals(a.getNodeFromThis(0).data, 1); assertEquals(a.getNodeFromThis(1).data, 2); assertEquals(a.getNodeFromThis(2).data, 3); assertNull(a.getNodeFromThis(3)); } catch (InvalidInputException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void test() { Node a = new Node(1); a.appendToTail(2); a.appendToTail(3); a.appendToTail(4); try { Node second = a.getNodeFromThis(1); System.out.println(second.data); Node third = a.getNodeFromThis(2); System.out.println(third.data); DeleteMiddleNode.deleteMiddle(second); System.out.println(a.toString()); assertEquals(a.toString(), "1->3->4"); DeleteMiddleNode.deleteMiddle(second); System.out.println(second.toString()); assertEquals(a.toString(), "1->4"); } catch (InvalidInputException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
1,664
java
DeleteMiddleNodeTest.java
Java
[]
null
[]
package com.test.LinkedListsTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import com.Algorithms.LinkedLists.DeleteMiddleNode; import com.Exceptions.InvalidInputException; import com.Utils.Node; public class DeleteMiddleNodeTest { @Test public void testGet() { Node a = new Node(1); a.appendToTail(2); a.appendToTail(3); try { assertEquals(a.getNodeFromThis(0).data, 1); assertEquals(a.getNodeFromThis(1).data, 2); assertEquals(a.getNodeFromThis(2).data, 3); assertNull(a.getNodeFromThis(3)); } catch (InvalidInputException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void test() { Node a = new Node(1); a.appendToTail(2); a.appendToTail(3); a.appendToTail(4); try { Node second = a.getNodeFromThis(1); System.out.println(second.data); Node third = a.getNodeFromThis(2); System.out.println(third.data); DeleteMiddleNode.deleteMiddle(second); System.out.println(a.toString()); assertEquals(a.toString(), "1->3->4"); DeleteMiddleNode.deleteMiddle(second); System.out.println(second.toString()); assertEquals(a.toString(), "1->4"); } catch (InvalidInputException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
1,664
0.564904
0.552284
59
27.20339
18.043055
55
false
false
0
0
0
0
0
0
0.59322
false
false
2
4419714a3f00380fa79b72a056d59fbb350497be
16,638,703,310,724
e7a544c6374c7e2d2229bc247b271c5a07ad9ce1
/lianxin/trunk/src/com/surekam/iptv/service/IptvService.java
c5f160044cf42716920546e66bbad66ce687e254
[]
no_license
helloWorlddxq/javaee
https://github.com/helloWorlddxq/javaee
ffe0c348bb069225ac051f7b353e4656fe6788f4
c7ff87171a47e9e8c0e9b31614ce907a7cabaa60
refs/heads/master
2018-12-22T17:40:31.601000
2018-05-31T06:36:03
2018-05-31T06:36:03
62,043,472
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.surekam.iptv.service; import java.util.List; import java.util.Map; import com.surekam.iptv.model.IptvModel; import com.surekam.platform.core.persistence.Page; import com.surekam.wbspbill.model.WbspSheetDisposal; import com.surekam.wbspbill.model.WbspSheetDisposalRemark; public interface IptvService { Page queryIptvSheetForPageOne(Map params,int page,int pageSize); String queryLoginId(Long staffId); Map queryWbspSheetInfo(String sheetId); //订单新增 boolean addIptvSheetDisposalInfo(WbspSheetDisposal sheetDisposal,String loginId); //修改订单状态 void updateIptvSheetInfo(String sheetId,int orderStatus,String adslCode); //修改订单处理信息 void updateIptvDisposalInfo(String sheetId,String loginId,int status); //添加订单备注信息 void addIptvSheetList(WbspSheetDisposalRemark sheetRemark); WbspSheetDisposal getWbspDisposalInfo(String sheetId); List queryWbspSheetList(String sheetId); }
GB18030
Java
991
java
IptvService.java
Java
[]
null
[]
package com.surekam.iptv.service; import java.util.List; import java.util.Map; import com.surekam.iptv.model.IptvModel; import com.surekam.platform.core.persistence.Page; import com.surekam.wbspbill.model.WbspSheetDisposal; import com.surekam.wbspbill.model.WbspSheetDisposalRemark; public interface IptvService { Page queryIptvSheetForPageOne(Map params,int page,int pageSize); String queryLoginId(Long staffId); Map queryWbspSheetInfo(String sheetId); //订单新增 boolean addIptvSheetDisposalInfo(WbspSheetDisposal sheetDisposal,String loginId); //修改订单状态 void updateIptvSheetInfo(String sheetId,int orderStatus,String adslCode); //修改订单处理信息 void updateIptvDisposalInfo(String sheetId,String loginId,int status); //添加订单备注信息 void addIptvSheetList(WbspSheetDisposalRemark sheetRemark); WbspSheetDisposal getWbspDisposalInfo(String sheetId); List queryWbspSheetList(String sheetId); }
991
0.793397
0.793397
32
27.34375
26.299488
82
false
false
0
0
0
0
0
0
1.34375
false
false
2
1bf71ef619af637067ec32b9e6bb874f885e38ed
22,557,168,239,525
97aa08c7dd94164b650b3b4877f34dda51bddfd1
/sso-server/src/main/java/com/ppepper/sso/component/AccountUserDetailsService.java
47099b3e847c603f92749d1a4d8249cd7b33dccc
[ "Apache-2.0" ]
permissive
chenjidong/b2c-mall
https://github.com/chenjidong/b2c-mall
ba987ab0196f4cf0c7eed965e55856a0b19b32a5
b05fe7346b26049e6ec1720712f7f1994ccaa957
refs/heads/master
2022-06-22T10:09:06.147000
2020-02-24T11:44:51
2020-02-24T11:44:51
240,843,341
1
0
Apache-2.0
false
2022-06-21T02:48:28
2020-02-16T06:27:26
2020-02-24T11:48:20
2022-06-21T02:48:27
1,222
1
0
4
Java
false
false
package com.ppepper.sso.component; import com.ppepper.common.dto.AccountDTO; import com.ppepper.common.enums.AccountLoginType; import com.ppepper.common.feign.AccountSysFeignService; import com.ppepper.common.utils.JwtTokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import static com.ppepper.common.security.SecurityUtils.ROLE_SHOP; import static com.ppepper.common.security.SecurityUtils.ROLE_USER; /** * Created with ChenJiDong * Created By 2020-02-08 * tips:需要拆分时 使用 feign 获取即可 */ @Component public class AccountUserDetailsService implements UserDetailsService { @Autowired private AccountSysFeignService accountSysFeignService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { AccountDTO accountDTO = accountSysFeignService.getByPhone(s); if (accountDTO == null) { accountDTO = accountSysFeignService.getByUsername(s); if (accountDTO == null) throw new UsernameNotFoundException("账户不存在!"); } String role = accountDTO.getLoginType() == AccountLoginType.SHOP.getCode() ? ROLE_SHOP : ROLE_USER; String name = accountDTO.getUsername(); if (name == null) name = accountDTO.getPhone(); String username = JwtTokenUtils.generateSubject(name, accountDTO.getId(), role); return new User(username, accountDTO.getPassword(), AuthorityUtils.createAuthorityList(role)); } }
UTF-8
Java
1,912
java
AccountUserDetailsService.java
Java
[ { "context": "rity.SecurityUtils.ROLE_USER;\n\n/**\n * Created with ChenJiDong\n * Created By 2020-02-08\n * tips:需要拆分时 使用 feign ", "end": 854, "score": 0.9019960761070251, "start": 844, "tag": "USERNAME", "value": "ChenJiDong" } ]
null
[]
package com.ppepper.sso.component; import com.ppepper.common.dto.AccountDTO; import com.ppepper.common.enums.AccountLoginType; import com.ppepper.common.feign.AccountSysFeignService; import com.ppepper.common.utils.JwtTokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import static com.ppepper.common.security.SecurityUtils.ROLE_SHOP; import static com.ppepper.common.security.SecurityUtils.ROLE_USER; /** * Created with ChenJiDong * Created By 2020-02-08 * tips:需要拆分时 使用 feign 获取即可 */ @Component public class AccountUserDetailsService implements UserDetailsService { @Autowired private AccountSysFeignService accountSysFeignService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { AccountDTO accountDTO = accountSysFeignService.getByPhone(s); if (accountDTO == null) { accountDTO = accountSysFeignService.getByUsername(s); if (accountDTO == null) throw new UsernameNotFoundException("账户不存在!"); } String role = accountDTO.getLoginType() == AccountLoginType.SHOP.getCode() ? ROLE_SHOP : ROLE_USER; String name = accountDTO.getUsername(); if (name == null) name = accountDTO.getPhone(); String username = JwtTokenUtils.generateSubject(name, accountDTO.getId(), role); return new User(username, accountDTO.getPassword(), AuthorityUtils.createAuthorityList(role)); } }
1,912
0.765458
0.761194
45
40.688889
30.422815
107
false
false
0
0
0
0
0
0
0.6
false
false
2
3cd97f608b661b403756e24cdb1a3ad6bd19f594
18,365,280,206,464
5dcf0b90f03bfb4ae6e1012a0c1b25fb2dec178a
/api/src/main/java/com/soecode/lyf/entity/Collections.java
207badab3ecb0d5700318ec505354a28a7086370
[]
no_license
guoyu07/HouDuan
https://github.com/guoyu07/HouDuan
7a58aa37e324d7dc1656dc289707cee7d7e2988d
c41c98d9ba491e7de76bffe9339ab1de8f8de652
refs/heads/master
2021-04-12T04:29:08.696000
2018-01-10T02:19:50
2018-01-10T02:19:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.soecode.lyf.entity; public class Collections { private int cid;//主键 private Cuser cuser;//用户id private Corder corder;//订单id public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public Cuser getCuser() { return cuser; } public void setCuser(Cuser cuser) { this.cuser = cuser; } public Corder getCorder() { return corder; } public void setCorder(Corder corder) { this.corder = corder; } @Override public String toString() { return "Collections [cid=" + cid + ", cuser=" + cuser + ", corder=" + corder + "]"; } public Collections() {} }
UTF-8
Java
663
java
Collections.java
Java
[]
null
[]
package com.soecode.lyf.entity; public class Collections { private int cid;//主键 private Cuser cuser;//用户id private Corder corder;//订单id public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public Cuser getCuser() { return cuser; } public void setCuser(Cuser cuser) { this.cuser = cuser; } public Corder getCorder() { return corder; } public void setCorder(Corder corder) { this.corder = corder; } @Override public String toString() { return "Collections [cid=" + cid + ", cuser=" + cuser + ", corder=" + corder + "]"; } public Collections() {} }
663
0.62212
0.62212
35
17.6
17.007896
86
false
false
0
0
0
0
0
0
2.314286
false
false
2
e9b368281f5b3c566f187d7f5006b624b4f3e884
12,695,923,395,447
9cbe8dac8b1c2146bc0959c30e21e498ddf26d86
/lab4/Driver.java
2390ad78e0888227f67c68d23d77f94213ab08d3
[]
no_license
bradcardello/Database-Systems-1
https://github.com/bradcardello/Database-Systems-1
fdb4b25068c5defe6650b5b80022bec9d543fcfc
c17df6e88bd949281fd28a866d75a675138baebe
refs/heads/master
2016-12-12T18:15:02.577000
2016-03-21T03:09:15
2016-03-21T03:09:15
32,761,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.sql.*; import java.io.*; import java.util.*; /** * A sample class that connects to PostgreSQL and runs a simple query. * * Note: Your database name is your login name, so for login jsmith, * you would have * getConnection("jdbc:postgresql://cmps182-db.ic.ucsc.edu/jsmith", * "jsmith" , "password"); */ public class Driver { public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException { Connection connection; int i; Class.forName("org.postgresql.Driver"); // Registering the driver connection = DriverManager.getConnection( "jdbc:postgresql://cmps180-db.lt.ucsc.edu/username", "username", "password"); // Making the Connection, // but you have to replace // username and password to // make it work StoreApplication app = new StoreApplication(); System.out.println("\nTesting Get phone number function"); System.out.println("---------------------------------"); List<String> phoneNumbers = app.getCustomerPhoneFromFirstLastName(connection, "Mary", "Smith"); for(i=0;i<phoneNumbers.size();i++) System.out.println("The Phone number of Mary Smith is: "+phoneNumbers.get(i)); phoneNumbers = app.getCustomerPhoneFromFirstLastName(connection, "Kathleen", "Adams"); for(i=0;i<phoneNumbers.size();i++) System.out.println("The Phone number of Kathleen Adams is: "+phoneNumbers.get(i)); System.out.println("\nTesting Get film titles function(Title length 45 - 47)"); System.out.println("--------------------------------------------------------"); List<String> filmTitles = app.getFilmTitlesBasedOnLengthRange(connection, 45, 47); for(i=0;i<filmTitles.size();i++) System.out.println("Film Title "+(i+1)+": "+filmTitles.get(i)); System.out.println("\nTesting Get customer count function"); System.out.println("-------------------------------------"); int count = app.countCustomersInDistrict(connection, "Buenos Aires", true); System.out.println("The number of active customers in District Buenos Aires is "+count); count = app.countCustomersInDistrict(connection, "California", true); System.out.println("The number of active customers in District California is "+count); app.insertFilmIntoInventory(connection, "Sequel to the Prequel", "Memorable", 98, "PG-13"); connection.close(); //Closing Connection } }
UTF-8
Java
2,822
java
Driver.java
Java
[ { "context": "our database name is your login name, so for login jsmith,\n * you would have\n * getConnection(\"jdbc:post", "end": 203, "score": 0.9995730519294739, "start": 197, "tag": "USERNAME", "value": "jsmith" }, { "context": "nection(\"jdbc:postgresql://cmps182-db.ic.ucsc.e...
null
[]
import java.sql.*; import java.io.*; import java.util.*; /** * A sample class that connects to PostgreSQL and runs a simple query. * * Note: Your database name is your login name, so for login jsmith, * you would have * getConnection("jdbc:postgresql://cmps182-db.ic.ucsc.edu/jsmith", * "jsmith" , "<PASSWORD>"); */ public class Driver { public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException { Connection connection; int i; Class.forName("org.postgresql.Driver"); // Registering the driver connection = DriverManager.getConnection( "jdbc:postgresql://cmps180-db.lt.ucsc.edu/username", "username", "password"); // Making the Connection, // but you have to replace // username and password to // make it work StoreApplication app = new StoreApplication(); System.out.println("\nTesting Get phone number function"); System.out.println("---------------------------------"); List<String> phoneNumbers = app.getCustomerPhoneFromFirstLastName(connection, "Mary", "Smith"); for(i=0;i<phoneNumbers.size();i++) System.out.println("The Phone number of <NAME> is: "+phoneNumbers.get(i)); phoneNumbers = app.getCustomerPhoneFromFirstLastName(connection, "Kathleen", "Adams"); for(i=0;i<phoneNumbers.size();i++) System.out.println("The Phone number of <NAME>ams is: "+phoneNumbers.get(i)); System.out.println("\nTesting Get film titles function(Title length 45 - 47)"); System.out.println("--------------------------------------------------------"); List<String> filmTitles = app.getFilmTitlesBasedOnLengthRange(connection, 45, 47); for(i=0;i<filmTitles.size();i++) System.out.println("Film Title "+(i+1)+": "+filmTitles.get(i)); System.out.println("\nTesting Get customer count function"); System.out.println("-------------------------------------"); int count = app.countCustomersInDistrict(connection, "Buenos Aires", true); System.out.println("The number of active customers in District Buenos Aires is "+count); count = app.countCustomersInDistrict(connection, "California", true); System.out.println("The number of active customers in District California is "+count); app.insertFilmIntoInventory(connection, "Sequel to the Prequel", "Memorable", 98, "PG-13"); connection.close(); //Closing Connection } }
2,815
0.573707
0.565911
75
36.613335
31.15933
96
false
false
0
0
0
0
0
0
0.76
false
false
2
a8aa611287126f0d37aaebc72d3772ad46b633e2
23,184,233,471,977
a0fddc59237140f6d328c356928f44f1b81e0b8a
/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserJPAResource.java
806bc8bf0184a74450be1364cf41b70407696fb8
[]
no_license
alexmalyshev123/restfulwebservices
https://github.com/alexmalyshev123/restfulwebservices
a1a7b5863c768ebfac92341d44092b1838312363
32ef6c211ebc6234560eaab55eca4ac656584087
refs/heads/master
2020-12-28T08:05:21.458000
2020-02-04T15:28:08
2020-02-04T15:28:08
238,239,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.in28minutes.rest.webservices.restfulwebservices.user; import com.in28minutes.rest.webservices.restfulwebservices.Post.Post; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ControllerLinkBuilder; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.List; import java.util.Optional; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @RestController public class UserJPAResource { @Autowired // Using Entity Manager to communicate with DB private UserRepository userRepository; @Autowired private PostRepository postRepository; @GetMapping("/") public String welcome(){ return "Welcome to everyone"; } @GetMapping("/admin/users") public List<User> retrieveAllUsers(){ return userRepository.findAll(); } @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id){ userRepository.deleteById(id); // if method fails it throws an exception } @GetMapping("/users/{id}") public Resource<User> retrieveUser(@PathVariable int id){ Optional<User> user = userRepository.findById(id); if(!user.isPresent()){ throw new RuntimeException("id-" + id); } // HATEOAS: Adds links to our resource (link method retrieveAllUsers to our resource ../id) Resource<User> resource = new Resource<User>(user.get()); // Now we will add links to this resource ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());//created link to a method resource.add(linkTo.withRel("all-users")); //adding link to our resource with a name all-users return resource; } @PostMapping(value = "/users") public ResponseEntity<Object> createUser(@Valid @RequestBody User user){ // maps values from post request to User Object User savedUser = userRepository.save(user); //CREATED (return status back - uri of the created resource (reponse) ) URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedUser.getId()).toUri(); //concatinates cuurent path (user) with Id of the added user return ResponseEntity.created(location).build(); } @GetMapping("/users/{id}/posts") public List<Post> retrieveAllPosts(@PathVariable int id){ Optional<User> userOptional = userRepository.findById(id); if(!userOptional.isPresent()){ throw new RuntimeException("id not found- " + id); } return userOptional.get().getPosts(); } @PostMapping(value = "/users/{id}/posts") public ResponseEntity<Object> createPost(@PathVariable int id, @RequestBody Post post){ // maps values from post request to User Object Optional<User> userOptional = userRepository.findById(id); if(!userOptional.isPresent()){ throw new RuntimeException("id not found- " + id); } User user = userOptional.get(); post.setUser(user); postRepository.save(post); // saving post to Post table in DB //CREATED (return status back - uri of the created resource (reponse) ) URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(post.getId()).toUri(); //concatinates cuurent path (user) with Id of the added user return ResponseEntity.created(location).build(); } }
UTF-8
Java
3,808
java
UserJPAResource.java
Java
[]
null
[]
package com.in28minutes.rest.webservices.restfulwebservices.user; import com.in28minutes.rest.webservices.restfulwebservices.Post.Post; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ControllerLinkBuilder; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.List; import java.util.Optional; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @RestController public class UserJPAResource { @Autowired // Using Entity Manager to communicate with DB private UserRepository userRepository; @Autowired private PostRepository postRepository; @GetMapping("/") public String welcome(){ return "Welcome to everyone"; } @GetMapping("/admin/users") public List<User> retrieveAllUsers(){ return userRepository.findAll(); } @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id){ userRepository.deleteById(id); // if method fails it throws an exception } @GetMapping("/users/{id}") public Resource<User> retrieveUser(@PathVariable int id){ Optional<User> user = userRepository.findById(id); if(!user.isPresent()){ throw new RuntimeException("id-" + id); } // HATEOAS: Adds links to our resource (link method retrieveAllUsers to our resource ../id) Resource<User> resource = new Resource<User>(user.get()); // Now we will add links to this resource ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());//created link to a method resource.add(linkTo.withRel("all-users")); //adding link to our resource with a name all-users return resource; } @PostMapping(value = "/users") public ResponseEntity<Object> createUser(@Valid @RequestBody User user){ // maps values from post request to User Object User savedUser = userRepository.save(user); //CREATED (return status back - uri of the created resource (reponse) ) URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedUser.getId()).toUri(); //concatinates cuurent path (user) with Id of the added user return ResponseEntity.created(location).build(); } @GetMapping("/users/{id}/posts") public List<Post> retrieveAllPosts(@PathVariable int id){ Optional<User> userOptional = userRepository.findById(id); if(!userOptional.isPresent()){ throw new RuntimeException("id not found- " + id); } return userOptional.get().getPosts(); } @PostMapping(value = "/users/{id}/posts") public ResponseEntity<Object> createPost(@PathVariable int id, @RequestBody Post post){ // maps values from post request to User Object Optional<User> userOptional = userRepository.findById(id); if(!userOptional.isPresent()){ throw new RuntimeException("id not found- " + id); } User user = userOptional.get(); post.setUser(user); postRepository.save(post); // saving post to Post table in DB //CREATED (return status back - uri of the created resource (reponse) ) URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(post.getId()).toUri(); //concatinates cuurent path (user) with Id of the added user return ResponseEntity.created(location).build(); } }
3,808
0.699317
0.698267
125
29.464001
37.440201
189
false
false
0
0
0
0
0
0
0.312
false
false
2
fa8b7938a1b930c05b1d422174c9e9ec49e36afa
13,477,607,440,234
ab743b52142061bbefb34e4f6d68640e7b258c31
/trustkit/src/androidTest/java/com/datatheorem/android/trustkit/reporting/ReportRateLimiterTest.java
09ea3e667de7adbf12594dcaab1de75534793653
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
datatheorem/TrustKit-Android
https://github.com/datatheorem/TrustKit-Android
7f77ae200350e0e6c5f27680546ef49a609b5a48
94445e8fcde33051cc1d7abc95eb21218aebab15
refs/heads/master
2023-08-02T10:30:18.556000
2022-11-08T17:01:13
2022-11-08T17:01:13
73,692,244
579
101
MIT
false
2022-11-08T10:07:25
2016-11-14T10:12:05
2022-10-29T09:11:21
2022-11-08T10:07:25
846
533
84
28
Java
false
false
package com.datatheorem.android.trustkit.reporting; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import androidx.test.runner.AndroidJUnit4; import com.datatheorem.android.trustkit.config.PublicKeyPin; import com.datatheorem.android.trustkit.pinning.PinningValidationResult; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import org.junit.Test; import org.junit.runner.RunWith; public class ReportRateLimiterTest { private final HashSet<PublicKeyPin> pinList = new HashSet<PublicKeyPin>() {{ add(new PublicKeyPin("rFjc3wG7lTZe43zeYTvPq8k4xdDEutCmIhI5dn4oCeE=")); add(new PublicKeyPin("0SDf3cRToyZJaMsoS17oF72VMavLxj/N7WBNasNuiR8=")); }}; private final ArrayList<String> pemCertificateList1 = new ArrayList<String>() {{ add("-----BEGIN CERTIFICATE-----\n"+ "MIIDGTCCAgGgAwIBAgIJAI1jD1qixIPLMA0GCSqGSIb3DQEBBQUAMCMxITAfBgNV\n"+ "BAMMGGV2aWxjZXJ0LmRhdGF0aGVvcmVtLmNvbTAeFw0xNTEyMjAxMzU4NDNaFw0y\n"+ "NTEyMTcxMzU4NDNaMCMxITAfBgNVBAMMGGV2aWxjZXJ0LmRhdGF0aGVvcmVtLmNv\n"+ "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMdltqsRJtO7Nqypkehh\n"+ "4DSEirp9RM+hJXkBE9nRleTO+utV/snWqX/0wsUrz0wgWyPnAHybGOOXvkrWfXSt\n"+ "c2/8PyONOeFEU/9S/lWBXGZkaPhgTvkEzPmOOhf06rBMTwXUMGNDI45gKFgkO6Br\n"+ "bGPeSCuheQj0TKeWdwwNoJ+kczUE06IKu2tcuFRjHXci6VeHjANJzrfKro4ivIRy\n"+ "bewOGJj1onnpKbui/EOytsmW9MPpOSEXMoVksHOKBQ9nhpL6cDODRvG+t8u7qfFt\n"+ "mhphemK3IYNMNA4MMXpbJ+Au2hnPApZPEOit34bAwOiGi/batcS3iA+nl06dPYA9\n"+ "nPkCAwEAAaNQME4wHQYDVR0OBBYEFANxdSXS1JSvjdNtNbYBbRlgii93MB8GA1Ud\n"+ "IwQYMBaAFANxdSXS1JSvjdNtNbYBbRlgii93MAwGA1UdEwQFMAMBAf8wDQYJKoZI\n"+ "hvcNAQEFBQADggEBAAM78Bt2aLUgl2Yq4KMIGDeHdWYcRB7QPQ8sp3Q1TOQQzw0i\n"+ "AukRccl9iYNLgaSJDvlVMapD76jo3okydoWgDogWJhtZpMU/9xegIpukmu5hvF6i\n"+ "NpqE99PFO5E8BpMkNz+2nskwu//D0as6P9F3tA/o3jC6n6fWX0gt/e9th2ZgVwNQ\n"+ "9JTH1ZcyFbX9hdBI4xPAtzFX51AsSa8dpRdG+8DmI41Q/1ludoMZboExHldlUbQH\n"+ "zUuHKF8/T+aNo/9FfpqDz1fFnuoF7tuwyRh73B0YDyDVTNuq7LJ4tmzpVvqIt2tn\n"+ "RJnQoL4pLQ40SQsoUi4FYG/gxJMoQX6ROWe2nyg=\n"+ "-----END CERTIFICATE-----"); }}; private final ArrayList<String> pemCertificateList2 = new ArrayList<String>() {{ add("-----BEGIN CERTIFICATE-----\n" + "MIIE2TCCA8GgAwIBAgIQFVDTs9tHXX3ivhstjNW2zANBgkqhkiG9w0BAQUFADA8\n" + "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMuMRYwFAYDVQQDEw1U\n" + "aGF3dGUgU1NMIENBMB4XDTE0MTAwMjAwMDAwMFoXDTE1MTEwMTIzNTk1OVowgZcx\n" + "CzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRIwEAYDVQQHFAlQYWxv\n" + "IEFsdG8xGzAZBgNVBAoUEkRhdGEgVGhlb3JlbSwgSW5jLjEkMCIGA1UECxQbU2Nh\n" + "biBhbmQgU2VjdXJlIE1vYmlsZSBBcHBzMRwwGgYDVQQDFBN3d3cuZGF0YXRoZW9y\n" + "ZW0uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5bCuLK3XOnNs\n" + "i8CJvHU4H5yY3d4G1qzq7EeMydKuScMM8Nqsp4CySKTbrUhi/uIc08II9yBxM+q4\n" + "NmrEg0tgVvTqvUjmMN/MrYQrSGVLxPq5gadI7UxfWeGSo9DpvgXaw1Vvehs2jGFK\n" + "jLzDYbzJOhv/pqpv4UCV/xfeuqmTNqqzsp+tB5Zn6gXIvIFsxfpjbeId4OWviLnC\n" + "q957++coddvqBZd2sWkyzE2un5itXRKfnMGSBTB0cU9/9fXeGhzA+u01Xj+BfpHR\n" + "uP/eX+rHsgc3a4hbsSWDG5278ujJ5+4To9Bn/rTZy7uALTM2oBZvsFX4567RhB1\n" + "IYbMDE5y8QIDAQABo4IBeTCCAXUwHgYDVR0RBBcwFYITd3d3LmRhdGF0aGVvcmVt\n" + "LmNvbTAJBgNVHRMEAjAAMHIGA1UdIARrMGkwZwYKYIZIAYb4RQEHNjBZMCYGCCsG\n" + "AQUFBwIBFhpodHRwczovL3d3dy50aGF3dGUuY29tL2NwczAvBggrBgEFBQcCAjAj\n" + "DCFodHRwczovL3d3dy50aGF3dGUuY29tL3JlcG9zaXRvcnkwDgYDVR0PAQH/BAQD\n" + "AgWgMB8GA1UdIwQYMBaAFKeig7s0RUA9/NUwTxK5PqEBn/bbMCsGA1UdHwQkMCIw\n" + "IKAeoByGGmh0dHA6Ly90Yi5zeW1jYi5jb20vdGIuY3JsMB0GA1UdJQQWMBQGCCsG\n" + "AQUFBwMBBggrBgEFBQcDAjBXBggrBgEFBQcBAQRLMEkwHwYIKwYBBQUHMAGGE2h0\n" + "dHA6Ly90Yi5zeW1jZC5jb20wJgYIKwYBBQUHMAKGGmh0dHA6Ly90Yi5zeW1jYi5j\n" + "b20vdGIuY3J0MA0GCSqGSIb3DQEBBQUAA4IBAQB2qnnrsAICkV9HNuBdXe+cThHV\n" + "8+5+LBz3zGDpC1rCyq/DIGu0vaa/gasM+MswPj+AEI4f1K1x9K9KedjilVfXH+QI\n" + "tfRzLO8iR0TbPsC6Y1avuXhal1BuvZ9UQayHRDPUEncsf+SHbIOD2GJzXy7vVk5a\n" + "VjkvxLtjMprWIi+P7Hbn2qj03qX9KM1DnNsB28jqg7r2rpXNUPUKsxekfrMTaJgg\n" + "zTnCN/EQvF5eGvAjjHckr1SlogV9o/y4k0x6YmPWR/vopMEPyOj+JhflKCdg+6w3\n" + "79ESvZUhmgT2285c1Nu5vJjtr8x51zCNIpEoVqdkCU4c1aVZGZogSWl1rAIi\n" + "-----END CERTIFICATE-----"); }}; @Test public void test() { PinningFailureReport report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.host.com", 443, "host.com", true, true, pemCertificateList1, pemCertificateList1, new Date(), pinList, PinningValidationResult.FAILED); // Ensure the same report will not be sent twice in a row assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Set the last time the cache was reset to more than 24 hours ago and ensure the report // is sent again long oneDayAgo = System.currentTimeMillis()-25*60*60*1000; TestableReportRateLimiter.setLastReportsCacheResetDate(new Date(oneDayAgo)); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Ensure the same report with a different validation result will be sent report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.host.com", 443, "host.com", true, true, pemCertificateList1, pemCertificateList1, new Date(), pinList, PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Ensure the same report with a different hostname will be sent report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.otherhost.com", 443, "host.com", true, true, pemCertificateList1, pemCertificateList1, new Date(), pinList, PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Ensure the same report with a different certificate chain will be sent report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.otherhost.com", 443, "host.com", true, true, pemCertificateList2, pemCertificateList2, new Date(), pinList, PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); } }
UTF-8
Java
7,257
java
ReportRateLimiterTest.java
Java
[ { "context": "<PublicKeyPin>() {{\n add(new PublicKeyPin(\"rFjc3wG7lTZe43zeYTvPq8k4xdDEutCmIhI5dn4oCeE=\"));\n add(new PublicKeyPin(\"0SDf3cRToyZJaMso", "end": 660, "score": 0.99973064661026, "start": 615, "tag": "KEY", "value": "rFjc3wG7lTZe43zeYTvPq8k4xdDEutCmIhI5dn4oCeE=\"" ...
null
[]
package com.datatheorem.android.trustkit.reporting; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import androidx.test.runner.AndroidJUnit4; import com.datatheorem.android.trustkit.config.PublicKeyPin; import com.datatheorem.android.trustkit.pinning.PinningValidationResult; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import org.junit.Test; import org.junit.runner.RunWith; public class ReportRateLimiterTest { private final HashSet<PublicKeyPin> pinList = new HashSet<PublicKeyPin>() {{ add(new PublicKeyPin("<KEY>)); add(new PublicKeyPin("<KEY>)); }}; private final ArrayList<String> pemCertificateList1 = new ArrayList<String>() {{ add("-----BEGIN CERTIFICATE-----\n"+ "MIIDGTCCAgGgAwIBAgIJAI1jD1qixIPLMA0GCSqGSIb3DQEBBQUAMCMxITAfBgNV\n"+ "BAMMGGV2aWxjZXJ0LmRhdGF0aGVvcmVtLmNvbTAeFw0xNTEyMjAxMzU4NDNaFw0y\n"+ "NTEyMTcxMzU4NDNaMCMxITAfBgNVBAMMGGV2aWxjZXJ0LmRhdGF0aGVvcmVtLmNv\n"+ "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMdltqsRJtO7Nqypkehh\n"+ "4DSEirp9RM+hJXkBE9nRleTO+utV/snWqX/0wsUrz0wgWyPnAHybGOOXvkrWfXSt\n"+ "c2/8PyONOeFEU/9S/lWBXGZkaPhgTvkEzPmOOhf06rBMTwXUMGNDI45gKFgkO6Br\n"+ "bGPeSCuheQj0TKeWdwwNoJ+kczUE06IKu2tcuFRjHXci6VeHjANJzrfKro4ivIRy\n"+ "bewOGJj1onnpKbui/EOytsmW9MPpOSEXMoVksHOKBQ9nhpL6cDODRvG+t8u7qfFt\n"+ "mhphemK3IYNMNA4MMXpbJ+Au2hnPApZPEOit34bAwOiGi/batcS3iA+nl06dPYA9\n"+ "nPkCAwEAAaNQME4wHQYDVR0OBBYEFANxdSXS1JSvjdNtNbYBbRlgii93MB8GA1Ud\n"+ "Iw<KEY>vjdNtNbYBbRlgii93MAwGA1UdEw<KEY>\n"+ "hvcNAQEFBQADggEBAAM78Bt2aLUgl2Yq4KMIGDeHdWYcRB7QPQ8sp3Q1TOQQzw0i\n"+ "AukRccl9iYNLgaSJDvlVMapD76jo3okydoWgDogWJhtZpMU/9xegIpukmu5hvF6i\n"+ "NpqE99PFO5E8BpMkNz+2nskwu//D0as6P9F3tA/o3jC6n6fWX0gt/e9th2ZgVwNQ\n"+ "9JTH1ZcyFbX9hdBI4xPAtzFX51AsSa8dpRdG+8DmI41Q/1ludoMZboExHldlUbQH\n"+ "zUuHKF8/T+aNo/9FfpqDz1fFnuoF7tuwyRh73B0YDyDVTNuq7LJ4tmzpVvqIt2tn\n"+ "RJnQoL4pLQ40SQsoUi4FYG/gxJMoQX6ROWe2nyg=\n"+ "-----END CERTIFICATE-----"); }}; private final ArrayList<String> pemCertificateList2 = new ArrayList<String>() {{ add("-----BEGIN CERTIFICATE-----\n" + "MIIE2TCCA8GgAwIBAgIQFVDTs9tHXX3ivhstjNW2zANBgkqhkiG9w0BAQUFADA8\n" + "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMuMRYwFAYDVQQDEw1U\n" + "<KEY>n" + "<KEY>" + "<KEY>" + "<KEY>n" + "<KEY>w<KEY>Q8<KEY>5bCuLK3XOnNs\n" + "i8CJvHU4H5yY3d4G1qzq7EeMydKuScMM8Nqsp4CySKTbrUhi/uIc08II9yBxM+q4\n" + "NmrEg0tgVvTqvUjmMN/MrYQrSGVLxPq5gadI7UxfWeGSo9DpvgXaw1Vvehs2jGFK\n" + "jLzDYbzJOhv/pqpv4UCV/xfeuqmTNqqzsp+tB5Zn6gXIvIFsxfpjbeId4OWviLnC\n" + "q957++coddvqBZd2sWkyzE2un5itXRKfnMGSBTB0cU9/9fXeGhzA+u01Xj+BfpHR\n" + "uP/eX+rHsgc3a4hbsSWDG5278ujJ5+4To9Bn/rTZy7uALTM2oBZvsFX4567RhB1\n" + "IYbMDE5y8QIDAQABo4IBeTCCAXUwHgYDVR0RBBcwFYITd3d3LmRhdGF0aGVvcmVt\n" + "Lm<KEY>n" + "<KEY>" + "<KEY>zovL3d3dy50aGF3d<KEY>lc<KEY>DgYD<KEY>\n" + "<KEY>UdIw<KEY>ig7s0RUA9/NUwTxK5PqEBn/bbMCsGA1UdHwQkMCIw\n" + "IKAeoByGGmh0dHA6Ly90Yi5zeW1jYi5jb20vdGIuY3JsMB0GA1UdJQQWMBQGCCsG\n" + "<KEY>BgEFBQc<KEY>FBQc<KEY>\n" + "dHA6Ly90Yi5zeW1jZC5jb20wJgYIKwYBBQUHMAKGGmh0dHA6Ly90Yi5zeW1jYi5j\n" + "b20vdGIuY3J0MA0GCSqGSIb3DQEBBQUAA4IBAQB2qnnrsAICkV9HNuBdXe+cThHV\n" + "8+5+LBz3zGDpC1rCyq/DIGu0vaa/gasM+MswPj+AEI4f1K1x9K9KedjilVfXH+QI\n" + "tfRzLO8iR0TbPsC6Y1avuXhal1BuvZ9UQayHRDPUEncsf+SHbIOD2GJzXy7vVk5a\n" + "VjkvxLtjMprWIi+P7Hbn2qj03qX9KM1DnNsB28jqg7r2rpXNUPUKsxekfrMTaJgg\n" + "zTnCN/EQvF5eGvAjjHckr1SlogV9o/y4k0x6YmPWR/vopMEPyOj+JhflKCdg+6w3\n" + "79ESvZUhmgT2285c1Nu5vJjtr8x51zCNIpEoVqdkCU4c1aVZGZogSWl1rAIi\n" + "-----END CERTIFICATE-----"); }}; @Test public void test() { PinningFailureReport report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.host.com", 443, "host.com", true, true, pemCertificateList1, pemCertificateList1, new Date(), pinList, PinningValidationResult.FAILED); // Ensure the same report will not be sent twice in a row assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Set the last time the cache was reset to more than 24 hours ago and ensure the report // is sent again long oneDayAgo = System.currentTimeMillis()-25*60*60*1000; TestableReportRateLimiter.setLastReportsCacheResetDate(new Date(oneDayAgo)); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Ensure the same report with a different validation result will be sent report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.host.com", 443, "host.com", true, true, pemCertificateList1, pemCertificateList1, new Date(), pinList, PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Ensure the same report with a different hostname will be sent report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.otherhost.com", 443, "host.com", true, true, pemCertificateList1, pemCertificateList1, new Date(), pinList, PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); // Ensure the same report with a different certificate chain will be sent report = new PinningFailureReport("com.test", "1.2.3", "vendorId", "www.otherhost.com", 443, "host.com", true, true, pemCertificateList2, pemCertificateList2, new Date(), pinList, PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED); assertFalse(ReportRateLimiter.shouldRateLimit(report)); assertTrue(ReportRateLimiter.shouldRateLimit(report)); } }
6,688
0.709384
0.655229
122
58.483608
32.167908
96
false
false
0
0
0
0
64
0.343944
0.672131
false
false
2
2954ededd83edfdad2654fc5d62b88754c3eada0
38,714,835,246,233
57b049bc606b7e864c75a52b94f666eba9fa98c2
/app/src/main/java/com/copasso/cocobill/mvp/model/Imp/MonthChartModelImp.java
21de5a8fe98296c2b258980eacbaf76e379340b7
[]
no_license
JinHT1218/CocoBill-master
https://github.com/JinHT1218/CocoBill-master
f088989731b9d678aed539c954fdad05737c843e
84f47f9fdb24a0b33d0ee2075c1df0f0875d73c0
refs/heads/master
2020-03-25T04:45:13.538000
2018-08-03T10:03:37
2018-08-03T10:03:37
143,411,425
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.copasso.cocobill.mvp.model.Imp; import com.copasso.cocobill.base.BaseObserver; import com.copasso.cocobill.model.bean.local.BBill; import com.copasso.cocobill.model.bean.local.MonthChartBean; import com.copasso.cocobill.model.repository.LocalRepository; import com.copasso.cocobill.mvp.model.MonthChartModel; import com.copasso.cocobill.utils.BillUtils; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import java.util.List; public class MonthChartModelImp implements MonthChartModel { private MonthChartOnListener listener; public MonthChartModelImp(MonthChartOnListener listener) { this.listener = listener; } @Override public void getMonthChartBills(int id, String year, String month) { LocalRepository.getInstance().getBBillByUserIdWithYM(id, year, month) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new BaseObserver<List<BBill>>() { @Override protected void onSuccees(List<BBill> bBills) throws Exception { listener.onSuccess(BillUtils.packageChartList(bBills)); } @Override protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception { listener.onFailure(e); } }); } @Override public void onUnsubscribe() { } /** * 回调接口 */ public interface MonthChartOnListener { void onSuccess(MonthChartBean bean); void onFailure(Throwable e); } }
UTF-8
Java
1,705
java
MonthChartModelImp.java
Java
[]
null
[]
package com.copasso.cocobill.mvp.model.Imp; import com.copasso.cocobill.base.BaseObserver; import com.copasso.cocobill.model.bean.local.BBill; import com.copasso.cocobill.model.bean.local.MonthChartBean; import com.copasso.cocobill.model.repository.LocalRepository; import com.copasso.cocobill.mvp.model.MonthChartModel; import com.copasso.cocobill.utils.BillUtils; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import java.util.List; public class MonthChartModelImp implements MonthChartModel { private MonthChartOnListener listener; public MonthChartModelImp(MonthChartOnListener listener) { this.listener = listener; } @Override public void getMonthChartBills(int id, String year, String month) { LocalRepository.getInstance().getBBillByUserIdWithYM(id, year, month) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new BaseObserver<List<BBill>>() { @Override protected void onSuccees(List<BBill> bBills) throws Exception { listener.onSuccess(BillUtils.packageChartList(bBills)); } @Override protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception { listener.onFailure(e); } }); } @Override public void onUnsubscribe() { } /** * 回调接口 */ public interface MonthChartOnListener { void onSuccess(MonthChartBean bean); void onFailure(Throwable e); } }
1,705
0.657631
0.657631
54
30.425926
27.046326
100
false
false
0
0
0
0
0
0
0.407407
false
false
2
5817ef9074b8cea0450790e3d971bdcb3f5ae530
38,027,640,450,611
e9d5a9927f37b7f96be716192c85517f8cfaaba0
/src/com/chd/hrp/ass/serviceImpl/repair/AssRepairRecServiceImpl.java
a260ef1086046fc39d501271cda358a0563e43ea
[]
no_license
moutainhigh/chdHRP
https://github.com/moutainhigh/chdHRP
2e227136bbfa0ec303ceae594964bf3ad7dd7bcc
481bf54d10c4dfb7bd457d678f9b3621b5889f15
refs/heads/master
2022-05-25T23:56:21.391000
2020-04-29T08:09:08
2020-04-29T08:09:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @Description: * @Copyright: Copyright (c) 2015-9-16 下午9:54:34 * @Company: 杭州亦童科技有限公司 * @网站:www.s-chd.com */ package com.chd.hrp.ass.serviceImpl.repair; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.ibatis.session.RowBounds; import org.apache.log4j.Logger; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import com.chd.base.SessionManager; import com.chd.base.SysPage; import com.chd.base.exception.SysException; import com.chd.base.util.ChdJson; import com.chd.hrp.ass.dao.card.AssCardGeneralMapper; import com.chd.hrp.ass.dao.card.AssCardHouseMapper; import com.chd.hrp.ass.dao.card.AssCardInassetsMapper; import com.chd.hrp.ass.dao.card.AssCardLandMapper; import com.chd.hrp.ass.dao.card.AssCardOtherMapper; import com.chd.hrp.ass.dao.card.AssCardSpecialMapper; import com.chd.hrp.ass.dao.repair.AssRepairApplyMapper; import com.chd.hrp.ass.dao.repair.AssRepairRecDetailMapper; import com.chd.hrp.ass.dao.repair.AssRepairRecMapper; import com.chd.hrp.ass.entity.repair.AssRepairApply; import com.chd.hrp.ass.entity.repair.AssRepairRec; import com.chd.hrp.ass.entity.repair.AssRepairRecDetail; import com.chd.hrp.ass.service.repair.AssRepairRecService; import com.github.pagehelper.PageInfo; /** * * @Description: * tabledesc * @Table: * ASS_REPAIR_REC * @Author: bell * @email: bell@e-tonggroup.com * @Version: 1.0 */ @Service("assRepairRecService") public class AssRepairRecServiceImpl implements AssRepairRecService { private static Logger logger = Logger.getLogger(AssRepairRecServiceImpl.class); //引入DAO操作 @Resource(name = "assRepairRecMapper") private final AssRepairRecMapper assRepairRecMapper = null; //引入DAO操作 @Resource(name = "assRepairRecDetailMapper") private final AssRepairRecDetailMapper assRepairRecDetailMapper = null; //引入DAO操作 @Resource(name = "assRepairApplyMapper") private final AssRepairApplyMapper assRepairApplyMapper = null; @Resource(name = "assCardSpecialMapper") private final AssCardSpecialMapper assCardSpecialMapper = null; @Resource(name = "assCardGeneralMapper") private final AssCardGeneralMapper assCardGeneralMapper = null; @Resource(name = "assCardOtherMapper") private final AssCardOtherMapper assCardOtherMapper = null; @Resource(name = "assCardHouseMapper") private final AssCardHouseMapper assCardHouseMapper = null; @Resource(name = "assCardInassetsMapper") private final AssCardInassetsMapper assCardInassetsMapper = null; @Resource(name = "assCardLandMapper") private final AssCardLandMapper assCardLandMapper = null; /** * @Description * 添加tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String add(Map<String,Object> entityMap)throws DataAccessException{ //获取对象tabledesc AssRepairRec assRepairRec = queryByCode(entityMap); if (assRepairRec != null) { return "{\"error\":\"数据重复,请重新添加.\"}"; } try { int state = assRepairRecMapper.add(entityMap); return "{\"msg\":\"添加成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"添加失败 数据库异常 请联系管理员! 方法 add\"}"; } } /** * @Description * 批量添加tabledesc<BR> * @param entityList * @return String JSON * @throws DataAccessException */ @Override public String addBatch(List<Map<String,Object>> entityList)throws DataAccessException{ try { assRepairRecMapper.addBatch(entityList); return "{\"msg\":\"添加成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"添加失败 数据库异常 请联系管理员! 方法 addBatch\"}"; } } /** * @Description * 更新tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String update(Map<String,Object> entityMap)throws DataAccessException{ List<Map<String,Object>> listVo = new ArrayList<Map<String,Object>>(); List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); Map<String,Object> exitMap = new HashMap<String, Object>(); Map<String,Object> invMap = new HashMap<String, Object>(); try { //从主表取出卡片信息,根据资产性质,更新卡片状态, Map<String,Object> cardMap = new HashMap<String, Object>(); AssRepairApply assRepairApply =assRepairApplyMapper.queryByCode(entityMap); cardMap.put("group_id", assRepairApply.getGroup_id()); cardMap.put("hos_id", assRepairApply.getHos_id()); cardMap.put("copy_code", assRepairApply.getCopy_code()); cardMap.put("ass_card_no", assRepairApply.getAss_card_no()); if("7".equals(entityMap.get("state").toString())){ cardMap.put("use_state", 4); }else{ cardMap.put("use_state", 3); } if(assRepairApply.getAss_nature()!=null){ if("02".equals(assRepairApply.getAss_nature())){ assCardSpecialMapper.updateAssCardStateByRecCardNo(cardMap); }else if("03".equals(assRepairApply.getAss_nature())){ assCardGeneralMapper.updateAssCardStateByRecCardNo(cardMap); }else if("04".equals(assRepairApply.getAss_nature())){ assCardOtherMapper.updateAssCardStateByRecCardNo(cardMap); } else if("01".equals(assRepairApply.getAss_nature())){ assCardHouseMapper.updateAssCardStateByRecCardNo(cardMap); }else if("05".equals(assRepairApply.getAss_nature())){ assCardInassetsMapper.updateAssCardStateByRecCardNo(cardMap); }else if("06".equals(assRepairApply.getAss_nature())){ assCardLandMapper.updateAssCardStateByRecCardNo(cardMap); } } //更新记录表信息, int state = assRepairRecMapper.update(entityMap); //材料取出明细数据 List<Map> detail = ChdJson.fromJsonAsList(Map.class, entityMap.get("ParamVo").toString()); for (Map<String,Object> map : detail) { if(map.get("inv_code")!=null){ map.put("group_id", SessionManager.getGroupId()); map.put("hos_id", SessionManager.getHosId()); map.put("copy_code", SessionManager.getCopyCode()); map.put("repair_rec_no", entityMap.get("repair_rec_no")); map.put("ass_year", assRepairApply.getAss_year()); map.put("ass_month", assRepairApply.getAss_month()); exitMap.put("group_id", SessionManager.getGroupId()); exitMap.put("hos_id", SessionManager.getHosId()); exitMap.put("copy_code", SessionManager.getCopyCode()); //判断所传 AssRepairRecDetail assRepairRecDetail= assRepairRecDetailMapper.queryAssRepairRecDetailByCode(map); if(assRepairRecDetail!=null){ exitMap.put("repair_rec_no", assRepairRecDetail.getRepair_rec_no()); exitMap.put("inv_code", assRepairRecDetail.getInv_code()); listVo.add(exitMap); } list.add(map); } } if(listVo.size()>0){ assRepairRecDetailMapper.deleteBatchAssRepairRecDetail(listVo); assRepairRecDetailMapper.addBatchAssRepairRecDetail(list); }else if(list.size()>0){ assRepairRecDetailMapper.addBatchAssRepairRecDetail(list); } return "{\"msg\":\"更新成功.\",\"state\":\"true\"}"; } catch (Exception e) { throw new SysException(e); } } /** * @Description * 批量更新tabledesc<BR> * @param entityList * @return String JSON * @throws DataAccessException */ @Override public String updateBatch(List<Map<String,Object>> entityList)throws DataAccessException{ try { assRepairRecMapper.updateBatch(entityList); return "{\"msg\":\"更新成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"删除失败 数据库异常 请联系管理员! 方法 updateBatch\"}"; } } /** * @Description * 删除tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String delete(Map<String, Object> entityMap) throws DataAccessException { try { int state = assRepairRecMapper.delete(entityMap); return "{\"msg\":\"删除成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"删除失败 数据库异常 请联系管理员! 方法 delete\"}"; } } /** * @Description * 批量删除tabledesc<BR> * @param entityList * @return String JSON * @throws DataAccessException */ @Override public String deleteBatch(List<Map<String,Object>> entityList)throws DataAccessException{ try { assRepairRecMapper.deleteBatch(entityList); return "{\"msg\":\"删除成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"删除失败 数据库异常 请联系管理员! 方法 deleteBatch\"}"; } } /** * @Description * 添加tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String addOrUpdate(Map<String,Object> entityMap)throws DataAccessException{ /** * 备注 先判断是否存在 存在即更新不存在则添加<br> * 在判断是否存在时可根据实际情况进行修改传递的参数进行判断<br> * 判断是否名称相同 判断是否 编码相同 等一系列规则 */ //判断是否存在对象tabledesc Map<String, Object> mapVo=new HashMap<String, Object>(); mapVo.put("group_id",entityMap.get("group_id")); mapVo.put("hos_id",entityMap.get("hos_id")); mapVo.put("copy_code", entityMap.get("copy_code")); mapVo.put("acct_year", entityMap.get("acct_year")); List<AssRepairRec> list = (List<AssRepairRec>)assRepairRecMapper.queryExists(mapVo); if (list.size()>0) { int state = assRepairRecMapper.update(entityMap); return "{\"msg\":\"更新成功.\",\"state\":\"true\"}"; } try { int state = assRepairRecMapper.add(entityMap); return "{\"msg\":\"添加成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"添加失败 数据库异常 请联系管理员! 方法 addOrUpdate\"}"; } } /** * @Description * 查询结果集tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String query(Map<String,Object> entityMap) throws DataAccessException{ SysPage sysPage = new SysPage(); sysPage = (SysPage) entityMap.get("sysPage"); if (sysPage.getTotal()==-1){ List<AssRepairRec> list = (List<AssRepairRec>)assRepairRecMapper.query(entityMap); return ChdJson.toJson(list); }else{ RowBounds rowBounds = new RowBounds(sysPage.getPage(), sysPage.getPagesize()); List<AssRepairRec> list = (List<AssRepairRec>)assRepairRecMapper.query(entityMap, rowBounds); PageInfo page = new PageInfo(list); return ChdJson.toJson(list, page.getTotal()); } } /** * @Description * 获取对象tabledesc<BR> * @param entityMap<BR> * 参数为主键 * @return String JSON * @throws DataAccessException */ @Override public <T> T queryByCode(Map<String,Object> entityMap)throws DataAccessException{ return assRepairRecMapper.queryByCode(entityMap); } /** * @Description * 获取tabledesc<BR> * @param entityMap<BR> * 参数为要检索的字段 * @return AssRepairRec * @throws DataAccessException */ @Override public <T> T queryByUniqueness(Map<String,Object> entityMap)throws DataAccessException{ return assRepairRecMapper.queryByUniqueness(entityMap); } /** * @Description * 获取tabledesc<BR> * @param entityMap<BR> * 参数为要检索的字段 * @return List<AssRepairRec> * @throws DataAccessException */ @Override public List<?> queryExists(Map<String,Object> entityMap)throws DataAccessException{ return assRepairRecMapper.queryExists(entityMap); } @Override public String queryAssRepairRecDetail(Map<String, Object> mapVo) { List<AssRepairRecDetail> list =(List<AssRepairRecDetail>) assRepairRecDetailMapper.queryAssRepairRecDetail(mapVo); return ChdJson.toJson(list); } @Override public String deleteAssRepairRecDetail(List<Map<String, Object>> listVo) { try { assRepairRecDetailMapper.deleteBatchAssRepairRecDetail(listVo); return "{\"msg\":\"删除成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } @Override public String auditAssRepairRec(List<Map<String, Object>> mapVo) { try { for (Map<String, Object> map : mapVo) { AssRepairRec assRepairRec=assRepairRecMapper.queryByCode(map); if(assRepairRec.getState()==3){ continue; }else if (assRepairRec.getState()==4){ return "{\"warn\":\"已维修确认维修完成的单据能审核,请重新选择.\",\"state\":\"false\"}"; }else { map.put("audit_emp", SessionManager.getUserId()); assRepairRecMapper.auditAssRepairRec(map); } } return "{\"msg\":\"审核成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } @Override public String backAssRepairRec(List<Map<String, Object>> mapVo) { try { for (Map<String, Object> map : mapVo) { AssRepairRec assRepairRec=assRepairRecMapper.queryByCode(map); if(assRepairRec.getState()==2){ continue; }else if (assRepairRec.getState()!=3){ return "{\"warn\":\"所选择单据存在未审核数据,请核对.\",\"state\":\"false\"}"; }else if (assRepairRec.getState()==4){ return "{\"warn\":\"已维修确认维修完成的单据能撤销审核,请重新选择.\",\"state\":\"false\"}"; }else{ map.put("audit_emp", SessionManager.getUserId()); assRepairRecMapper.backAssRepairRec(map); } } return "{\"msg\":\"消审成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } @Override public String countAssRepairRec(List<Map<String, Object>> mapVo) { try { for (Map<String, Object> map : mapVo) { Map<String,Object> cardMap = new HashMap<String, Object>(); AssRepairRec assRepairRec=assRepairRecMapper.queryByCode(map); if(assRepairRec.getState()!=3){ return "{\"warn\":\"维修确认完成的单据必须为审核状态.\",\"state\":\"false\"}"; }else{ map.put("audit_emp", SessionManager.getUserId()); assRepairRecMapper.countAssRepairRec(map); } cardMap.put("group_id", assRepairRec.getGroup_id()); cardMap.put("hos_id", assRepairRec.getHos_id()); cardMap.put("copy_code", assRepairRec.getCopy_code()); cardMap.put("ass_card_no", assRepairRec.getAss_card_no()); cardMap.put("use_state",4); if(assRepairRec.getAss_nature()!=null){ if("02".equals(assRepairRec.getAss_nature())){ assCardSpecialMapper.updateAssCardStateByRecCardNo(cardMap); }else if("03".equals(assRepairRec.getAss_nature())){ assCardGeneralMapper.updateAssCardStateByRecCardNo(cardMap); }else if("04".equals(assRepairRec.getAss_nature())){ assCardOtherMapper.updateAssCardStateByRecCardNo(cardMap); } else if("01".equals(assRepairRec.getAss_nature())){ assCardHouseMapper.updateAssCardStateByRecCardNo(cardMap); }else if("05".equals(assRepairRec.getAss_nature())){ assCardInassetsMapper.updateAssCardStateByRecCardNo(cardMap); }else if("06".equals(assRepairRec.getAss_nature())){ assCardLandMapper.updateAssCardStateByRecCardNo(cardMap); } } } return "{\"msg\":\"确认成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } /** * 资产维修打印 */ @Override public Map<String,Object> queryAssRepairRecDY(Map<String, Object> map)throws DataAccessException { try{ Map<String,Object> reMap=new HashMap<String,Object>(); WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); AssRepairRecMapper assRepairRecMapper = (AssRepairRecMapper)context.getBean("assRepairRecMapper"); if("1".equals(String.valueOf(map.get("p_num")))){ // 资产维修打印模板主表 List<Map<String,Object>> mainList=assRepairRecMapper.queryaAssRepairRecBatch(map); //资产维修打印模板从表 List<Map<String,Object>> detailList=assRepairRecMapper.queryAssRepairRec_detail(map); reMap.put("main", mainList); reMap.put("detail", detailList); }else{ Map<String,Object> mainList=assRepairRecMapper.querAssRepairRecByPrint(map); //资产维修打印模板从表 List<Map<String,Object>> detailList=assRepairRecMapper.queryAssRepairRec_detail(map); reMap.put("main", mainList); reMap.put("detail", detailList); } return reMap; }catch(Exception e){ logger.error(e.getMessage(),e); throw new SysException(e.getMessage()); } } }
UTF-8
Java
17,245
java
AssRepairRecServiceImpl.java
Java
[ { "context": "tabledesc\n * @Table:\n * ASS_REPAIR_REC\n * @Author: bell\n * @email: bell@e-tonggroup.com\n * @Version: 1.0", "end": 1569, "score": 0.9996421933174133, "start": 1565, "tag": "USERNAME", "value": "bell" }, { "context": "le:\n * ASS_REPAIR_REC\n * @Author: bell\n * @em...
null
[]
/** * @Description: * @Copyright: Copyright (c) 2015-9-16 下午9:54:34 * @Company: 杭州亦童科技有限公司 * @网站:www.s-chd.com */ package com.chd.hrp.ass.serviceImpl.repair; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.ibatis.session.RowBounds; import org.apache.log4j.Logger; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import com.chd.base.SessionManager; import com.chd.base.SysPage; import com.chd.base.exception.SysException; import com.chd.base.util.ChdJson; import com.chd.hrp.ass.dao.card.AssCardGeneralMapper; import com.chd.hrp.ass.dao.card.AssCardHouseMapper; import com.chd.hrp.ass.dao.card.AssCardInassetsMapper; import com.chd.hrp.ass.dao.card.AssCardLandMapper; import com.chd.hrp.ass.dao.card.AssCardOtherMapper; import com.chd.hrp.ass.dao.card.AssCardSpecialMapper; import com.chd.hrp.ass.dao.repair.AssRepairApplyMapper; import com.chd.hrp.ass.dao.repair.AssRepairRecDetailMapper; import com.chd.hrp.ass.dao.repair.AssRepairRecMapper; import com.chd.hrp.ass.entity.repair.AssRepairApply; import com.chd.hrp.ass.entity.repair.AssRepairRec; import com.chd.hrp.ass.entity.repair.AssRepairRecDetail; import com.chd.hrp.ass.service.repair.AssRepairRecService; import com.github.pagehelper.PageInfo; /** * * @Description: * tabledesc * @Table: * ASS_REPAIR_REC * @Author: bell * @email: <EMAIL> * @Version: 1.0 */ @Service("assRepairRecService") public class AssRepairRecServiceImpl implements AssRepairRecService { private static Logger logger = Logger.getLogger(AssRepairRecServiceImpl.class); //引入DAO操作 @Resource(name = "assRepairRecMapper") private final AssRepairRecMapper assRepairRecMapper = null; //引入DAO操作 @Resource(name = "assRepairRecDetailMapper") private final AssRepairRecDetailMapper assRepairRecDetailMapper = null; //引入DAO操作 @Resource(name = "assRepairApplyMapper") private final AssRepairApplyMapper assRepairApplyMapper = null; @Resource(name = "assCardSpecialMapper") private final AssCardSpecialMapper assCardSpecialMapper = null; @Resource(name = "assCardGeneralMapper") private final AssCardGeneralMapper assCardGeneralMapper = null; @Resource(name = "assCardOtherMapper") private final AssCardOtherMapper assCardOtherMapper = null; @Resource(name = "assCardHouseMapper") private final AssCardHouseMapper assCardHouseMapper = null; @Resource(name = "assCardInassetsMapper") private final AssCardInassetsMapper assCardInassetsMapper = null; @Resource(name = "assCardLandMapper") private final AssCardLandMapper assCardLandMapper = null; /** * @Description * 添加tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String add(Map<String,Object> entityMap)throws DataAccessException{ //获取对象tabledesc AssRepairRec assRepairRec = queryByCode(entityMap); if (assRepairRec != null) { return "{\"error\":\"数据重复,请重新添加.\"}"; } try { int state = assRepairRecMapper.add(entityMap); return "{\"msg\":\"添加成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"添加失败 数据库异常 请联系管理员! 方法 add\"}"; } } /** * @Description * 批量添加tabledesc<BR> * @param entityList * @return String JSON * @throws DataAccessException */ @Override public String addBatch(List<Map<String,Object>> entityList)throws DataAccessException{ try { assRepairRecMapper.addBatch(entityList); return "{\"msg\":\"添加成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"添加失败 数据库异常 请联系管理员! 方法 addBatch\"}"; } } /** * @Description * 更新tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String update(Map<String,Object> entityMap)throws DataAccessException{ List<Map<String,Object>> listVo = new ArrayList<Map<String,Object>>(); List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); Map<String,Object> exitMap = new HashMap<String, Object>(); Map<String,Object> invMap = new HashMap<String, Object>(); try { //从主表取出卡片信息,根据资产性质,更新卡片状态, Map<String,Object> cardMap = new HashMap<String, Object>(); AssRepairApply assRepairApply =assRepairApplyMapper.queryByCode(entityMap); cardMap.put("group_id", assRepairApply.getGroup_id()); cardMap.put("hos_id", assRepairApply.getHos_id()); cardMap.put("copy_code", assRepairApply.getCopy_code()); cardMap.put("ass_card_no", assRepairApply.getAss_card_no()); if("7".equals(entityMap.get("state").toString())){ cardMap.put("use_state", 4); }else{ cardMap.put("use_state", 3); } if(assRepairApply.getAss_nature()!=null){ if("02".equals(assRepairApply.getAss_nature())){ assCardSpecialMapper.updateAssCardStateByRecCardNo(cardMap); }else if("03".equals(assRepairApply.getAss_nature())){ assCardGeneralMapper.updateAssCardStateByRecCardNo(cardMap); }else if("04".equals(assRepairApply.getAss_nature())){ assCardOtherMapper.updateAssCardStateByRecCardNo(cardMap); } else if("01".equals(assRepairApply.getAss_nature())){ assCardHouseMapper.updateAssCardStateByRecCardNo(cardMap); }else if("05".equals(assRepairApply.getAss_nature())){ assCardInassetsMapper.updateAssCardStateByRecCardNo(cardMap); }else if("06".equals(assRepairApply.getAss_nature())){ assCardLandMapper.updateAssCardStateByRecCardNo(cardMap); } } //更新记录表信息, int state = assRepairRecMapper.update(entityMap); //材料取出明细数据 List<Map> detail = ChdJson.fromJsonAsList(Map.class, entityMap.get("ParamVo").toString()); for (Map<String,Object> map : detail) { if(map.get("inv_code")!=null){ map.put("group_id", SessionManager.getGroupId()); map.put("hos_id", SessionManager.getHosId()); map.put("copy_code", SessionManager.getCopyCode()); map.put("repair_rec_no", entityMap.get("repair_rec_no")); map.put("ass_year", assRepairApply.getAss_year()); map.put("ass_month", assRepairApply.getAss_month()); exitMap.put("group_id", SessionManager.getGroupId()); exitMap.put("hos_id", SessionManager.getHosId()); exitMap.put("copy_code", SessionManager.getCopyCode()); //判断所传 AssRepairRecDetail assRepairRecDetail= assRepairRecDetailMapper.queryAssRepairRecDetailByCode(map); if(assRepairRecDetail!=null){ exitMap.put("repair_rec_no", assRepairRecDetail.getRepair_rec_no()); exitMap.put("inv_code", assRepairRecDetail.getInv_code()); listVo.add(exitMap); } list.add(map); } } if(listVo.size()>0){ assRepairRecDetailMapper.deleteBatchAssRepairRecDetail(listVo); assRepairRecDetailMapper.addBatchAssRepairRecDetail(list); }else if(list.size()>0){ assRepairRecDetailMapper.addBatchAssRepairRecDetail(list); } return "{\"msg\":\"更新成功.\",\"state\":\"true\"}"; } catch (Exception e) { throw new SysException(e); } } /** * @Description * 批量更新tabledesc<BR> * @param entityList * @return String JSON * @throws DataAccessException */ @Override public String updateBatch(List<Map<String,Object>> entityList)throws DataAccessException{ try { assRepairRecMapper.updateBatch(entityList); return "{\"msg\":\"更新成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"删除失败 数据库异常 请联系管理员! 方法 updateBatch\"}"; } } /** * @Description * 删除tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String delete(Map<String, Object> entityMap) throws DataAccessException { try { int state = assRepairRecMapper.delete(entityMap); return "{\"msg\":\"删除成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"删除失败 数据库异常 请联系管理员! 方法 delete\"}"; } } /** * @Description * 批量删除tabledesc<BR> * @param entityList * @return String JSON * @throws DataAccessException */ @Override public String deleteBatch(List<Map<String,Object>> entityList)throws DataAccessException{ try { assRepairRecMapper.deleteBatch(entityList); return "{\"msg\":\"删除成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"删除失败 数据库异常 请联系管理员! 方法 deleteBatch\"}"; } } /** * @Description * 添加tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String addOrUpdate(Map<String,Object> entityMap)throws DataAccessException{ /** * 备注 先判断是否存在 存在即更新不存在则添加<br> * 在判断是否存在时可根据实际情况进行修改传递的参数进行判断<br> * 判断是否名称相同 判断是否 编码相同 等一系列规则 */ //判断是否存在对象tabledesc Map<String, Object> mapVo=new HashMap<String, Object>(); mapVo.put("group_id",entityMap.get("group_id")); mapVo.put("hos_id",entityMap.get("hos_id")); mapVo.put("copy_code", entityMap.get("copy_code")); mapVo.put("acct_year", entityMap.get("acct_year")); List<AssRepairRec> list = (List<AssRepairRec>)assRepairRecMapper.queryExists(mapVo); if (list.size()>0) { int state = assRepairRecMapper.update(entityMap); return "{\"msg\":\"更新成功.\",\"state\":\"true\"}"; } try { int state = assRepairRecMapper.add(entityMap); return "{\"msg\":\"添加成功.\",\"state\":\"true\"}"; } catch (Exception e) { logger.error(e.getMessage(), e); return "{\"error\":\"添加失败 数据库异常 请联系管理员! 方法 addOrUpdate\"}"; } } /** * @Description * 查询结果集tabledesc<BR> * @param entityMap * @return String JSON * @throws DataAccessException */ @Override public String query(Map<String,Object> entityMap) throws DataAccessException{ SysPage sysPage = new SysPage(); sysPage = (SysPage) entityMap.get("sysPage"); if (sysPage.getTotal()==-1){ List<AssRepairRec> list = (List<AssRepairRec>)assRepairRecMapper.query(entityMap); return ChdJson.toJson(list); }else{ RowBounds rowBounds = new RowBounds(sysPage.getPage(), sysPage.getPagesize()); List<AssRepairRec> list = (List<AssRepairRec>)assRepairRecMapper.query(entityMap, rowBounds); PageInfo page = new PageInfo(list); return ChdJson.toJson(list, page.getTotal()); } } /** * @Description * 获取对象tabledesc<BR> * @param entityMap<BR> * 参数为主键 * @return String JSON * @throws DataAccessException */ @Override public <T> T queryByCode(Map<String,Object> entityMap)throws DataAccessException{ return assRepairRecMapper.queryByCode(entityMap); } /** * @Description * 获取tabledesc<BR> * @param entityMap<BR> * 参数为要检索的字段 * @return AssRepairRec * @throws DataAccessException */ @Override public <T> T queryByUniqueness(Map<String,Object> entityMap)throws DataAccessException{ return assRepairRecMapper.queryByUniqueness(entityMap); } /** * @Description * 获取tabledesc<BR> * @param entityMap<BR> * 参数为要检索的字段 * @return List<AssRepairRec> * @throws DataAccessException */ @Override public List<?> queryExists(Map<String,Object> entityMap)throws DataAccessException{ return assRepairRecMapper.queryExists(entityMap); } @Override public String queryAssRepairRecDetail(Map<String, Object> mapVo) { List<AssRepairRecDetail> list =(List<AssRepairRecDetail>) assRepairRecDetailMapper.queryAssRepairRecDetail(mapVo); return ChdJson.toJson(list); } @Override public String deleteAssRepairRecDetail(List<Map<String, Object>> listVo) { try { assRepairRecDetailMapper.deleteBatchAssRepairRecDetail(listVo); return "{\"msg\":\"删除成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } @Override public String auditAssRepairRec(List<Map<String, Object>> mapVo) { try { for (Map<String, Object> map : mapVo) { AssRepairRec assRepairRec=assRepairRecMapper.queryByCode(map); if(assRepairRec.getState()==3){ continue; }else if (assRepairRec.getState()==4){ return "{\"warn\":\"已维修确认维修完成的单据能审核,请重新选择.\",\"state\":\"false\"}"; }else { map.put("audit_emp", SessionManager.getUserId()); assRepairRecMapper.auditAssRepairRec(map); } } return "{\"msg\":\"审核成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } @Override public String backAssRepairRec(List<Map<String, Object>> mapVo) { try { for (Map<String, Object> map : mapVo) { AssRepairRec assRepairRec=assRepairRecMapper.queryByCode(map); if(assRepairRec.getState()==2){ continue; }else if (assRepairRec.getState()!=3){ return "{\"warn\":\"所选择单据存在未审核数据,请核对.\",\"state\":\"false\"}"; }else if (assRepairRec.getState()==4){ return "{\"warn\":\"已维修确认维修完成的单据能撤销审核,请重新选择.\",\"state\":\"false\"}"; }else{ map.put("audit_emp", SessionManager.getUserId()); assRepairRecMapper.backAssRepairRec(map); } } return "{\"msg\":\"消审成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } @Override public String countAssRepairRec(List<Map<String, Object>> mapVo) { try { for (Map<String, Object> map : mapVo) { Map<String,Object> cardMap = new HashMap<String, Object>(); AssRepairRec assRepairRec=assRepairRecMapper.queryByCode(map); if(assRepairRec.getState()!=3){ return "{\"warn\":\"维修确认完成的单据必须为审核状态.\",\"state\":\"false\"}"; }else{ map.put("audit_emp", SessionManager.getUserId()); assRepairRecMapper.countAssRepairRec(map); } cardMap.put("group_id", assRepairRec.getGroup_id()); cardMap.put("hos_id", assRepairRec.getHos_id()); cardMap.put("copy_code", assRepairRec.getCopy_code()); cardMap.put("ass_card_no", assRepairRec.getAss_card_no()); cardMap.put("use_state",4); if(assRepairRec.getAss_nature()!=null){ if("02".equals(assRepairRec.getAss_nature())){ assCardSpecialMapper.updateAssCardStateByRecCardNo(cardMap); }else if("03".equals(assRepairRec.getAss_nature())){ assCardGeneralMapper.updateAssCardStateByRecCardNo(cardMap); }else if("04".equals(assRepairRec.getAss_nature())){ assCardOtherMapper.updateAssCardStateByRecCardNo(cardMap); } else if("01".equals(assRepairRec.getAss_nature())){ assCardHouseMapper.updateAssCardStateByRecCardNo(cardMap); }else if("05".equals(assRepairRec.getAss_nature())){ assCardInassetsMapper.updateAssCardStateByRecCardNo(cardMap); }else if("06".equals(assRepairRec.getAss_nature())){ assCardLandMapper.updateAssCardStateByRecCardNo(cardMap); } } } return "{\"msg\":\"确认成功.\",\"state\":\"true\"}"; } catch (DataAccessException e) { throw new SysException(e); } } /** * 资产维修打印 */ @Override public Map<String,Object> queryAssRepairRecDY(Map<String, Object> map)throws DataAccessException { try{ Map<String,Object> reMap=new HashMap<String,Object>(); WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); AssRepairRecMapper assRepairRecMapper = (AssRepairRecMapper)context.getBean("assRepairRecMapper"); if("1".equals(String.valueOf(map.get("p_num")))){ // 资产维修打印模板主表 List<Map<String,Object>> mainList=assRepairRecMapper.queryaAssRepairRecBatch(map); //资产维修打印模板从表 List<Map<String,Object>> detailList=assRepairRecMapper.queryAssRepairRec_detail(map); reMap.put("main", mainList); reMap.put("detail", detailList); }else{ Map<String,Object> mainList=assRepairRecMapper.querAssRepairRecByPrint(map); //资产维修打印模板从表 List<Map<String,Object>> detailList=assRepairRecMapper.queryAssRepairRec_detail(map); reMap.put("main", mainList); reMap.put("detail", detailList); } return reMap; }catch(Exception e){ logger.error(e.getMessage(),e); throw new SysException(e.getMessage()); } } }
17,232
0.691335
0.688018
581
27.025818
26.008757
116
false
false
0
0
0
0
0
0
2.457831
false
false
2
586a8ff9a30974b770de415bf33eddbb9d751a95
38,044,820,325,583
59924adea24fbdc09e82c7a1a4a26ed32d271a7b
/src/Main.java
9beef2c1ef3cc8989c0190a5d4d384d72ff2695b
[ "Apache-2.0" ]
permissive
AndrewZeitler/Game-Engine
https://github.com/AndrewZeitler/Game-Engine
5ba26e934d0e793c2e40599c7aa1e077a7b73343
65121d03854b9cfe648f6fd974bbdbe97f90f9b8
refs/heads/master
2020-03-24T04:32:04.392000
2018-07-26T15:03:50
2018-07-26T15:03:50
142,456,353
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.*; /** * The main program * This program will allow a user to design their own games using the engine I designed * * Andrew Zeitler * June 21st, 2018 * */ public class Main extends JFrame implements ActionListener{ //The default serial ID for the JFrame private static final long serialVersionUID = 1L; //The UI behaviour object to handle all the UI interations private UIBehaviour uib; //The pane for holding all the script/scene tabs private JTabbedPane pane; //An array of all the pages being held by the JTabbedPane private ArrayList<Page> pages; //The file project location private File project; //The file location of the main scene to be run private File mainScene; /** * The main class for the program to run from */ public Main(){ //Super the constructor for the JFrame super("Culminating"); //Set the size to be the monitors screen size setSize(Toolkit.getDefaultToolkit().getScreenSize()); //Sets the layout to contain the UI nicely setLayout(new BorderLayout()); //Sets the default close operation so that the whole program ends when you close it setDefaultCloseOperation(EXIT_ON_CLOSE); ///Sets the menu bar on the JFrame setJMenuBar(createMenuBar()); //Create the tab pane object and add it to the JFrame pane = new JTabbedPane(); add(pane); //Create the UIBehaviour object uib = new UIBehaviour(this); //Create the arraylist of pages pages = new ArrayList<Page>(); //Get the project file location JOptionPane.showMessageDialog(null, "Please select or create your project file."); //Set the project file project = uib.getFile("Project", null, JFileChooser.DIRECTORIES_ONLY, null, null); //If they clicked cancel, exit the program if(project == null){ System.exit(0); } //Create the project files necessary for the program createFiles(project); //Sets the JFrame to be visible setVisible(true); } /** * Create the files necessary for the project to run if it hasn't been created yet * @param project the project file location */ public void createFiles(File project){ //The scenes folder File scenes = new File(project.toString() + File.separator + "Scenes"); //The scripts folder File scripts = new File(project.toString() + File.separator + "Scripts"); //The resources folder File resources = new File(project.toString() + File.separator + "Resources"); //The executable main class File execMain = new File(project.toString() + File.separator + "ExecutableMain.class"); //If the scenes folder doesn't exist, make it if(!scenes.exists()){ scenes.mkdir(); } //If the scripts folder doesn't exist, make it if(!scripts.exists()){ scripts.mkdir(); } //If the resources folder doesn't exist, make it if(!resources.exists()){ resources.mkdir(); } //Create and compile the executable main file for the user try { //Create the temporary file of executable main as a .java for compilation File tempFile = new File(execMain.getPath().replace(".class", ".java")); //Read the data from the .java version of executable main String data = FileManager.readFile(new File("src" + File.separator + "ExecutableMain.java")); //Write the executable main class with the correct package line to join the other files data = "package com." + project.getName() + ";\n\n" + data; //Write the executable main file to the project directory FileManager.writeToFile(data, tempFile); //Compile the file FileManager.compileFile(tempFile); //Delete the temporary file tempFile.delete(); } catch (IOException e) { e.printStackTrace(); } } /** * Entry point for program * @param args */ public static void main(String[] args) { new Main(); } /** * Creates a tab to hold the script/scene in * @param title the title of the script/scene * @param dir the directory of the script/scene * @return returns the tab after being created */ public Page createTab(String title, File dir){ //Create the page to be added to the pane Page page = new Page(title, dir); //Add the page to the array pages.add(page); //Add the tab and switch to that tab pane.addTab(title, page); pane.setSelectedIndex(pane.getTabCount() - 1); //Return the newly created page return page; } /** * Creates a UI menu bar for the user * @return returns the created menu bar for the UI */ private JMenuBar createMenuBar(){ //Create menu bar JMenuBar mB = new JMenuBar(); //Create the menus JMenu file = new JMenu("File"); JMenu tools = new JMenu("Run"); //Sets the font on each menu file.setFont(new Font("Monospace", Font.PLAIN, 15)); tools.setFont(new Font("Monospace", Font.PLAIN, 15)); //Create all the menu items JMenuItem[] fileItems = {new JMenuItem("Create Scene"), new JMenuItem("Open Scene"), new JMenuItem("New"), new JMenuItem("Open"), new JMenuItem("Save"), new JMenuItem("Save As"), new JMenuItem("Save All"), new JMenuItem("Close Tab"), new JMenuItem("Exit")}; JMenuItem[] toolItems = {new JMenuItem("Run"), new JMenuItem("Main Scene..."), new JMenuItem("Export")}; //Add listeners to each of the menu items so we can respond to their actions //Also add the item to their menu for(JMenuItem item : fileItems){ item.addActionListener(this); file.add(item); } for(JMenuItem item : toolItems){ item.addActionListener(this); tools.add(item); } //Add separators to make the menu look nice file.insertSeparator(2); file.insertSeparator(8); tools.insertSeparator(1); //Add the menus to the menu bar mB.add(file); mB.add(tools); //Set the menu bar to be white mB.setBackground(Color.WHITE); //Return the newly created menu bar return mB; } /** * Gets the page at the given index * @param index the index to get the page from * @return returns the page at the given index */ public Page getText(int index){ return pages.get(index); } /** * Gets the page the user is currently looking at * @return returns the page the user is on */ public Page getCurrentPage(){ //Make sure there are pages open and then return the current open one if(pages.size() > 0){ return pages.get(pane.getSelectedIndex()); } //If nothing is open, return null return null; } /** * Returns true if the page with the given directory is already open * @param dir the directory of the page * @return returns true if the page is found, false otherwise */ public boolean isPage(String dir){ //Check to see if the page is already open for(Page page : pages){ if(page.getDirectory().getAbsolutePath().equals(dir)){ //Return true if it is open return true; } } //Return false if it is not open return false; } /** * Gets the whole project's directory * @return returns the File object of the directory */ public File getProjectDirectory(){ return project; } /** * Overrides actions with desired effect */ public void actionPerformed(ActionEvent e) { //If they click exit if(e.getActionCommand().equals("Exit")){ //Keeps track of any unsaved items int unsaved = 0; //Loop through and find all unsaved pages for(Page page : pages){ if(!page.isSaved()){ unsaved++; } } //If there are some unsaved, let the user know if(unsaved > 0){ int input = JOptionPane.showConfirmDialog(null, "There are some unsaved files. Would you like to continue?", "Are You Sure?", JOptionPane.YES_NO_OPTION); //If they say yes, exit if(input == 0){ System.exit(DISPOSE_ON_CLOSE); } } else { //Exit if there is nothing unsaved System.exit(DISPOSE_ON_CLOSE); } //Close tab } else if(e.getActionCommand().equals("Close Tab")){ uib.closeTab(); //Open scene } else if(e.getActionCommand().equals("Open Scene")){ uib.openScene(); //Create scene } else if(e.getActionCommand().equals("Create Scene")){ uib.newScene(); //Open script } else if(e.getActionCommand().equals("Open")){ uib.openScript(); //Save file }else if(e.getActionCommand().equals("Save")){ uib.save(); //Save the file as } else if(e.getActionCommand().equals("Save As")){ uib.saveAs(); //Save all files } else if(e.getActionCommand().equals("Save All")){ uib.saveAll(); //Create new script } else if(e.getActionCommand().equals("New")){ uib.newScript(); //Run the program } else if(e.getActionCommand().equals("Run")){ uib.run(); //Choose main scene for running } else if(e.getActionCommand().equals("Main Scene...")){ uib.mainScene(); //Export the project } else if(e.getActionCommand().equals("Export")){ uib.export(); } } /** * Gets the main scene the user wants to begin their program from * @return returns the file object of the scene */ public File getMainScene(){ return mainScene; } /** * Sets the main scene the user wants to begin their program from * @param mainScene the File object of the scene to start from */ public void setMainScene(File mainScene){ this.mainScene = mainScene; } /** * Gets the pages open currently * @return returns an ArrayList of the pages currently open */ public ArrayList<Page> getPages(){ return pages; } /** * Get the JTabbedPane object * @return returns the JTabbedPane for main */ public JTabbedPane getTabbedPane(){ return pane; } }
UTF-8
Java
9,981
java
Main.java
Java
[ { "context": "eir own games using the engine I designed\r\n * \r\n * Andrew Zeitler\r\n * June 21st, 2018\r\n *\r\n */\r\npublic class Main e", "end": 425, "score": 0.9996771812438965, "start": 411, "tag": "NAME", "value": "Andrew Zeitler" } ]
null
[]
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.*; /** * The main program * This program will allow a user to design their own games using the engine I designed * * <NAME> * June 21st, 2018 * */ public class Main extends JFrame implements ActionListener{ //The default serial ID for the JFrame private static final long serialVersionUID = 1L; //The UI behaviour object to handle all the UI interations private UIBehaviour uib; //The pane for holding all the script/scene tabs private JTabbedPane pane; //An array of all the pages being held by the JTabbedPane private ArrayList<Page> pages; //The file project location private File project; //The file location of the main scene to be run private File mainScene; /** * The main class for the program to run from */ public Main(){ //Super the constructor for the JFrame super("Culminating"); //Set the size to be the monitors screen size setSize(Toolkit.getDefaultToolkit().getScreenSize()); //Sets the layout to contain the UI nicely setLayout(new BorderLayout()); //Sets the default close operation so that the whole program ends when you close it setDefaultCloseOperation(EXIT_ON_CLOSE); ///Sets the menu bar on the JFrame setJMenuBar(createMenuBar()); //Create the tab pane object and add it to the JFrame pane = new JTabbedPane(); add(pane); //Create the UIBehaviour object uib = new UIBehaviour(this); //Create the arraylist of pages pages = new ArrayList<Page>(); //Get the project file location JOptionPane.showMessageDialog(null, "Please select or create your project file."); //Set the project file project = uib.getFile("Project", null, JFileChooser.DIRECTORIES_ONLY, null, null); //If they clicked cancel, exit the program if(project == null){ System.exit(0); } //Create the project files necessary for the program createFiles(project); //Sets the JFrame to be visible setVisible(true); } /** * Create the files necessary for the project to run if it hasn't been created yet * @param project the project file location */ public void createFiles(File project){ //The scenes folder File scenes = new File(project.toString() + File.separator + "Scenes"); //The scripts folder File scripts = new File(project.toString() + File.separator + "Scripts"); //The resources folder File resources = new File(project.toString() + File.separator + "Resources"); //The executable main class File execMain = new File(project.toString() + File.separator + "ExecutableMain.class"); //If the scenes folder doesn't exist, make it if(!scenes.exists()){ scenes.mkdir(); } //If the scripts folder doesn't exist, make it if(!scripts.exists()){ scripts.mkdir(); } //If the resources folder doesn't exist, make it if(!resources.exists()){ resources.mkdir(); } //Create and compile the executable main file for the user try { //Create the temporary file of executable main as a .java for compilation File tempFile = new File(execMain.getPath().replace(".class", ".java")); //Read the data from the .java version of executable main String data = FileManager.readFile(new File("src" + File.separator + "ExecutableMain.java")); //Write the executable main class with the correct package line to join the other files data = "package com." + project.getName() + ";\n\n" + data; //Write the executable main file to the project directory FileManager.writeToFile(data, tempFile); //Compile the file FileManager.compileFile(tempFile); //Delete the temporary file tempFile.delete(); } catch (IOException e) { e.printStackTrace(); } } /** * Entry point for program * @param args */ public static void main(String[] args) { new Main(); } /** * Creates a tab to hold the script/scene in * @param title the title of the script/scene * @param dir the directory of the script/scene * @return returns the tab after being created */ public Page createTab(String title, File dir){ //Create the page to be added to the pane Page page = new Page(title, dir); //Add the page to the array pages.add(page); //Add the tab and switch to that tab pane.addTab(title, page); pane.setSelectedIndex(pane.getTabCount() - 1); //Return the newly created page return page; } /** * Creates a UI menu bar for the user * @return returns the created menu bar for the UI */ private JMenuBar createMenuBar(){ //Create menu bar JMenuBar mB = new JMenuBar(); //Create the menus JMenu file = new JMenu("File"); JMenu tools = new JMenu("Run"); //Sets the font on each menu file.setFont(new Font("Monospace", Font.PLAIN, 15)); tools.setFont(new Font("Monospace", Font.PLAIN, 15)); //Create all the menu items JMenuItem[] fileItems = {new JMenuItem("Create Scene"), new JMenuItem("Open Scene"), new JMenuItem("New"), new JMenuItem("Open"), new JMenuItem("Save"), new JMenuItem("Save As"), new JMenuItem("Save All"), new JMenuItem("Close Tab"), new JMenuItem("Exit")}; JMenuItem[] toolItems = {new JMenuItem("Run"), new JMenuItem("Main Scene..."), new JMenuItem("Export")}; //Add listeners to each of the menu items so we can respond to their actions //Also add the item to their menu for(JMenuItem item : fileItems){ item.addActionListener(this); file.add(item); } for(JMenuItem item : toolItems){ item.addActionListener(this); tools.add(item); } //Add separators to make the menu look nice file.insertSeparator(2); file.insertSeparator(8); tools.insertSeparator(1); //Add the menus to the menu bar mB.add(file); mB.add(tools); //Set the menu bar to be white mB.setBackground(Color.WHITE); //Return the newly created menu bar return mB; } /** * Gets the page at the given index * @param index the index to get the page from * @return returns the page at the given index */ public Page getText(int index){ return pages.get(index); } /** * Gets the page the user is currently looking at * @return returns the page the user is on */ public Page getCurrentPage(){ //Make sure there are pages open and then return the current open one if(pages.size() > 0){ return pages.get(pane.getSelectedIndex()); } //If nothing is open, return null return null; } /** * Returns true if the page with the given directory is already open * @param dir the directory of the page * @return returns true if the page is found, false otherwise */ public boolean isPage(String dir){ //Check to see if the page is already open for(Page page : pages){ if(page.getDirectory().getAbsolutePath().equals(dir)){ //Return true if it is open return true; } } //Return false if it is not open return false; } /** * Gets the whole project's directory * @return returns the File object of the directory */ public File getProjectDirectory(){ return project; } /** * Overrides actions with desired effect */ public void actionPerformed(ActionEvent e) { //If they click exit if(e.getActionCommand().equals("Exit")){ //Keeps track of any unsaved items int unsaved = 0; //Loop through and find all unsaved pages for(Page page : pages){ if(!page.isSaved()){ unsaved++; } } //If there are some unsaved, let the user know if(unsaved > 0){ int input = JOptionPane.showConfirmDialog(null, "There are some unsaved files. Would you like to continue?", "Are You Sure?", JOptionPane.YES_NO_OPTION); //If they say yes, exit if(input == 0){ System.exit(DISPOSE_ON_CLOSE); } } else { //Exit if there is nothing unsaved System.exit(DISPOSE_ON_CLOSE); } //Close tab } else if(e.getActionCommand().equals("Close Tab")){ uib.closeTab(); //Open scene } else if(e.getActionCommand().equals("Open Scene")){ uib.openScene(); //Create scene } else if(e.getActionCommand().equals("Create Scene")){ uib.newScene(); //Open script } else if(e.getActionCommand().equals("Open")){ uib.openScript(); //Save file }else if(e.getActionCommand().equals("Save")){ uib.save(); //Save the file as } else if(e.getActionCommand().equals("Save As")){ uib.saveAs(); //Save all files } else if(e.getActionCommand().equals("Save All")){ uib.saveAll(); //Create new script } else if(e.getActionCommand().equals("New")){ uib.newScript(); //Run the program } else if(e.getActionCommand().equals("Run")){ uib.run(); //Choose main scene for running } else if(e.getActionCommand().equals("Main Scene...")){ uib.mainScene(); //Export the project } else if(e.getActionCommand().equals("Export")){ uib.export(); } } /** * Gets the main scene the user wants to begin their program from * @return returns the file object of the scene */ public File getMainScene(){ return mainScene; } /** * Sets the main scene the user wants to begin their program from * @param mainScene the File object of the scene to start from */ public void setMainScene(File mainScene){ this.mainScene = mainScene; } /** * Gets the pages open currently * @return returns an ArrayList of the pages currently open */ public ArrayList<Page> getPages(){ return pages; } /** * Get the JTabbedPane object * @return returns the JTabbedPane for main */ public JTabbedPane getTabbedPane(){ return pane; } }
9,973
0.664663
0.662659
329
28.331306
22.698828
112
false
false
0
0
0
0
0
0
2.167173
false
false
2
21d220a4fa2d2dc434b63788563c45a64e166c24
34,840,774,730,972
08c449e932ab055b064eafb5b7f28d73d2a60e6d
/WorkAppServer/src/main/java/com/workapp/workappserver/dataaccess/orm/core/ResultSetIterator.java
67ee6fc51667d2f7340c7a00606f99582983aa3a
[ "Apache-2.0" ]
permissive
sgdheeban/WorkApp
https://github.com/sgdheeban/WorkApp
82cb72f0b398aed1f923cfc87812c272c5fc9205
fada85658e4340d6c9e5c59ff7cc1054680a740a
refs/heads/master
2021-01-14T13:47:24.399000
2016-09-13T02:39:01
2016-09-13T02:39:01
44,852,094
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.workapp.workappserver.dataaccess.orm.core; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import com.workapp.workappserver.common.exception.RuntimeSQLException; /** * Iterator backed by a ResultSet. */ public final class ResultSetIterator implements Iterator { public static final int TYPE_OBJECT = 1; public static final int TYPE_MAP = 2; private final ResultSet resultSet; private final Persist persist; private final Class objectClass; private final int type; private boolean hasNext = false; public ResultSetIterator(final Persist persist, final Class objectClass, final ResultSet resultSet, final int type) { if (type != TYPE_OBJECT && type != TYPE_MAP) { throw new RuntimeSQLException("Invalid ResultSetIterator type: " + type); } this.persist = persist; this.objectClass = objectClass; this.resultSet = resultSet; this.type = type; try { hasNext = resultSet.next(); } catch (SQLException e) { throw new RuntimeSQLException(e); } } public boolean hasNext() { return hasNext; } public Object next() { try { final Object ret; if (type == TYPE_OBJECT) { ret = persist.loadObject(objectClass, resultSet); } else if (type == TYPE_MAP) { ret = Persist.loadMap(resultSet); } else { ret = null; } hasNext = resultSet.next(); return ret; } catch (SQLException e) { throw new RuntimeSQLException(e); } } public void remove() { try { this.resultSet.deleteRow(); } catch (SQLException e) { throw new RuntimeSQLException(e); } } }
UTF-8
Java
1,707
java
ResultSetIterator.java
Java
[]
null
[]
package com.workapp.workappserver.dataaccess.orm.core; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import com.workapp.workappserver.common.exception.RuntimeSQLException; /** * Iterator backed by a ResultSet. */ public final class ResultSetIterator implements Iterator { public static final int TYPE_OBJECT = 1; public static final int TYPE_MAP = 2; private final ResultSet resultSet; private final Persist persist; private final Class objectClass; private final int type; private boolean hasNext = false; public ResultSetIterator(final Persist persist, final Class objectClass, final ResultSet resultSet, final int type) { if (type != TYPE_OBJECT && type != TYPE_MAP) { throw new RuntimeSQLException("Invalid ResultSetIterator type: " + type); } this.persist = persist; this.objectClass = objectClass; this.resultSet = resultSet; this.type = type; try { hasNext = resultSet.next(); } catch (SQLException e) { throw new RuntimeSQLException(e); } } public boolean hasNext() { return hasNext; } public Object next() { try { final Object ret; if (type == TYPE_OBJECT) { ret = persist.loadObject(objectClass, resultSet); } else if (type == TYPE_MAP) { ret = Persist.loadMap(resultSet); } else { ret = null; } hasNext = resultSet.next(); return ret; } catch (SQLException e) { throw new RuntimeSQLException(e); } } public void remove() { try { this.resultSet.deleteRow(); } catch (SQLException e) { throw new RuntimeSQLException(e); } } }
1,707
0.652021
0.650849
88
17.397728
22.497242
124
false
false
0
0
0
0
0
0
1.852273
false
false
2
3da2ff3ca63b9105bc3698d32ce69609c768a27b
37,641,093,402,962
60390974c67eb7f465b7a769de59cbd4fa9e3c05
/src/main/java/com/example/task/service/UserService.java
7ffe311de3e9669311359a8204a8daafd5010be8
[]
no_license
HatemRise/task
https://github.com/HatemRise/task
e93b70cf564664ccb3ab6fc85b091fd410b6aedc
00d734b73d6efce3af117f33bd79829424245076
refs/heads/master
2022-03-01T17:48:44.498000
2019-11-17T02:30:46
2019-11-17T02:30:46
215,370,139
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.task.service; import com.example.task.model.User; import com.example.task.model.UserDTO; import org.springframework.stereotype.Service; import java.util.List; @Service public interface UserService { void save(User user); void save(UserDTO userDTO); boolean changeGuild(String guild, User user); boolean changeGuild(UserDTO userDTO); List<User> findAllByLogin(String login); List<User> findAllByEmail(String email); }
UTF-8
Java
469
java
UserService.java
Java
[]
null
[]
package com.example.task.service; import com.example.task.model.User; import com.example.task.model.UserDTO; import org.springframework.stereotype.Service; import java.util.List; @Service public interface UserService { void save(User user); void save(UserDTO userDTO); boolean changeGuild(String guild, User user); boolean changeGuild(UserDTO userDTO); List<User> findAllByLogin(String login); List<User> findAllByEmail(String email); }
469
0.754797
0.754797
22
20.318182
18.806156
49
false
false
0
0
0
0
0
0
0.545455
false
false
2
76b0346929fc3b8124861abfc0590023502e87cb
37,641,093,403,999
32b2327dd12a7a943f542847020323796b1ce93e
/app/src/main/java/com/example/bonz/uniap_fake/model/SemesterModel.java
514fba3d1ee68de6b65b4d110ffe51678fda0b4e
[]
no_license
Tuanna1906/uniap_fake
https://github.com/Tuanna1906/uniap_fake
dfb155de9d680faab3fa726249dbe4bfbd324189
dac26c93918071b7667895eedaf445ee157281b2
refs/heads/master
2019-07-25T16:57:31.763000
2017-03-18T10:17:18
2017-03-18T10:17:18
85,215,605
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.bonz.uniap_fake.model; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by HuongNTM5 on 3/15/2017. */ public class SemesterModel extends RealmObject { @PrimaryKey private int id; private String semesterName; private String startDate; private String endDate; public static SemesterModel create(int id, String semesterName, String startDate, String endDate) { SemesterModel semesterModel = new SemesterModel(); semesterModel.id = id; semesterModel.semesterName = semesterName; semesterModel.startDate = startDate; semesterModel.endDate = endDate; return semesterModel; } public void setId(int id) { this.id = id; } public void setSemesterName(String semesterName) { this.semesterName = semesterName; } public void setStartDate(String startDate) { this.startDate = startDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public int getId() { return id; } public String getSemesterName() { return semesterName; } public String getStartDate() { return startDate; } public String getEndDate() { return endDate; } }
UTF-8
Java
1,305
java
SemesterModel.java
Java
[ { "context": "o.realm.annotations.PrimaryKey;\n\n/**\n * Created by HuongNTM5 on 3/15/2017.\n */\n\npublic class SemesterModel ext", "end": 141, "score": 0.9996681213378906, "start": 132, "tag": "USERNAME", "value": "HuongNTM5" } ]
null
[]
package com.example.bonz.uniap_fake.model; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by HuongNTM5 on 3/15/2017. */ public class SemesterModel extends RealmObject { @PrimaryKey private int id; private String semesterName; private String startDate; private String endDate; public static SemesterModel create(int id, String semesterName, String startDate, String endDate) { SemesterModel semesterModel = new SemesterModel(); semesterModel.id = id; semesterModel.semesterName = semesterName; semesterModel.startDate = startDate; semesterModel.endDate = endDate; return semesterModel; } public void setId(int id) { this.id = id; } public void setSemesterName(String semesterName) { this.semesterName = semesterName; } public void setStartDate(String startDate) { this.startDate = startDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public int getId() { return id; } public String getSemesterName() { return semesterName; } public String getStartDate() { return startDate; } public String getEndDate() { return endDate; } }
1,305
0.655939
0.649808
57
21.894737
20.691284
103
false
false
0
0
0
0
0
0
0.421053
false
false
2
87392d3b83a56f68b4ca81963d5d9f684335447a
35,966,056,167,117
c8688db388a2c5ac494447bac90d44b34fa4132c
/sources/com/google/android/gms/internal/ads/zzcjg.java
9760f94271efa6f70f742969eb69ebf41413692a
[]
no_license
mred312/apk-source
https://github.com/mred312/apk-source
98dacfda41848e508a0c9db2c395fec1ae33afa1
d3ca7c46cb8bf701703468ddc88f25ba4fb9d975
refs/heads/master
2023-03-06T05:53:50.863000
2021-02-23T13:34:20
2021-02-23T13:34:20
341,481,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.internal.ads; import com.google.android.gms.internal.ads.zztu; /* compiled from: com.google.android.gms:play-services-ads@@19.5.0 */ public final class zzcjg implements zzepf<zzckc> { public static zzcjg zzapo() { return C2104kk.f9768a; } public final /* synthetic */ Object get() { return (zzckc) zzepl.zza(new zzckc(zztu.zza.C3991zza.REQUEST_WILL_UPDATE_SIGNALS, zztu.zza.C3991zza.REQUEST_DID_UPDATE_SIGNALS, zztu.zza.C3991zza.REQUEST_FAILED_TO_UPDATE_SIGNALS), "Cannot return null from a non-@Nullable @Provides method"); } }
UTF-8
Java
595
java
zzcjg.java
Java
[]
null
[]
package com.google.android.gms.internal.ads; import com.google.android.gms.internal.ads.zztu; /* compiled from: com.google.android.gms:play-services-ads@@19.5.0 */ public final class zzcjg implements zzepf<zzckc> { public static zzcjg zzapo() { return C2104kk.f9768a; } public final /* synthetic */ Object get() { return (zzckc) zzepl.zza(new zzckc(zztu.zza.C3991zza.REQUEST_WILL_UPDATE_SIGNALS, zztu.zza.C3991zza.REQUEST_DID_UPDATE_SIGNALS, zztu.zza.C3991zza.REQUEST_FAILED_TO_UPDATE_SIGNALS), "Cannot return null from a non-@Nullable @Provides method"); } }
595
0.72437
0.684034
14
41.5
61.898247
249
false
false
0
0
0
0
0
0
0.5
false
false
2
e27ff8d525766fd14f3ee56f4061e5589d7ea132
2,276,332,680,590
899d1c53f33378e3f6354bbc3b64f675b1bdfd4d
/Chapter6Strings/src/com/test/Test21.java
86d56b14489eab9ae8047f37bd6098c3423c20ad
[]
no_license
coolshree4u/testpythonlantesting
https://github.com/coolshree4u/testpythonlantesting
f43ce058b1405e47174a6d85460345090adf81d2
e81ddcb342133bf59bd2a6157df12802da2730ed
refs/heads/master
2021-01-01T18:18:53.972000
2017-07-25T11:17:53
2017-07-25T11:17:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test; public class Test21 { public static void main(String[] args) { // TODO Auto-generated method stub String name="spot"; int age=4; String str="My dog "+name+" is "+age; System.out.println(str); StringBuffer sb=new StringBuffer(); sb.append("My dog "+name+" is "+age); System.out.println(sb); /*sb.insert(1,"My dog ").append(name+" is "+age); System.out.println(sb);*/ } }
UTF-8
Java
417
java
Test21.java
Java
[]
null
[]
package com.test; public class Test21 { public static void main(String[] args) { // TODO Auto-generated method stub String name="spot"; int age=4; String str="My dog "+name+" is "+age; System.out.println(str); StringBuffer sb=new StringBuffer(); sb.append("My dog "+name+" is "+age); System.out.println(sb); /*sb.insert(1,"My dog ").append(name+" is "+age); System.out.println(sb);*/ } }
417
0.640288
0.630695
19
21
16.170149
51
false
false
0
0
0
0
0
0
1.947368
false
false
2
9a73d4980036b21d022788005ff6f787e405d7fb
17,549,236,383,792
c625fa9fcf8433fe7006626e32ff5c87de99d22e
/sipivr.web/src/main/java/ru/sipivr/web/interceptor/ControllerInterceptor.java
0c6167b1a61dc2ab696295512c215deef0120b52
[ "MIT" ]
permissive
Jenner4S/sipivr
https://github.com/Jenner4S/sipivr
9b9b7f3cd5a4d22a44bcfcecf77a9001a72799fe
0292d1804e5ae9e0432562b6874d172367838426
refs/heads/master
2020-04-30T01:55:07.874000
2018-11-13T21:46:24
2018-11-13T21:46:24
176,543,440
0
1
MIT
true
2019-03-19T15:29:17
2019-03-19T15:29:17
2018-11-13T21:47:26
2018-11-13T21:46:25
10,663
0
0
0
null
false
null
package ru.sipivr.web.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import ru.sipivr.core.service.PluginService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by Karpukhin on 02.01.2016. */ public class ControllerInterceptor implements HandlerInterceptor { private static Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class); @Autowired private PluginService pluginService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.trace("pre [{}] {} {}", request.getRemoteAddr(), request.getRequestURL(), request.getQueryString()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if(modelAndView != null) { modelAndView.getModel().put("pluginService", pluginService); } logger.trace("post [{}] {} {}", request.getRemoteAddr(), request.getRequestURL(), request.getQueryString()); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.trace("after [{}] {} {}", request.getRemoteAddr(), request.getRequestURL(), request.getQueryString()); } }
UTF-8
Java
1,632
java
ControllerInterceptor.java
Java
[ { "context": "rvlet.http.HttpServletResponse;\n\n/**\n * Created by Karpukhin on 02.01.2016.\n */\npublic class ControllerInterce", "end": 435, "score": 0.9402519464492798, "start": 426, "tag": "NAME", "value": "Karpukhin" } ]
null
[]
package ru.sipivr.web.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import ru.sipivr.core.service.PluginService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by Karpukhin on 02.01.2016. */ public class ControllerInterceptor implements HandlerInterceptor { private static Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class); @Autowired private PluginService pluginService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.trace("pre [{}] {} {}", request.getRemoteAddr(), request.getRequestURL(), request.getQueryString()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if(modelAndView != null) { modelAndView.getModel().put("pluginService", pluginService); } logger.trace("post [{}] {} {}", request.getRemoteAddr(), request.getRequestURL(), request.getQueryString()); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.trace("after [{}] {} {}", request.getRemoteAddr(), request.getRequestURL(), request.getQueryString()); } }
1,632
0.748775
0.742647
41
38.829269
42.80751
146
false
false
0
0
0
0
0
0
0.829268
false
false
2
3ca630cdbcc8fda93ebc8e752ba5596ccc9abdcd
15,109,694,958,014
17449995e74129b3b657f008b769320038d6fe70
/src/test/java/com/bonyeon/tdd/ch02/PasswordStrength.java
38b3144bdc528b357afe3ac15e641a282368c39c
[]
no_license
bonyeon0605/java_tdd
https://github.com/bonyeon0605/java_tdd
6ef5fca4f02a1466e1e88bf79f38373a949749bb
620b37855754dbf3bb6a6b4304a17cf1eb28bb50
refs/heads/master
2023-04-19T05:31:37.703000
2021-05-04T11:43:58
2021-05-04T11:43:58
363,667,521
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bonyeon.tdd.ch02; public enum PasswordStrength { STRONG, INVALID, WEAK, NORMAL }
UTF-8
Java
98
java
PasswordStrength.java
Java
[]
null
[]
package com.bonyeon.tdd.ch02; public enum PasswordStrength { STRONG, INVALID, WEAK, NORMAL }
98
0.744898
0.72449
5
18.6
14.840486
33
false
false
0
0
0
0
0
0
0.8
false
false
2
16cf58c398b788231476abff6d497d7d498a2a99
2,010,044,708,978
8c3869b8977a493728597f51b2c3cdc8a7ea1f89
/lib/antlr-3.0.1/src/org/antlr/test/TestAttributes.java
8f47c071f19938a261e6e7be7407a8bd3b6c2541
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
Sable/mclab-core
https://github.com/Sable/mclab-core
4fc9fdeae81fe6cc4f9cf0eeab67e7adf30882f2
beeea16c1c79b3005f3c46363b8c49d1928a937b
refs/heads/master
2021-01-17T01:40:32.341000
2019-11-06T05:08:43
2019-11-06T05:08:43
33,200,144
12
14
Apache-2.0
false
2019-11-06T05:08:44
2015-03-31T17:41:17
2019-10-21T02:44:04
2019-11-06T05:08:44
48,599
6
10
9
Java
false
false
/* [The "BSD licence"] Copyright (c) 2005-2006 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.test; import org.antlr.Tool; import org.antlr.codegen.CodeGenerator; import org.antlr.codegen.ActionTranslatorLexer; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import org.antlr.tool.*; import java.io.StringReader; import java.util.List; import java.util.ArrayList; /** Check the $x, $x.y attributes. For checking the actual * translation, assume the Java target. This is still a great test * for the semantics of the $x.y stuff regardless of the target. */ public class TestAttributes extends BaseTest { /** Public default constructor used by TestRig */ public TestAttributes() { } public void testEscapedLessThanInAction() throws Exception { Grammar g = new Grammar(); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); String action = "i<3; '<xmltag>'"; ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),0); String expecting = action; String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, "<action>"); actionST.setAttribute("action", rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testEscaped$InAction() throws Exception { String action = "int \\$n; \"\\$in string\\$\""; String expecting = "int $n; \"$in string$\""; Grammar g = new Grammar( "parser grammar t;\n"+ "@members {"+action+"}\n"+ "a[User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testArguments() throws Exception { String action = "$i; $i.x; $u; $u.x"; String expecting = "i; i.x; u; u.x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } /** $x.start refs are checked during translation not before so ANTLR misses the fact that rule r has refs to predefined attributes if the ref is after the def of the method or self-referential. Actually would be ok if I didn't convert actions to strings; keep as templates. June 9, 2006: made action translation leave templates not strings */ public void testRefToReturnValueBeforeRefToPredefinedAttr() throws Exception { String action = "$x.foo"; String expecting = "x.foo"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : x=b {"+action+"} ;\n" + "b returns [int foo] : B {$b.start} ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelBeforeRefToPredefinedAttr() throws Exception { // As of Mar 2007, I'm removing unused labels. Unfortunately, // the action is not seen until code gen. Can't see $x.text // before stripping unused labels. We really need to translate // actions first so code gen logic can use info. String action = "$x.text"; String expecting = "input.toString(x.start,x.stop)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : x=b {"+action+"} ;\n" + "b : B ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testInvalidArguments() throws Exception { String action = "$x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testReturnValue() throws Exception { String action = "$x.i"; String expecting = "x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i]\n" + " : 'a'\n" + " ;\n" + "b : x=a {"+action+"} ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReturnValueWithNumber() throws Exception { String action = "$x.i1"; String expecting = "x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i1]\n" + " : 'a'\n" + " ;\n" + "b : x=a {"+action+"} ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReturnValues() throws Exception { String action = "$i; $i.x; $u; $u.x"; String expecting = "retval.i; retval.i.x; retval.u; retval.u.x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } /* regression test for ANTLR-46 */ public void testReturnWithMultipleRuleRefs() throws Exception { String action1 = "$obj = $rule2.obj;"; String action2 = "$obj = $rule3.obj;"; String expecting1 = "obj = rule21;"; String expecting2 = "obj = rule32;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "rule1 returns [ Object obj ]\n" + ": rule2 { "+action1+" }\n" + "| rule3 { "+action2+" }\n" + ";\n"+ "rule2 returns [ Object obj ]\n"+ ": foo='foo' { $obj = $foo.text; }\n"+ ";\n"+ "rule3 returns [ Object obj ]\n"+ ": bar='bar' { $obj = $bar.text; }\n"+ ";"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int i = 0; String action = action1; String expecting = expecting1; do { ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"rule1", new antlr.CommonToken(ANTLRParser.ACTION,action),i+1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); action = action2; expecting = expecting2; } while (i++ < 1); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testInvalidReturnValues() throws Exception { String action = "$x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testTokenLabels() throws Exception { String action = "$id; $f; $id.text; $id.getText(); $id.dork " + "$id.type; $id.line; $id.pos; " + "$id.channel; $id.index;"; String expecting = "id; f; id.getText(); id.getText(); id.dork " + "id.getType(); id.getLine(); id.getCharPositionInLine(); " + "id.getChannel(); id.getTokenIndex();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : id=ID f=FLOAT {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabels() throws Exception { String action = "$r.x; $r.start; $r.stop; $r.tree; $a.x; $a.stop;"; String expecting = "r.x; ((Token)r.start); ((Token)r.stop); ((Object)r.tree); r.x; ((Token)r.stop);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelsWithSpecialToken() throws Exception { String action = "$r.x; $r.start; $r.stop; $r.tree; $a.x; $a.stop;"; String expecting = "r.x; ((MYTOKEN)r.start); ((MYTOKEN)r.stop); ((Object)r.tree); r.x; ((MYTOKEN)r.stop);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "options {TokenLabelType=MYTOKEN;}\n"+ "a returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testForwardRefRuleLabels() throws Exception { String action = "$r.x; $r.start; $r.stop; $r.tree; $a.x; $a.tree;"; String expecting = "r.x; ((Token)r.start); ((Token)r.stop); ((Object)r.tree); r.x; ((Object)r.tree);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;\n" + "a returns [int x]\n" + " : ;\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testInvalidRuleLabelAccessesParameter() throws Exception { String action = "$r.z"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[int z] returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_INVALID_RULE_PARAMETER_REF; Object expectedArg = "a"; Object expectedArg2 = "z"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testInvalidRuleLabelAccessesScopeAttribute() throws Exception { String action = "$r.n"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a\n" + "scope { int n; }\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_INVALID_RULE_SCOPE_ATTRIBUTE_REF; Object expectedArg = "a"; Object expectedArg2 = "n"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testInvalidRuleAttribute() throws Exception { String action = "$r.blort"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[int z] returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_RULE_ATTRIBUTE; Object expectedArg = "a"; Object expectedArg2 = "blort"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testMissingRuleAttribute() throws Exception { String action = "$r"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[int z] returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "r"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testMissingUnlabeledRuleAttribute() throws Exception { String action = "$a"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [int x]:\n" + " ;\n"+ "b : a {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "a"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testNonDynamicAttributeOutsideRule() throws Exception { String action = "public void foo() { $x; }"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "@members {'+action+'}\n" + "a : ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, null, new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_ATTRIBUTE_REF_NOT_IN_RULE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testNonDynamicAttributeOutsideRule2() throws Exception { String action = "public void foo() { $x.y; }"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "@members {'+action+'}\n" + "a : ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, null, new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_ATTRIBUTE_REF_NOT_IN_RULE; Object expectedArg = "x"; Object expectedArg2 = "y"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } // D Y N A M I C A L L Y S C O P E D A T T R I B U T E S public void testBasicGlobalScope() throws Exception { String action = "$Symbols::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.peek()).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testUnknownGlobalScope() throws Exception { String action = "$Symbols::names.add($id.text);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); assertEquals("unexpected errors: "+equeue, 2, equeue.errors.size()); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE; Object expectedArg = "Symbols"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testIndexedGlobalScope() throws Exception { String action = "$Symbols[-1]::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.elementAt(Symbols_stack.size()-1-1)).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void test0IndexedGlobalScope() throws Exception { String action = "$Symbols[0]::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.elementAt(0)).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testAbsoluteIndexedGlobalScope() throws Exception { String action = "$Symbols[3]::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.elementAt(3)).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testScopeAndAttributeWithUnderscore() throws Exception { String action = "$foo_bar::a_b;"; String expecting = "((foo_bar_scope)foo_bar_stack.peek()).a_b;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope foo_bar {\n" + " int a_b;\n" + "}\n" + "a scope foo_bar; : (ID {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testSharedGlobalScope() throws Exception { String action = "$Symbols::x;"; String expecting = "((Symbols_scope)Symbols_stack.peek()).x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " String x;\n" + "}\n" + "a\n"+ "scope { int y; }\n"+ "scope Symbols;\n" + " : b {"+action+"}\n" + " ;\n" + "b : ID {$Symbols::x=$ID.text} ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testGlobalScopeOutsideRule() throws Exception { String action = "public void foo() {$Symbols::names.add('foo');}"; String expecting = "public void foo() {((Symbols_scope)Symbols_stack.peek()).names.add('foo');}"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "@members {'+action+'}\n" + "a : \n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleScopeOutsideRule() throws Exception { String action = "public void foo() {$a::name;}"; String expecting = "public void foo() {((a_scope)a_stack.peek()).name;}"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "@members {"+action+"}\n" + "a\n" + "scope { int name; }\n" + " : {foo();}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, null, new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testBasicRuleScope() throws Exception { String action = "$a::n;"; String expecting = "((a_scope)a_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testUnqualifiedRuleScopeAccessInsideRule() throws Exception { String action = "$n;"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_ATTRIBUTE; Object expectedArg = "n"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIsolatedDynamicRuleScopeRef() throws Exception { String action = "$a;"; // refers to stack not top of stack String expecting = "a_stack;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b ;\n" + "b : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testDynamicRuleScopeRefInSubrule() throws Exception { String action = "$a::n;"; String expecting = "((a_scope)a_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b ;\n" + "b : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testIsolatedGlobalScopeRef() throws Exception { String action = "$Symbols;"; String expecting = "Symbols_stack;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " String x;\n" + "}\n" + "a\n"+ "scope { int y; }\n"+ "scope Symbols;\n" + " : b {"+action+"}\n" + " ;\n" + "b : ID {$Symbols::x=$ID.text} ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleScopeFromAnotherRule() throws Exception { String action = "$a::n;"; // must be qualified String expecting = "((a_scope)a_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b\n" + " ;\n" + "b : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testFullyQualifiedRefToCurrentRuleParameter() throws Exception { String action = "$a.i;"; String expecting = "i;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a[int i]: {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testFullyQualifiedRefToCurrentRuleRetVal() throws Exception { String action = "$a.i;"; String expecting = "retval.i;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i, int j]: {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testSetFullyQualifiedRefToCurrentRuleRetVal() throws Exception { String action = "$a.i = 1;"; String expecting = "retval.i = 1;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i, int j]: {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testIsolatedRefToCurrentRule() throws Exception { String action = "$a;"; String expecting = ""; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : 'a' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "a"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIsolatedRefToRule() throws Exception { String action = "$x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x=b {"+action+"}\n" + " ;\n" + "b : 'b' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } /* I think these have to be errors $a.x makes no sense. public void testFullyQualifiedRefToLabelInCurrentRule() throws Exception { String action = "$a.x;"; String expecting = "x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x='a' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testFullyQualifiedRefToListLabelInCurrentRule() throws Exception { String action = "$a.x;"; // must be qualified String expecting = "list_x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x+='a' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } */ public void testFullyQualifiedRefToTemplateAttributeInCurrentRule() throws Exception { String action = "$a.st;"; // can be qualified String expecting = "retval.st;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "options {output=template;}\n"+ "a : (A->{$A.text}) {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleRefWhenRuleHasScope() throws Exception { String action = "$b.start;"; String expecting = "((Token)b1.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "a : b {###"+action+"!!!} ;\n" + "b\n" + "scope {\n" + " int n;\n" + "} : 'b' \n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testDynamicScopeRefOkEvenThoughRuleRefExists() throws Exception { String action = "$b::n;"; String expecting = "((b_scope)b_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "s : b ;\n"+ "b\n" + "scope {\n" + " int n;\n" + "} : '(' b ')' {"+action+"}\n" + // refers to current invocation's n " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToTemplateAttributeForCurrentRule() throws Exception { String action = "$st=null;"; String expecting = "retval.st =null;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "options {output=template;}\n"+ "a : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToTextAttributeForCurrentRule() throws Exception { String action = "$text"; String expecting = "input.toString(retval.start,input.LT(-1))"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "options {output=template;}\n"+ "a : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToStartAttributeForCurrentRule() throws Exception { String action = "$start;"; String expecting = "((Token)retval.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "a : {###"+action+"!!!}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testTokenLabelFromMultipleAlts() throws Exception { String action = "$ID.text;"; // must be qualified String action2 = "$INT.text;"; // must be qualified String expecting = "ID1.getText();"; String expecting2 = "INT2.getText();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID {"+action+"}\n" + " | INT {"+action2+"}\n" + " ;\n" + "ID : 'a';\n" + "INT : '0';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action2),2); rawTranslation = translator.translate(); templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); actionST = new StringTemplate(templates, rawTranslation); found = actionST.toString(); assertEquals(expecting2, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelFromMultipleAlts() throws Exception { String action = "$b.text;"; // must be qualified String action2 = "$c.text;"; // must be qualified String expecting = "input.toString(b1.start,b1.stop);"; String expecting2 = "input.toString(c2.start,c2.stop);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : b {"+action+"}\n" + " | c {"+action2+"}\n" + " ;\n" + "b : 'a';\n" + "c : '0';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action2),2); rawTranslation = translator.translate(); templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); actionST = new StringTemplate(templates, rawTranslation); found = actionST.toString(); assertEquals(expecting2, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testUnknownDynamicAttribute() throws Exception { String action = "$a::x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE_ATTRIBUTE; Object expectedArg = "a"; Object expectedArg2 = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testUnknownGlobalDynamicAttribute() throws Exception { String action = "$Symbols::x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + "}\n" + "a : {'+action+'}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE_ATTRIBUTE; Object expectedArg = "Symbols"; Object expectedArg2 = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testUnqualifiedRuleScopeAttribute() throws Exception { String action = "$n;"; // must be qualified String expecting = "$n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b\n" + " ;\n" + "b : {'+action+'}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; Object expectedArg = "n"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testRuleAndTokenLabelTypeMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : id='foo' id=b\n" + " ;\n" + "b : ;\n"); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; Object expectedArg = "id"; Object expectedArg2 = "rule!=token"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testListAndTokenLabelTypeMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+='a' ids='b'\n" + " ;\n" + "b : ;\n"); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; Object expectedArg = "ids"; Object expectedArg2 = "token!=token-list"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testListAndRuleLabelTypeMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "options {output=AST;}\n"+ "a : bs+=b bs=b\n" + " ;\n" + "b : 'b';\n"); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; Object expectedArg = "bs"; Object expectedArg2 = "rule!=rule-list"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgReturnValueMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a[int i] returns [int x, int i]\n" + " : \n" + " ;\n" + "b : ;\n"); int expectedMsgID = ErrorManager.MSG_ARG_RETVAL_CONFLICT; Object expectedArg = "i"; Object expectedArg2 = "a"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testSimplePlusEqualLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : ids+=ID ( COMMA ids+=ID {"+action+"})* ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testPlusEqualStringLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+='if' ( ',' ids+=ID {"+action+"})* ;" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testPlusEqualSetLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+=('a'|'b') ( ',' ids+=ID {"+action+"})* ;" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testPlusEqualWildcardLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+=. ( ',' ids+=ID {"+action+"})* ;" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testImplicitTokenLabel() throws Exception { String action = "$ID; $ID.text; $ID.getText()"; String expecting = "ID1; ID1.getText(); ID1.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testImplicitRuleLabel() throws Exception { String action = "$r.start;"; String expecting = "((Token)r1.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r {###"+action+"!!!} ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingLabelWithImplicitRuleLabel() throws Exception { String action = "$r.start;"; String expecting = "((Token)x.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x=r {###"+action+"!!!} ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingListLabelWithImplicitRuleLabel() throws Exception { String action = "$r.start;"; String expecting = "((Token)x.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "options {output=AST;}\n" + "a : x+=r {###"+action+"!!!} ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingLabelWithImplicitTokenLabel() throws Exception { String action = "$ID.text;"; String expecting = "x.getText();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x=ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingListLabelWithImplicitTokenLabel() throws Exception { String action = "$ID.text;"; String expecting = "x.getText();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x+=ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelWithoutOutputOption() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar T;\n"+ "s : x+=a ;" + "a : 'a';\n"+ "b : 'b';\n"+ "WS : ' '|'\n';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_LIST_LABEL_INVALID_UNLESS_RETVAL_STRUCT; Object expectedArg = "x"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testRuleLabelOnTwoDifferentRulesAST() throws Exception { String grammar = "grammar T;\n"+ "options {output=AST;}\n"+ "s : x+=a x+=b {System.out.println($x);} ;" + "a : 'a';\n"+ "b : 'b';\n"+ "WS : (' '|'\n') {skip();};\n"; String expecting = "[a, b]\na b\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "a b", false); assertEquals(expecting, found); } public void testRuleLabelOnTwoDifferentRulesTemplate() throws Exception { String grammar = "grammar T;\n"+ "options {output=template;}\n"+ "s : x+=a x+=b {System.out.println($x);} ;" + "a : 'a' -> {%{\"hi\"}} ;\n"+ "b : 'b' -> {%{\"mom\"}} ;\n"+ "WS : (' '|'\n') {skip();};\n"; String expecting = "[hi, mom]\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "a b", false); assertEquals(expecting, found); } public void testMissingArgs() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;" + "r[int i] : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; Object expectedArg = "r"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgsWhenNoneDefined() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r[32,34] ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; Object expectedArg = "r"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testReturnInitValue() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;\n" + "r returns [int x=0] : 'a' {$x = 4;} ;\n"); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); Rule r = g.getRule("r"); AttributeScope retScope = r.returnScope; List parameters = retScope.getAttributes(); assertNotNull("missing return action", parameters); assertEquals(1, parameters.size()); String found = parameters.get(0).toString(); String expecting = "int x=0"; assertEquals(expecting, found); } public void testMultipleReturnInitValue() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;\n" + "r returns [int x=0, int y, String s=new String(\"foo\")] : 'a' {$x = 4;} ;\n"); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); Rule r = g.getRule("r"); AttributeScope retScope = r.returnScope; List parameters = retScope.getAttributes(); assertNotNull("missing return action", parameters); assertEquals(3, parameters.size()); assertEquals("int x=0", parameters.get(0).toString()); assertEquals("int y", parameters.get(1).toString()); assertEquals("String s=new String(\"foo\")", parameters.get(2).toString()); } public void testCStyleReturnInitValue() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;\n" + "r returns [int (*x)()=NULL] : 'a' ;\n"); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); Rule r = g.getRule("r"); AttributeScope retScope = r.returnScope; List parameters = retScope.getAttributes(); assertNotNull("missing return action", parameters); assertEquals(1, parameters.size()); String found = parameters.get(0).toString(); String expecting = "int (*)() x=NULL"; assertEquals(expecting, found); } public void testArgsWithInitValues() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r[32,34] ;" + "r[int x, int y=3] : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_ARG_INIT_VALUES_ILLEGAL; Object expectedArg = "y"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgsOnToken() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID[32,34] ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_ARGS_ON_TOKEN_REF; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgsOnTokenInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' ID[32,34] ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testLabelOnRuleRefInLexer() throws Exception { String action = "$i.text"; String expecting = "i.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' i=ID {"+action+"};" + "fragment ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToRuleRefInLexer() throws Exception { String action = "$ID.text"; String expecting = "ID1.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToRuleRefInLexerNoAttribute() throws Exception { String action = "$ID"; String expecting = "ID1"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testCharLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x='z' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testCharListLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x+='z' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testWildcardCharLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x=. ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testWildcardCharListLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x+=. ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testMissingArgsInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "A : R ;" + "R[int i] : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; Object expectedArg = "R"; Object expectedArg2 = null; // getting a second error @1:12, probably from nextToken GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testLexerRulePropertyRefs() throws Exception { String action = "$text $type $line $pos $channel $index $start $stop"; String expecting = "getText() _type tokenStartLine tokenStartCharPositionInLine channel -1 tokenStartCharIndex (getCharIndex()-1)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'r' {"+action+"};\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testLexerLabelRefs() throws Exception { String action = "$a $b.text $c $d.text"; String expecting = "a b.getText() c d.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : a='c' b='hi' c=. d=DUH {"+action+"};\n" + "DUH : 'd' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testSettingLexerRulePropertyRefs() throws Exception { String action = "$text $type=1 $line=1 $pos=1 $channel=1 $index"; String expecting = "getText() _type=1 tokenStartLine=1 tokenStartCharPositionInLine=1 channel=1 -1"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'r' {"+action+"};\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testArgsOnTokenInLexerRuleOfCombined() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : R;\n" + "R : 'z' ID[32] ;\n" + "ID : 'a';\n"); String lexerGrammarStr = g.getLexerGrammar(); StringReader sr = new StringReader(lexerGrammarStr); Grammar lexerGrammar = new Grammar(); lexerGrammar.setFileName("<internally-generated-lexer>"); lexerGrammar.importTokenVocabulary(g); lexerGrammar.setGrammarContent(sr); sr.close(); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, lexerGrammar, "Java"); lexerGrammar.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, lexerGrammar, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testMissingArgsOnTokenInLexerRuleOfCombined() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : R;\n" + "R : 'z' ID ;\n" + "ID[int i] : 'a';\n"); String lexerGrammarStr = g.getLexerGrammar(); StringReader sr = new StringReader(lexerGrammarStr); Grammar lexerGrammar = new Grammar(); lexerGrammar.setFileName("<internally-generated-lexer>"); lexerGrammar.importTokenVocabulary(g); lexerGrammar.setGrammarContent(sr); sr.close(); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, lexerGrammar, "Java"); lexerGrammar.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, lexerGrammar, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } // T R E E S public void testTokenLabelTreeProperty() throws Exception { String action = "$id.tree;"; String expecting = "id_tree;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : id=ID {"+action+"} ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testTokenRefTreeProperty() throws Exception { String action = "$ID.tree;"; String expecting = "ID1_tree;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testAmbiguousTokenRef() throws Exception { String action = "$ID;"; String expecting = ""; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_NONUNIQUE_REF; Object expectedArg = "ID"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testAmbiguousTokenRefWithProp() throws Exception { String action = "$ID.text;"; String expecting = ""; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_NONUNIQUE_REF; Object expectedArg = "ID"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testRuleRefWithDynamicScope() throws Exception { String action = "$field::x = $field.st;"; String expecting = "((field_scope)field_stack.peek()).x = retval.st;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "field\n" + "scope { StringTemplate x; }\n" + " : 'y' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "field", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testAssignToOwnRulenameAttr() throws Exception { String action = "$rule.tree = null;"; String expecting = "retval.tree = null;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testAssignToOwnParamAttr() throws Exception { String action = "$rule.i = 42; $i = 23;"; String expecting = "i = 42; i = 23;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule[int i]\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testIllegalAssignToOwnRulenameAttr() throws Exception { String action = "$rule.stop = 0;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; Object expectedArg = "rule"; Object expectedArg2 = "stop"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIllegalAssignToLocalAttr() throws Exception { String action = "$tree = null; $st = null; $start = 0; $stop = 0; $text = 0;"; String expecting = "retval.tree = null; retval.st = null; "; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; ArrayList expectedErrors = new ArrayList(3); GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, "start", ""); expectedErrors.add(expectedMessage); GrammarSemanticsMessage expectedMessage2 = new GrammarSemanticsMessage(expectedMsgID, g, null, "stop", ""); expectedErrors.add(expectedMessage2); GrammarSemanticsMessage expectedMessage3 = new GrammarSemanticsMessage(expectedMsgID, g, null, "text", ""); expectedErrors.add(expectedMessage3); checkErrors(equeue, expectedErrors); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testIllegalAssignRuleRefAttr() throws Exception { String action = "$other.tree = null;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "options { output = AST;}" + "otherrule\n" + " : 'y' ;" + "rule\n" + " : other=otherrule {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; Object expectedArg = "other"; Object expectedArg2 = "tree"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIllegalAssignTokenRefAttr() throws Exception { String action = "$ID.text = \"test\";"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "ID\n" + " : 'y' ;" + "rule\n" + " : ID {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; Object expectedArg = "ID"; Object expectedArg2 = "text"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testAssignToTreeNodeAttribute() throws Exception { String action = "$tree.scope = localScope;"; String expecting = "(()retval.tree).scope = localScope;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "options { output=AST; }" + "rule\n" + "@init {\n" + " Scope localScope=null;\n" + "}\n" + "@after {\n" + " $tree.scope = localScope;\n" + "}\n" + " : 'a' -> ^('a')\n" + ";"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals(expecting, found); } public void testDoNotTranslateAttributeCompare() throws Exception { String action = "$a.line == $b.line"; String expecting = "a.getLine() == b.getLine()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar a;\n" + "RULE:\n" + " a=ID b=ID {" + action + "}" + " ;\n" + "ID : 'id';" ); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "RULE", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals(expecting, found); } public void testDoNotTranslateScopeAttributeCompare() throws Exception { String action = "if ($rule::foo == \"foo\" || 1) { System.out.println(\"ouch\"); }"; String expecting = "if (((rule_scope)rule_stack.peek()).foo == \"foo\" || 1) { System.out.println(\"ouch\"); }"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + "scope {\n" + " String foo;" + "} :\n" + " twoIDs" + " ;\n" + "twoIDs:\n" + " ID ID {" + action + "}\n" + " ;\n" + "ID : 'id';" ); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "twoIDs", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); // check that we didn't use scopeSetAttributeRef int translation! boolean foundScopeSetAttributeRef = false; for (int i = 0; i < translator.chunks.size(); i++) { Object chunk = translator.chunks.get(i); if (chunk instanceof StringTemplate) { if (((StringTemplate)chunk).getName().equals("scopeSetAttributeRef")) { foundScopeSetAttributeRef = true; } } } assertFalse("action translator used scopeSetAttributeRef template in comparison!", foundScopeSetAttributeRef); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals(expecting, found); } public void testTreeRuleStopAttributeIsInvalid() throws Exception { String action = "$r.x; $r.start; $r.stop"; String expecting = "r.x; ((CommonTree)r.start); $r.stop"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "tree grammar t;\n" + "options {ASTLabelType=CommonTree;}\n"+ "a returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_RULE_ATTRIBUTE; Object expectedArg = "a"; Object expectedArg2 = "stop"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); System.out.println("equeue:"+equeue); checkError(equeue, expectedMessage); } public void testRefToTextAttributeForCurrentTreeRule() throws Exception { String action = "$text"; String expecting = "input.getTokenStream().toString(\n" + " input.getTreeAdaptor().getTokenStartIndex(retval.start),\n" + " input.getTreeAdaptor().getTokenStopIndex(retval.start))"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "tree grammar t;\n" + "options {ASTLabelType=CommonTree;}\n" + "a : {###"+action+"!!!}\n" + " ;\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } // S U P P O R T protected void checkError(ErrorQueue equeue, GrammarSemanticsMessage expectedMessage) throws Exception { /* System.out.println(equeue.infos); System.out.println(equeue.warnings); System.out.println(equeue.errors); */ Message foundMsg = null; for (int i = 0; i < equeue.errors.size(); i++) { Message m = (Message)equeue.errors.get(i); if (m.msgID==expectedMessage.msgID ) { foundMsg = m; } } assertTrue("no error; "+expectedMessage.msgID+" expected", equeue.errors.size() > 0); assertNotNull("couldn't find expected error: "+expectedMessage.msgID, foundMsg); assertTrue("error is not a GrammarSemanticsMessage", foundMsg instanceof GrammarSemanticsMessage); assertEquals(expectedMessage.arg, foundMsg.arg); assertEquals(expectedMessage.arg2, foundMsg.arg2); } /** Allow checking for multiple errors in one test */ protected void checkErrors(ErrorQueue equeue, ArrayList expectedMessages) throws Exception { ArrayList messageExpected = new ArrayList(equeue.errors.size()); for (int i = 0; i < equeue.errors.size(); i++) { Message m = (Message)equeue.errors.get(i); boolean foundMsg = false; for (int j = 0; j < expectedMessages.size(); j++) { Message em = (Message)expectedMessages.get(j); if (m.msgID==em.msgID && m.arg.equals(em.arg) && m.arg2.equals(em.arg2)) { foundMsg = true; } } if (foundMsg) { messageExpected.add(i, Boolean.TRUE); } else messageExpected.add(i, Boolean.FALSE); } for (int i = 0; i < equeue.errors.size(); i++) { assertTrue("unexpected error:" + equeue.errors.get(i), ((Boolean)messageExpected.get(i)).booleanValue()); } } }
UTF-8
Java
114,395
java
TestAttributes.java
Java
[ { "context": "/*\n [The \"BSD licence\"]\n Copyright (c) 2005-2006 Terence Parr\n All rights reserved.\n\n Redistribution and use in", "end": 61, "score": 0.9998106360435486, "start": 49, "tag": "NAME", "value": "Terence Parr" } ]
null
[]
/* [The "BSD licence"] Copyright (c) 2005-2006 <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.test; import org.antlr.Tool; import org.antlr.codegen.CodeGenerator; import org.antlr.codegen.ActionTranslatorLexer; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import org.antlr.tool.*; import java.io.StringReader; import java.util.List; import java.util.ArrayList; /** Check the $x, $x.y attributes. For checking the actual * translation, assume the Java target. This is still a great test * for the semantics of the $x.y stuff regardless of the target. */ public class TestAttributes extends BaseTest { /** Public default constructor used by TestRig */ public TestAttributes() { } public void testEscapedLessThanInAction() throws Exception { Grammar g = new Grammar(); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); String action = "i<3; '<xmltag>'"; ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),0); String expecting = action; String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, "<action>"); actionST.setAttribute("action", rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testEscaped$InAction() throws Exception { String action = "int \\$n; \"\\$in string\\$\""; String expecting = "int $n; \"$in string$\""; Grammar g = new Grammar( "parser grammar t;\n"+ "@members {"+action+"}\n"+ "a[User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testArguments() throws Exception { String action = "$i; $i.x; $u; $u.x"; String expecting = "i; i.x; u; u.x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } /** $x.start refs are checked during translation not before so ANTLR misses the fact that rule r has refs to predefined attributes if the ref is after the def of the method or self-referential. Actually would be ok if I didn't convert actions to strings; keep as templates. June 9, 2006: made action translation leave templates not strings */ public void testRefToReturnValueBeforeRefToPredefinedAttr() throws Exception { String action = "$x.foo"; String expecting = "x.foo"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : x=b {"+action+"} ;\n" + "b returns [int foo] : B {$b.start} ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelBeforeRefToPredefinedAttr() throws Exception { // As of Mar 2007, I'm removing unused labels. Unfortunately, // the action is not seen until code gen. Can't see $x.text // before stripping unused labels. We really need to translate // actions first so code gen logic can use info. String action = "$x.text"; String expecting = "input.toString(x.start,x.stop)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : x=b {"+action+"} ;\n" + "b : B ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testInvalidArguments() throws Exception { String action = "$x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testReturnValue() throws Exception { String action = "$x.i"; String expecting = "x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i]\n" + " : 'a'\n" + " ;\n" + "b : x=a {"+action+"} ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReturnValueWithNumber() throws Exception { String action = "$x.i1"; String expecting = "x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i1]\n" + " : 'a'\n" + " ;\n" + "b : x=a {"+action+"} ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReturnValues() throws Exception { String action = "$i; $i.x; $u; $u.x"; String expecting = "retval.i; retval.i.x; retval.u; retval.u.x"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } /* regression test for ANTLR-46 */ public void testReturnWithMultipleRuleRefs() throws Exception { String action1 = "$obj = $rule2.obj;"; String action2 = "$obj = $rule3.obj;"; String expecting1 = "obj = rule21;"; String expecting2 = "obj = rule32;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "rule1 returns [ Object obj ]\n" + ": rule2 { "+action1+" }\n" + "| rule3 { "+action2+" }\n" + ";\n"+ "rule2 returns [ Object obj ]\n"+ ": foo='foo' { $obj = $foo.text; }\n"+ ";\n"+ "rule3 returns [ Object obj ]\n"+ ": bar='bar' { $obj = $bar.text; }\n"+ ";"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int i = 0; String action = action1; String expecting = expecting1; do { ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"rule1", new antlr.CommonToken(ANTLRParser.ACTION,action),i+1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); action = action2; expecting = expecting2; } while (i++ < 1); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testInvalidReturnValues() throws Exception { String action = "$x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [User u, int i]\n" + " : {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testTokenLabels() throws Exception { String action = "$id; $f; $id.text; $id.getText(); $id.dork " + "$id.type; $id.line; $id.pos; " + "$id.channel; $id.index;"; String expecting = "id; f; id.getText(); id.getText(); id.dork " + "id.getType(); id.getLine(); id.getCharPositionInLine(); " + "id.getChannel(); id.getTokenIndex();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : id=ID f=FLOAT {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabels() throws Exception { String action = "$r.x; $r.start; $r.stop; $r.tree; $a.x; $a.stop;"; String expecting = "r.x; ((Token)r.start); ((Token)r.stop); ((Object)r.tree); r.x; ((Token)r.stop);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelsWithSpecialToken() throws Exception { String action = "$r.x; $r.start; $r.stop; $r.tree; $a.x; $a.stop;"; String expecting = "r.x; ((MYTOKEN)r.start); ((MYTOKEN)r.stop); ((Object)r.tree); r.x; ((MYTOKEN)r.stop);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "options {TokenLabelType=MYTOKEN;}\n"+ "a returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testForwardRefRuleLabels() throws Exception { String action = "$r.x; $r.start; $r.stop; $r.tree; $a.x; $a.tree;"; String expecting = "r.x; ((Token)r.start); ((Token)r.stop); ((Object)r.tree); r.x; ((Object)r.tree);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;\n" + "a returns [int x]\n" + " : ;\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testInvalidRuleLabelAccessesParameter() throws Exception { String action = "$r.z"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[int z] returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_INVALID_RULE_PARAMETER_REF; Object expectedArg = "a"; Object expectedArg2 = "z"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testInvalidRuleLabelAccessesScopeAttribute() throws Exception { String action = "$r.n"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a\n" + "scope { int n; }\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_INVALID_RULE_SCOPE_ATTRIBUTE_REF; Object expectedArg = "a"; Object expectedArg2 = "n"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testInvalidRuleAttribute() throws Exception { String action = "$r.blort"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[int z] returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_RULE_ATTRIBUTE; Object expectedArg = "a"; Object expectedArg2 = "blort"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testMissingRuleAttribute() throws Exception { String action = "$r"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a[int z] returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a[3] {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "r"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testMissingUnlabeledRuleAttribute() throws Exception { String action = "$a"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a returns [int x]:\n" + " ;\n"+ "b : a {"+action+"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "a"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testNonDynamicAttributeOutsideRule() throws Exception { String action = "public void foo() { $x; }"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "@members {'+action+'}\n" + "a : ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, null, new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_ATTRIBUTE_REF_NOT_IN_RULE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testNonDynamicAttributeOutsideRule2() throws Exception { String action = "public void foo() { $x.y; }"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "@members {'+action+'}\n" + "a : ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, null, new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_ATTRIBUTE_REF_NOT_IN_RULE; Object expectedArg = "x"; Object expectedArg2 = "y"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } // D Y N A M I C A L L Y S C O P E D A T T R I B U T E S public void testBasicGlobalScope() throws Exception { String action = "$Symbols::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.peek()).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testUnknownGlobalScope() throws Exception { String action = "$Symbols::names.add($id.text);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); assertEquals("unexpected errors: "+equeue, 2, equeue.errors.size()); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE; Object expectedArg = "Symbols"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testIndexedGlobalScope() throws Exception { String action = "$Symbols[-1]::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.elementAt(Symbols_stack.size()-1-1)).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void test0IndexedGlobalScope() throws Exception { String action = "$Symbols[0]::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.elementAt(0)).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testAbsoluteIndexedGlobalScope() throws Exception { String action = "$Symbols[3]::names.add($id.text);"; String expecting = "((Symbols_scope)Symbols_stack.elementAt(3)).names.add(id.getText());"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "a scope Symbols; : (id=ID ';' {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testScopeAndAttributeWithUnderscore() throws Exception { String action = "$foo_bar::a_b;"; String expecting = "((foo_bar_scope)foo_bar_stack.peek()).a_b;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope foo_bar {\n" + " int a_b;\n" + "}\n" + "a scope foo_bar; : (ID {"+action+"} )+\n" + " ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testSharedGlobalScope() throws Exception { String action = "$Symbols::x;"; String expecting = "((Symbols_scope)Symbols_stack.peek()).x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " String x;\n" + "}\n" + "a\n"+ "scope { int y; }\n"+ "scope Symbols;\n" + " : b {"+action+"}\n" + " ;\n" + "b : ID {$Symbols::x=$ID.text} ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testGlobalScopeOutsideRule() throws Exception { String action = "public void foo() {$Symbols::names.add('foo');}"; String expecting = "public void foo() {((Symbols_scope)Symbols_stack.peek()).names.add('foo');}"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + " List names;\n" + "}\n" + "@members {'+action+'}\n" + "a : \n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleScopeOutsideRule() throws Exception { String action = "public void foo() {$a::name;}"; String expecting = "public void foo() {((a_scope)a_stack.peek()).name;}"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "@members {"+action+"}\n" + "a\n" + "scope { int name; }\n" + " : {foo();}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, null, new antlr.CommonToken(ANTLRParser.ACTION,action),0); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testBasicRuleScope() throws Exception { String action = "$a::n;"; String expecting = "((a_scope)a_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testUnqualifiedRuleScopeAccessInsideRule() throws Exception { String action = "$n;"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_ATTRIBUTE; Object expectedArg = "n"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIsolatedDynamicRuleScopeRef() throws Exception { String action = "$a;"; // refers to stack not top of stack String expecting = "a_stack;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b ;\n" + "b : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testDynamicRuleScopeRefInSubrule() throws Exception { String action = "$a::n;"; String expecting = "((a_scope)a_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b ;\n" + "b : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testIsolatedGlobalScopeRef() throws Exception { String action = "$Symbols;"; String expecting = "Symbols_stack;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " String x;\n" + "}\n" + "a\n"+ "scope { int y; }\n"+ "scope Symbols;\n" + " : b {"+action+"}\n" + " ;\n" + "b : ID {$Symbols::x=$ID.text} ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleScopeFromAnotherRule() throws Exception { String action = "$a::n;"; // must be qualified String expecting = "((a_scope)a_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b\n" + " ;\n" + "b : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testFullyQualifiedRefToCurrentRuleParameter() throws Exception { String action = "$a.i;"; String expecting = "i;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a[int i]: {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testFullyQualifiedRefToCurrentRuleRetVal() throws Exception { String action = "$a.i;"; String expecting = "retval.i;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i, int j]: {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testSetFullyQualifiedRefToCurrentRuleRetVal() throws Exception { String action = "$a.i = 1;"; String expecting = "retval.i = 1;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a returns [int i, int j]: {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testIsolatedRefToCurrentRule() throws Exception { String action = "$a;"; String expecting = ""; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : 'a' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "a"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIsolatedRefToRule() throws Exception { String action = "$x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x=b {"+action+"}\n" + " ;\n" + "b : 'b' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates int expectedMsgID = ErrorManager.MSG_ISOLATED_RULE_SCOPE; Object expectedArg = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } /* I think these have to be errors $a.x makes no sense. public void testFullyQualifiedRefToLabelInCurrentRule() throws Exception { String action = "$a.x;"; String expecting = "x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x='a' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testFullyQualifiedRefToListLabelInCurrentRule() throws Exception { String action = "$a.x;"; // must be qualified String expecting = "list_x;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x+='a' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } */ public void testFullyQualifiedRefToTemplateAttributeInCurrentRule() throws Exception { String action = "$a.st;"; // can be qualified String expecting = "retval.st;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "options {output=template;}\n"+ "a : (A->{$A.text}) {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleRefWhenRuleHasScope() throws Exception { String action = "$b.start;"; String expecting = "((Token)b1.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "a : b {###"+action+"!!!} ;\n" + "b\n" + "scope {\n" + " int n;\n" + "} : 'b' \n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testDynamicScopeRefOkEvenThoughRuleRefExists() throws Exception { String action = "$b::n;"; String expecting = "((b_scope)b_stack.peek()).n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "s : b ;\n"+ "b\n" + "scope {\n" + " int n;\n" + "} : '(' b ')' {"+action+"}\n" + // refers to current invocation's n " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToTemplateAttributeForCurrentRule() throws Exception { String action = "$st=null;"; String expecting = "retval.st =null;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "options {output=template;}\n"+ "a : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToTextAttributeForCurrentRule() throws Exception { String action = "$text"; String expecting = "input.toString(retval.start,input.LT(-1))"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "options {output=template;}\n"+ "a : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToStartAttributeForCurrentRule() throws Exception { String action = "$start;"; String expecting = "((Token)retval.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n" + "a : {###"+action+"!!!}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testTokenLabelFromMultipleAlts() throws Exception { String action = "$ID.text;"; // must be qualified String action2 = "$INT.text;"; // must be qualified String expecting = "ID1.getText();"; String expecting2 = "INT2.getText();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID {"+action+"}\n" + " | INT {"+action2+"}\n" + " ;\n" + "ID : 'a';\n" + "INT : '0';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action2),2); rawTranslation = translator.translate(); templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); actionST = new StringTemplate(templates, rawTranslation); found = actionST.toString(); assertEquals(expecting2, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelFromMultipleAlts() throws Exception { String action = "$b.text;"; // must be qualified String action2 = "$c.text;"; // must be qualified String expecting = "input.toString(b1.start,b1.stop);"; String expecting2 = "input.toString(c2.start,c2.stop);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : b {"+action+"}\n" + " | c {"+action2+"}\n" + " ;\n" + "b : 'a';\n" + "c : '0';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action2),2); rawTranslation = translator.translate(); templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); actionST = new StringTemplate(templates, rawTranslation); found = actionST.toString(); assertEquals(expecting2, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testUnknownDynamicAttribute() throws Exception { String action = "$a::x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE_ATTRIBUTE; Object expectedArg = "a"; Object expectedArg2 = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testUnknownGlobalDynamicAttribute() throws Exception { String action = "$Symbols::x"; String expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "scope Symbols {\n" + " int n;\n" + "}\n" + "a : {'+action+'}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE_ATTRIBUTE; Object expectedArg = "Symbols"; Object expectedArg2 = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testUnqualifiedRuleScopeAttribute() throws Exception { String action = "$n;"; // must be qualified String expecting = "$n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a\n" + "scope {\n" + " int n;\n" + "} : b\n" + " ;\n" + "b : {'+action+'}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "b", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; Object expectedArg = "n"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testRuleAndTokenLabelTypeMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : id='foo' id=b\n" + " ;\n" + "b : ;\n"); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; Object expectedArg = "id"; Object expectedArg2 = "rule!=token"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testListAndTokenLabelTypeMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+='a' ids='b'\n" + " ;\n" + "b : ;\n"); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; Object expectedArg = "ids"; Object expectedArg2 = "token!=token-list"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testListAndRuleLabelTypeMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n" + "options {output=AST;}\n"+ "a : bs+=b bs=b\n" + " ;\n" + "b : 'b';\n"); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; Object expectedArg = "bs"; Object expectedArg2 = "rule!=rule-list"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgReturnValueMismatch() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a[int i] returns [int x, int i]\n" + " : \n" + " ;\n" + "b : ;\n"); int expectedMsgID = ErrorManager.MSG_ARG_RETVAL_CONFLICT; Object expectedArg = "i"; Object expectedArg2 = "a"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testSimplePlusEqualLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "parser grammar t;\n"+ "a : ids+=ID ( COMMA ids+=ID {"+action+"})* ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testPlusEqualStringLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+='if' ( ',' ids+=ID {"+action+"})* ;" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testPlusEqualSetLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+=('a'|'b') ( ',' ids+=ID {"+action+"})* ;" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testPlusEqualWildcardLabel() throws Exception { String action = "$ids.size();"; // must be qualified String expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ids+=. ( ',' ids+=ID {"+action+"})* ;" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testImplicitTokenLabel() throws Exception { String action = "$ID; $ID.text; $ID.getText()"; String expecting = "ID1; ID1.getText(); ID1.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testImplicitRuleLabel() throws Exception { String action = "$r.start;"; String expecting = "((Token)r1.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r {###"+action+"!!!} ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingLabelWithImplicitRuleLabel() throws Exception { String action = "$r.start;"; String expecting = "((Token)x.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x=r {###"+action+"!!!} ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingListLabelWithImplicitRuleLabel() throws Exception { String action = "$r.start;"; String expecting = "((Token)x.start);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "options {output=AST;}\n" + "a : x+=r {###"+action+"!!!} ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingLabelWithImplicitTokenLabel() throws Exception { String action = "$ID.text;"; String expecting = "x.getText();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x=ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testReuseExistingListLabelWithImplicitTokenLabel() throws Exception { String action = "$ID.text;"; String expecting = "x.getText();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : x+=ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRuleLabelWithoutOutputOption() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar T;\n"+ "s : x+=a ;" + "a : 'a';\n"+ "b : 'b';\n"+ "WS : ' '|'\n';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_LIST_LABEL_INVALID_UNLESS_RETVAL_STRUCT; Object expectedArg = "x"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testRuleLabelOnTwoDifferentRulesAST() throws Exception { String grammar = "grammar T;\n"+ "options {output=AST;}\n"+ "s : x+=a x+=b {System.out.println($x);} ;" + "a : 'a';\n"+ "b : 'b';\n"+ "WS : (' '|'\n') {skip();};\n"; String expecting = "[a, b]\na b\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "a b", false); assertEquals(expecting, found); } public void testRuleLabelOnTwoDifferentRulesTemplate() throws Exception { String grammar = "grammar T;\n"+ "options {output=template;}\n"+ "s : x+=a x+=b {System.out.println($x);} ;" + "a : 'a' -> {%{\"hi\"}} ;\n"+ "b : 'b' -> {%{\"mom\"}} ;\n"+ "WS : (' '|'\n') {skip();};\n"; String expecting = "[hi, mom]\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "s", "a b", false); assertEquals(expecting, found); } public void testMissingArgs() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;" + "r[int i] : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; Object expectedArg = "r"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgsWhenNoneDefined() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r[32,34] ;" + "r : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; Object expectedArg = "r"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testReturnInitValue() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;\n" + "r returns [int x=0] : 'a' {$x = 4;} ;\n"); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); Rule r = g.getRule("r"); AttributeScope retScope = r.returnScope; List parameters = retScope.getAttributes(); assertNotNull("missing return action", parameters); assertEquals(1, parameters.size()); String found = parameters.get(0).toString(); String expecting = "int x=0"; assertEquals(expecting, found); } public void testMultipleReturnInitValue() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;\n" + "r returns [int x=0, int y, String s=new String(\"foo\")] : 'a' {$x = 4;} ;\n"); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); Rule r = g.getRule("r"); AttributeScope retScope = r.returnScope; List parameters = retScope.getAttributes(); assertNotNull("missing return action", parameters); assertEquals(3, parameters.size()); assertEquals("int x=0", parameters.get(0).toString()); assertEquals("int y", parameters.get(1).toString()); assertEquals("String s=new String(\"foo\")", parameters.get(2).toString()); } public void testCStyleReturnInitValue() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r ;\n" + "r returns [int (*x)()=NULL] : 'a' ;\n"); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); Rule r = g.getRule("r"); AttributeScope retScope = r.returnScope; List parameters = retScope.getAttributes(); assertNotNull("missing return action", parameters); assertEquals(1, parameters.size()); String found = parameters.get(0).toString(); String expecting = "int (*)() x=NULL"; assertEquals(expecting, found); } public void testArgsWithInitValues() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : r[32,34] ;" + "r[int x, int y=3] : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_ARG_INIT_VALUES_ILLEGAL; Object expectedArg = "y"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgsOnToken() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID[32,34] ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_ARGS_ON_TOKEN_REF; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testArgsOnTokenInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' ID[32,34] ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testLabelOnRuleRefInLexer() throws Exception { String action = "$i.text"; String expecting = "i.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' i=ID {"+action+"};" + "fragment ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToRuleRefInLexer() throws Exception { String action = "$ID.text"; String expecting = "ID1.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testRefToRuleRefInLexerNoAttribute() throws Exception { String action = "$ID"; String expecting = "ID1"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'z' ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testCharLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x='z' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testCharListLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x+='z' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testWildcardCharLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x=. ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testWildcardCharListLabelInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : x+=. ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testMissingArgsInLexer() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "A : R ;" + "R[int i] : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; Object expectedArg = "R"; Object expectedArg2 = null; // getting a second error @1:12, probably from nextToken GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testLexerRulePropertyRefs() throws Exception { String action = "$text $type $line $pos $channel $index $start $stop"; String expecting = "getText() _type tokenStartLine tokenStartCharPositionInLine channel -1 tokenStartCharIndex (getCharIndex()-1)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'r' {"+action+"};\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testLexerLabelRefs() throws Exception { String action = "$a $b.text $c $d.text"; String expecting = "a b.getText() c d.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : a='c' b='hi' c=. d=DUH {"+action+"};\n" + "DUH : 'd' ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testSettingLexerRulePropertyRefs() throws Exception { String action = "$text $type=1 $line=1 $pos=1 $channel=1 $index"; String expecting = "getText() _type=1 tokenStartLine=1 tokenStartCharPositionInLine=1 channel=1 -1"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar t;\n"+ "R : 'r' {"+action+"};\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "R", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testArgsOnTokenInLexerRuleOfCombined() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : R;\n" + "R : 'z' ID[32] ;\n" + "ID : 'a';\n"); String lexerGrammarStr = g.getLexerGrammar(); StringReader sr = new StringReader(lexerGrammarStr); Grammar lexerGrammar = new Grammar(); lexerGrammar.setFileName("<internally-generated-lexer>"); lexerGrammar.importTokenVocabulary(g); lexerGrammar.setGrammarContent(sr); sr.close(); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, lexerGrammar, "Java"); lexerGrammar.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, lexerGrammar, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testMissingArgsOnTokenInLexerRuleOfCombined() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : R;\n" + "R : 'z' ID ;\n" + "ID[int i] : 'a';\n"); String lexerGrammarStr = g.getLexerGrammar(); StringReader sr = new StringReader(lexerGrammarStr); Grammar lexerGrammar = new Grammar(); lexerGrammar.setFileName("<internally-generated-lexer>"); lexerGrammar.importTokenVocabulary(g); lexerGrammar.setGrammarContent(sr); sr.close(); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, lexerGrammar, "Java"); lexerGrammar.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; Object expectedArg = "ID"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, lexerGrammar, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } // T R E E S public void testTokenLabelTreeProperty() throws Exception { String action = "$id.tree;"; String expecting = "id_tree;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : id=ID {"+action+"} ;\n" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testTokenRefTreeProperty() throws Exception { String action = "$ID.tree;"; String expecting = "ID1_tree;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID {"+action+"} ;" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator,"a", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testAmbiguousTokenRef() throws Exception { String action = "$ID;"; String expecting = ""; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_NONUNIQUE_REF; Object expectedArg = "ID"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testAmbiguousTokenRefWithProp() throws Exception { String action = "$ID.text;"; String expecting = ""; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar t;\n"+ "a : ID ID {"+action+"};" + "ID : 'a';\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_NONUNIQUE_REF; Object expectedArg = "ID"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkError(equeue, expectedMessage); } public void testRuleRefWithDynamicScope() throws Exception { String action = "$field::x = $field.st;"; String expecting = "((field_scope)field_stack.peek()).x = retval.st;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "field\n" + "scope { StringTemplate x; }\n" + " : 'y' {"+action+"}\n" + " ;\n"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "field", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testAssignToOwnRulenameAttr() throws Exception { String action = "$rule.tree = null;"; String expecting = "retval.tree = null;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testAssignToOwnParamAttr() throws Exception { String action = "$rule.i = 42; $i = 23;"; String expecting = "i = 42; i = 23;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule[int i]\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } public void testIllegalAssignToOwnRulenameAttr() throws Exception { String action = "$rule.stop = 0;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; Object expectedArg = "rule"; Object expectedArg2 = "stop"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIllegalAssignToLocalAttr() throws Exception { String action = "$tree = null; $st = null; $start = 0; $stop = 0; $text = 0;"; String expecting = "retval.tree = null; retval.st = null; "; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + " : 'y' {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; ArrayList expectedErrors = new ArrayList(3); GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, "start", ""); expectedErrors.add(expectedMessage); GrammarSemanticsMessage expectedMessage2 = new GrammarSemanticsMessage(expectedMsgID, g, null, "stop", ""); expectedErrors.add(expectedMessage2); GrammarSemanticsMessage expectedMessage3 = new GrammarSemanticsMessage(expectedMsgID, g, null, "text", ""); expectedErrors.add(expectedMessage3); checkErrors(equeue, expectedErrors); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals(expecting, found); } public void testIllegalAssignRuleRefAttr() throws Exception { String action = "$other.tree = null;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "options { output = AST;}" + "otherrule\n" + " : 'y' ;" + "rule\n" + " : other=otherrule {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; Object expectedArg = "other"; Object expectedArg2 = "tree"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testIllegalAssignTokenRefAttr() throws Exception { String action = "$ID.text = \"test\";"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "ID\n" + " : 'y' ;" + "rule\n" + " : ID {" + action +"}\n" + " ;"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); int expectedMsgID = ErrorManager.MSG_WRITE_TO_READONLY_ATTR; Object expectedArg = "ID"; Object expectedArg2 = "text"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } public void testAssignToTreeNodeAttribute() throws Exception { String action = "$tree.scope = localScope;"; String expecting = "(()retval.tree).scope = localScope;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "options { output=AST; }" + "rule\n" + "@init {\n" + " Scope localScope=null;\n" + "}\n" + "@after {\n" + " $tree.scope = localScope;\n" + "}\n" + " : 'a' -> ^('a')\n" + ";"); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // forces load of templates ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "rule", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals(expecting, found); } public void testDoNotTranslateAttributeCompare() throws Exception { String action = "$a.line == $b.line"; String expecting = "a.getLine() == b.getLine()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "lexer grammar a;\n" + "RULE:\n" + " a=ID b=ID {" + action + "}" + " ;\n" + "ID : 'id';" ); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "RULE", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals(expecting, found); } public void testDoNotTranslateScopeAttributeCompare() throws Exception { String action = "if ($rule::foo == \"foo\" || 1) { System.out.println(\"ouch\"); }"; String expecting = "if (((rule_scope)rule_stack.peek()).foo == \"foo\" || 1) { System.out.println(\"ouch\"); }"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "grammar a;\n" + "rule\n" + "scope {\n" + " String foo;" + "} :\n" + " twoIDs" + " ;\n" + "twoIDs:\n" + " ID ID {" + action + "}\n" + " ;\n" + "ID : 'id';" ); Tool antlr = newTool(); CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); ActionTranslatorLexer translator = new ActionTranslatorLexer(generator, "twoIDs", new antlr.CommonToken(ANTLRParser.ACTION,action),1); String rawTranslation = translator.translate(); // check that we didn't use scopeSetAttributeRef int translation! boolean foundScopeSetAttributeRef = false; for (int i = 0; i < translator.chunks.size(); i++) { Object chunk = translator.chunks.get(i); if (chunk instanceof StringTemplate) { if (((StringTemplate)chunk).getName().equals("scopeSetAttributeRef")) { foundScopeSetAttributeRef = true; } } } assertFalse("action translator used scopeSetAttributeRef template in comparison!", foundScopeSetAttributeRef); StringTemplateGroup templates = new StringTemplateGroup(".", AngleBracketTemplateLexer.class); StringTemplate actionST = new StringTemplate(templates, rawTranslation); String found = actionST.toString(); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals(expecting, found); } public void testTreeRuleStopAttributeIsInvalid() throws Exception { String action = "$r.x; $r.start; $r.stop"; String expecting = "r.x; ((CommonTree)r.start); $r.stop"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "tree grammar t;\n" + "options {ASTLabelType=CommonTree;}\n"+ "a returns [int x]\n" + " :\n" + " ;\n"+ "b : r=a {###"+action+"!!!}\n" + " ;"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_RULE_ATTRIBUTE; Object expectedArg = "a"; Object expectedArg2 = "stop"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); System.out.println("equeue:"+equeue); checkError(equeue, expectedMessage); } public void testRefToTextAttributeForCurrentTreeRule() throws Exception { String action = "$text"; String expecting = "input.getTokenStream().toString(\n" + " input.getTreeAdaptor().getTokenStartIndex(retval.start),\n" + " input.getTreeAdaptor().getTokenStopIndex(retval.start))"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Grammar g = new Grammar( "tree grammar t;\n" + "options {ASTLabelType=CommonTree;}\n" + "a : {###"+action+"!!!}\n" + " ;\n"); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.getRecognizerST(); String code = codeST.toString(); String found = code.substring(code.indexOf("###")+3,code.indexOf("!!!")); assertEquals(expecting, found); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } // S U P P O R T protected void checkError(ErrorQueue equeue, GrammarSemanticsMessage expectedMessage) throws Exception { /* System.out.println(equeue.infos); System.out.println(equeue.warnings); System.out.println(equeue.errors); */ Message foundMsg = null; for (int i = 0; i < equeue.errors.size(); i++) { Message m = (Message)equeue.errors.get(i); if (m.msgID==expectedMessage.msgID ) { foundMsg = m; } } assertTrue("no error; "+expectedMessage.msgID+" expected", equeue.errors.size() > 0); assertNotNull("couldn't find expected error: "+expectedMessage.msgID, foundMsg); assertTrue("error is not a GrammarSemanticsMessage", foundMsg instanceof GrammarSemanticsMessage); assertEquals(expectedMessage.arg, foundMsg.arg); assertEquals(expectedMessage.arg2, foundMsg.arg2); } /** Allow checking for multiple errors in one test */ protected void checkErrors(ErrorQueue equeue, ArrayList expectedMessages) throws Exception { ArrayList messageExpected = new ArrayList(equeue.errors.size()); for (int i = 0; i < equeue.errors.size(); i++) { Message m = (Message)equeue.errors.get(i); boolean foundMsg = false; for (int j = 0; j < expectedMessages.size(); j++) { Message em = (Message)expectedMessages.get(j); if (m.msgID==em.msgID && m.arg.equals(em.arg) && m.arg2.equals(em.arg2)) { foundMsg = true; } } if (foundMsg) { messageExpected.add(i, Boolean.TRUE); } else messageExpected.add(i, Boolean.FALSE); } for (int i = 0; i < equeue.errors.size(); i++) { assertTrue("unexpected error:" + equeue.errors.get(i), ((Boolean)messageExpected.get(i)).booleanValue()); } } }
114,389
0.695258
0.691962
3,140
35.43153
23.000944
133
false
false
0
0
0
0
0
0
3.567198
false
false
2
a7a2fef0376c7485c996f47e643e072c20865ddc
12,635,793,802,085
be815aacbd7b06ac0ce3f412831639aa0297b988
/notifier/smtp/src/main/java/com/epam/pipeline/notifier/service/NotificationService.java
eacf7e709aa770d662fe16dedd5a86034a65e5d4
[ "Apache-2.0" ]
permissive
epam/cloud-pipeline
https://github.com/epam/cloud-pipeline
8a861dae60d0f86089ff55e2f278e8593fc5e112
570dd898e96de931b96e584c86e72296b0e40607
refs/heads/develop
2023-08-30T08:03:18.672000
2023-08-29T17:07:13
2023-08-29T17:07:13
174,065,041
155
73
Apache-2.0
false
2023-09-14T13:36:36
2019-03-06T03:34:40
2023-09-10T02:53:30
2023-09-14T13:36:34
165,796
131
61
835
Java
false
false
/* * Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.pipeline.notifier.service; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import com.epam.pipeline.entity.notification.NotificationMessage; import com.epam.pipeline.notifier.repository.NotificationRepository; import com.epam.pipeline.notifier.service.task.NotificationManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class NotificationService { private static final Logger LOGGER = LoggerFactory.getLogger(NotificationService.class); @Autowired private ExecutorService notificationThreadPool; @Value(value = "${notification.at.time:5}") private int notificationAtTime; @Autowired private NotificationRepository notificationRepository; @Autowired private List<NotificationManager> notificationManagers; /** * Scheduled task to load batch of {@link NotificationMessage} from database * and delegate it to all realizations of {@link NotificationManager} */ @Scheduled(fixedDelayString = "${notification.scheduler.delay}") @Transactional(propagation = Propagation.REQUIRED) public void sendNotification() { LOGGER.debug("Start scheduled notification loop..."); Pageable limit = new PageRequest(0, notificationAtTime); List<NotificationMessage> result = notificationRepository.loadNotification(limit); result.forEach(message -> { notificationRepository.deleteById(message.getId()); for (NotificationManager notificationManager : notificationManagers) { CompletableFuture.runAsync( () -> notificationManager.notifySubscribers(message), notificationThreadPool) .exceptionally(throwable -> { LOGGER.warn("Exception while trying to send email", throwable); return null; }); } }); LOGGER.debug("End scheduled notification loop..."); } }
UTF-8
Java
3,145
java
NotificationService.java
Java
[]
null
[]
/* * Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.pipeline.notifier.service; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import com.epam.pipeline.entity.notification.NotificationMessage; import com.epam.pipeline.notifier.repository.NotificationRepository; import com.epam.pipeline.notifier.service.task.NotificationManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class NotificationService { private static final Logger LOGGER = LoggerFactory.getLogger(NotificationService.class); @Autowired private ExecutorService notificationThreadPool; @Value(value = "${notification.at.time:5}") private int notificationAtTime; @Autowired private NotificationRepository notificationRepository; @Autowired private List<NotificationManager> notificationManagers; /** * Scheduled task to load batch of {@link NotificationMessage} from database * and delegate it to all realizations of {@link NotificationManager} */ @Scheduled(fixedDelayString = "${notification.scheduler.delay}") @Transactional(propagation = Propagation.REQUIRED) public void sendNotification() { LOGGER.debug("Start scheduled notification loop..."); Pageable limit = new PageRequest(0, notificationAtTime); List<NotificationMessage> result = notificationRepository.loadNotification(limit); result.forEach(message -> { notificationRepository.deleteById(message.getId()); for (NotificationManager notificationManager : notificationManagers) { CompletableFuture.runAsync( () -> notificationManager.notifySubscribers(message), notificationThreadPool) .exceptionally(throwable -> { LOGGER.warn("Exception while trying to send email", throwable); return null; }); } }); LOGGER.debug("End scheduled notification loop..."); } }
3,145
0.730048
0.72496
80
38.3125
28.317219
92
false
false
0
0
0
0
0
0
0.5
false
false
2
5da2d78d98992380d63623950eeb4172767e4887
22,101,901,716,204
b1de5751155632aad39403948e3408d2a15ddab5
/src/problems/school/numbers/Pallindrome.java
453fe9065b7bc6e3e5a7bddedb0c483bf859caef
[]
no_license
poojabh37/data-structures
https://github.com/poojabh37/data-structures
1d17fcf6a117aa91a59bd0c60160d3fb443786e9
e87529cac062f92e72074ce3249332ce52f505a5
refs/heads/master
2022-03-02T16:22:01.559000
2019-10-05T13:06:46
2019-10-05T13:06:46
198,017,475
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package problems.school.numbers; import java.util.Scanner; public class Pallindrome { //can be done with strings public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int num = sc.nextInt(); if (num == reverse(num)) { System.out.println("YES"); } else { System.out.println("NO"); } } } //can also be done using strings private static int reverse(int num) { int reverse = 0; while (num > 0) { reverse = reverse * 10; reverse = reverse + num % 10; num = num / 10; } System.out.println(reverse); return reverse; } }
UTF-8
Java
806
java
Pallindrome.java
Java
[]
null
[]
package problems.school.numbers; import java.util.Scanner; public class Pallindrome { //can be done with strings public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int num = sc.nextInt(); if (num == reverse(num)) { System.out.println("YES"); } else { System.out.println("NO"); } } } //can also be done using strings private static int reverse(int num) { int reverse = 0; while (num > 0) { reverse = reverse * 10; reverse = reverse + num % 10; num = num / 10; } System.out.println(reverse); return reverse; } }
806
0.491315
0.480149
33
23.424242
15.309
44
false
false
0
0
0
0
0
0
0.454545
false
false
2
e96aabd4a509fc2ce37aa2291ed448b14faa0689
33,724,083,222,090
d2d0cc61e064e8d1711ff0a3f1da24fe1c6a3e07
/Android/M08_Intents/M10_Intent_02/app/src/main/java/com/example/gui/m10_intents_02/MainActivity.java
d3030345bfd8837a0c377b67f8de85d8fa49deae
[]
no_license
HireIsaac/Work-Samples
https://github.com/HireIsaac/Work-Samples
0cb099594a4324f9b537181c58b5b41fc580702e
fdc13ee537decb4aeac21ddd925b86633ffd6efa
refs/heads/master
2020-04-26T15:11:27.686000
2019-03-03T22:54:43
2019-03-03T22:54:43
173,639,565
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gui.m10_intents_02; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.ViewGroup; import android.widget.LinearLayout; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import java.io.IOException; public class MainActivity extends AppCompatActivity { // private View bouncingBallView = null; private View bouncingBallView = null; private int PICK_IMAGE_REQUEST = 17; FloatingActionButton actionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionButton = (FloatingActionButton) findViewById(R.id.actionButton); Bitmap.Config config = Bitmap.Config.ARGB_8888; Bitmap bitmap = Bitmap.createBitmap(500, 500, config); FrameLayout finalView = new FrameLayout(this); LinearLayout linearLayout = new LinearLayout(this); bouncingBallView = new BouncingBallView(this, bitmap); if(actionButton.getParent() != null) { ((ViewGroup)actionButton.getParent()).removeView(actionButton); } linearLayout.addView(actionButton); finalView.addView(bouncingBallView); finalView.addView(linearLayout); setContentView(finalView); actionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); // Show only images, no videos or anything else intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); // Always show the chooser (if there are multiple options available) startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); Log.w("MainActivity-INTENT", "M10_Intents_02: onCreate getting photo"); } }); } /** * Returns after photo picked from gallery * http://codetheory.in/android-pick-select-image-from-gallery-with-intents/ */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.w("MainActivity-INTENT", "onActivityResult-1 requestCode:" + requestCode + " resultCode:" + resultCode); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); Bitmap bitmap; bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); // ImageView imageView = (ImageView) findViewById(R.id.imageView); // imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } if (null != bitmap) { bouncingBallView = new BouncingBallView(this, bitmap); setContentView(bouncingBallView); Log.w("MainActivity-INTENT", "onActivityResult-2: " + String.valueOf(bitmap)); } } } }
UTF-8
Java
3,729
java
MainActivity.java
Java
[]
null
[]
package com.example.gui.m10_intents_02; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.ViewGroup; import android.widget.LinearLayout; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import java.io.IOException; public class MainActivity extends AppCompatActivity { // private View bouncingBallView = null; private View bouncingBallView = null; private int PICK_IMAGE_REQUEST = 17; FloatingActionButton actionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionButton = (FloatingActionButton) findViewById(R.id.actionButton); Bitmap.Config config = Bitmap.Config.ARGB_8888; Bitmap bitmap = Bitmap.createBitmap(500, 500, config); FrameLayout finalView = new FrameLayout(this); LinearLayout linearLayout = new LinearLayout(this); bouncingBallView = new BouncingBallView(this, bitmap); if(actionButton.getParent() != null) { ((ViewGroup)actionButton.getParent()).removeView(actionButton); } linearLayout.addView(actionButton); finalView.addView(bouncingBallView); finalView.addView(linearLayout); setContentView(finalView); actionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); // Show only images, no videos or anything else intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); // Always show the chooser (if there are multiple options available) startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); Log.w("MainActivity-INTENT", "M10_Intents_02: onCreate getting photo"); } }); } /** * Returns after photo picked from gallery * http://codetheory.in/android-pick-select-image-from-gallery-with-intents/ */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.w("MainActivity-INTENT", "onActivityResult-1 requestCode:" + requestCode + " resultCode:" + resultCode); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); Bitmap bitmap; bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); // ImageView imageView = (ImageView) findViewById(R.id.imageView); // imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } if (null != bitmap) { bouncingBallView = new BouncingBallView(this, bitmap); setContentView(bouncingBallView); Log.w("MainActivity-INTENT", "onActivityResult-2: " + String.valueOf(bitmap)); } } } }
3,729
0.661571
0.654867
106
34.179245
28.718147
117
false
false
0
0
0
0
0
0
0.679245
false
false
2
166ad1a3f397864d762adbc460ea4f05018bda2e
14,654,428,428,754
cc460ffc14a00795454affd59dfbd9e61eb60685
/src/Nodes/ParagraphNode.java
5feb4755f40e377fb72fa97d5e176d84c6ec519a
[]
no_license
Chin-Patel/MarkdownParser
https://github.com/Chin-Patel/MarkdownParser
521766c64089fa0b3d427cbe5c229d31f295c96d
f88e88a7dde778a49a1ee9971a8bfbee3cb60426
refs/heads/master
2020-03-27T23:38:52.795000
2018-09-04T11:31:15
2018-09-04T11:31:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Nodes; public class ParagraphNode extends Node{ private String paragraph = ""; private String format = ""; public ParagraphNode(String string, String format){ this.paragraph = string; this.format = format; } @Override public String toString() { if(format.equals("HTML")) return "<p>" + paragraph + "</p>"; if(format.equals("Latex")) return paragraph + " \\par"; return ""; } }
UTF-8
Java
405
java
ParagraphNode.java
Java
[]
null
[]
package Nodes; public class ParagraphNode extends Node{ private String paragraph = ""; private String format = ""; public ParagraphNode(String string, String format){ this.paragraph = string; this.format = format; } @Override public String toString() { if(format.equals("HTML")) return "<p>" + paragraph + "</p>"; if(format.equals("Latex")) return paragraph + " \\par"; return ""; } }
405
0.671605
0.671605
18
21.5
20.006248
62
false
false
0
0
0
0
0
0
1.444444
false
false
2
b251521dcd51f636efdfdb217583bfd72c818741
23,914,377,916,750
df72d17902b3d38d456400db22e5660de9ba1f96
/GoalExplorer/src/main/java/android/goal/explorer/tmp/Constants.java
1b724bb936fd6de7e2ddb9c079ced786a29dad8a
[ "MIT" ]
permissive
rafaelsamenezes/GoalExplorer-1
https://github.com/rafaelsamenezes/GoalExplorer-1
390098912182f54b12c7025dda8df588c4445b0d
ade232d8ab59139bdf554b073c39d2f656b6ace1
refs/heads/main
2023-04-25T13:46:01.149000
2021-05-08T00:25:29
2021-05-08T00:25:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.goal.explorer.tmp; public class Constants { public static final String enableJavaScriptString = "void setJavaScriptEnabled(boolean)"; public static final String loadURLdefault = "void loadUrl(java.lang.String)"; public static final String httpConnect = "java.net.URLConnection openConnection()"; public static final String jsInterfaceTag = "Landroid/webkit/JavascriptInterface;"; public static final String facebookLogin = "void a(android.support.v4.app.Fragment,java.util.Collection)"; public static final String facebookLoginSig = "<com.facebook.login.LoginManager: void a(android.support.v4.app.Fragment,java.util.Collection)>"; }
UTF-8
Java
677
java
Constants.java
Java
[]
null
[]
package android.goal.explorer.tmp; public class Constants { public static final String enableJavaScriptString = "void setJavaScriptEnabled(boolean)"; public static final String loadURLdefault = "void loadUrl(java.lang.String)"; public static final String httpConnect = "java.net.URLConnection openConnection()"; public static final String jsInterfaceTag = "Landroid/webkit/JavascriptInterface;"; public static final String facebookLogin = "void a(android.support.v4.app.Fragment,java.util.Collection)"; public static final String facebookLoginSig = "<com.facebook.login.LoginManager: void a(android.support.v4.app.Fragment,java.util.Collection)>"; }
677
0.779911
0.776957
12
55.416668
49.356625
148
false
false
0
0
0
0
0
0
0.833333
false
false
2
1fe9f97d578def05ccbbcbdeb0a4f8ce02fbbce0
11,390,253,283,819
c7bbc4ac7416ecf44e9e20bc4fe2fd13f15bca87
/src/test/java/com/paxotech/TaskProcess.java
b000bda37e9b8692754482c4cf7e8049d52fc5ab
[]
no_license
Mollagithub/BDD
https://github.com/Mollagithub/BDD
9a17c94b681c7df4ff8b041bae18611be42d0feb
5e33fb92ac7682972b2d117e47fc792164b9fd5a
refs/heads/master
2021-01-10T16:22:12.639000
2015-11-07T18:49:46
2015-11-07T18:49:46
45,748,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.paxotech; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class TaskProcess { private WebDriver driver; @Before public void setUp(){ // driver=new FirefoxDriver(); // driver=new PhantomJSDriver(); driver.get("https://www.google.com/"); } @Test public void test(){ System.out.println("Hello we cant run"); } @After public void tearDown(){ driver.close(); driver.quit(); } }
UTF-8
Java
644
java
TaskProcess.java
Java
[]
null
[]
package com.paxotech; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class TaskProcess { private WebDriver driver; @Before public void setUp(){ // driver=new FirefoxDriver(); // driver=new PhantomJSDriver(); driver.get("https://www.google.com/"); } @Test public void test(){ System.out.println("Hello we cant run"); } @After public void tearDown(){ driver.close(); driver.quit(); } }
644
0.588509
0.588509
30
19.166666
14.350571
49
false
false
0
0
0
0
0
0
1.2
false
false
2
97d3d78f5f3e1c4a20cf0e7ff9983ebe0ab74e8c
17,111,149,728,992
aba9829f7a7f89b27099e93bef84df657eb87209
/src/main/java/me/parozzz/hopeitems/items/database/BlockTable.java
0ee12782707e95a325b06310dc1b070d72205d1a
[ "MIT" ]
permissive
SpiroMarshes/HopeItems
https://github.com/SpiroMarshes/HopeItems
0ce162989c8a14a1731bc0087364ec1d7b882b23
ffcf70e3dcdea4e9ae1ab90b512ff1c778a48b51
refs/heads/master
2020-04-07T22:16:41.639000
2018-11-23T02:46:20
2018-11-23T02:46:20
158,762,761
0
1
MIT
true
2018-11-23T00:39:34
2018-11-23T00:39:34
2018-11-20T20:50:08
2018-11-20T20:50:07
559
0
0
0
null
false
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package me.parozzz.hopeitems.items.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import me.parozzz.hopeitems.items.ItemCollection; import me.parozzz.hopeitems.items.ItemInfo; import me.parozzz.reflex.utilities.TaskUtil; import org.bukkit.Bukkit; import org.bukkit.Location; /** * * @author Paros */ public class BlockTable { private static final Logger logger = Logger.getLogger(BlockTable.class.getSimpleName()); private final DatabaseManager databaseManager; protected BlockTable(final DatabaseManager databaseManager) { this.databaseManager = databaseManager; try (Connection con = databaseManager.getConnection()) { con.createStatement().execute("CREATE TABLE IF NOT EXISTS blocks (x INTEGER, y INTEGER, z INTEGER, world TEXT, id TEXT);"); } catch(final SQLException ex) { logger.log(Level.SEVERE, "Error creative BlockTable", ex); } } private final String ADD_BLOCK = "INSERT INTO blocks (x, y, z, world, id) VALUES (?, ?, ?, ? , ?);"; public void addBlock(final Location l, final ItemCollection collection) { int x = l.getBlockX(); int y = l.getBlockY(); int z = l.getBlockZ(); String world = l.getWorld().getName(); String collectionId = collection.getId(); TaskUtil.scheduleAsync(() -> { try (Connection con = databaseManager.getConnection()) { PreparedStatement prepared = con.prepareStatement(ADD_BLOCK); prepared.setInt(1, x); prepared.setInt(2, y); prepared.setInt(3, z); prepared.setString(4, world); prepared.setString(5, collectionId); prepared.executeUpdate(); } catch(final SQLException ex) { logger.log(Level.SEVERE, null, ex); } }); } private final String REMOVE_BLOCK = "DELETE FROM blocks WHERE x = ? AND y = ? AND z = ? AND world = ?;"; public void removeBlock(final Location l) { int x = l.getBlockX(); int y = l.getBlockY(); int z = l.getBlockZ(); String world = l.getWorld().getName(); TaskUtil.scheduleAsync(() -> { try (Connection con = databaseManager.getConnection()) { PreparedStatement prepared = con.prepareStatement(REMOVE_BLOCK); prepared.setInt(1, x); prepared.setInt(2, y); prepared.setInt(3, z); prepared.setString(4, world); prepared.executeUpdate(); } catch(final SQLException ex) { logger.log(Level.SEVERE, null, ex); } }); } public Map<Location, String> getAllBlocks() { try(Connection con = databaseManager.getConnection()) { ResultSet set = con.prepareStatement("SELECT * FROM blocks").executeQuery(); Map<Location, String> map = new HashMap<>(); while(set.next()) { Location loc = new Location(Bukkit.getWorld(set.getString("world")), set.getInt("x"), set.getInt("y"), set.getInt("z")); String id = set.getString("id"); map.put(loc, id); } return map; } catch(final SQLException ex) { logger.log(Level.SEVERE, null, ex); return new HashMap<>(); } } }
UTF-8
Java
3,887
java
BlockTable.java
Java
[ { "context": "it;\nimport org.bukkit.Location;\n\n/**\n *\n * @author Paros\n */\npublic class BlockTable \n{\n private static", "end": 681, "score": 0.9737054109573364, "start": 676, "tag": "NAME", "value": "Paros" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package me.parozzz.hopeitems.items.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import me.parozzz.hopeitems.items.ItemCollection; import me.parozzz.hopeitems.items.ItemInfo; import me.parozzz.reflex.utilities.TaskUtil; import org.bukkit.Bukkit; import org.bukkit.Location; /** * * @author Paros */ public class BlockTable { private static final Logger logger = Logger.getLogger(BlockTable.class.getSimpleName()); private final DatabaseManager databaseManager; protected BlockTable(final DatabaseManager databaseManager) { this.databaseManager = databaseManager; try (Connection con = databaseManager.getConnection()) { con.createStatement().execute("CREATE TABLE IF NOT EXISTS blocks (x INTEGER, y INTEGER, z INTEGER, world TEXT, id TEXT);"); } catch(final SQLException ex) { logger.log(Level.SEVERE, "Error creative BlockTable", ex); } } private final String ADD_BLOCK = "INSERT INTO blocks (x, y, z, world, id) VALUES (?, ?, ?, ? , ?);"; public void addBlock(final Location l, final ItemCollection collection) { int x = l.getBlockX(); int y = l.getBlockY(); int z = l.getBlockZ(); String world = l.getWorld().getName(); String collectionId = collection.getId(); TaskUtil.scheduleAsync(() -> { try (Connection con = databaseManager.getConnection()) { PreparedStatement prepared = con.prepareStatement(ADD_BLOCK); prepared.setInt(1, x); prepared.setInt(2, y); prepared.setInt(3, z); prepared.setString(4, world); prepared.setString(5, collectionId); prepared.executeUpdate(); } catch(final SQLException ex) { logger.log(Level.SEVERE, null, ex); } }); } private final String REMOVE_BLOCK = "DELETE FROM blocks WHERE x = ? AND y = ? AND z = ? AND world = ?;"; public void removeBlock(final Location l) { int x = l.getBlockX(); int y = l.getBlockY(); int z = l.getBlockZ(); String world = l.getWorld().getName(); TaskUtil.scheduleAsync(() -> { try (Connection con = databaseManager.getConnection()) { PreparedStatement prepared = con.prepareStatement(REMOVE_BLOCK); prepared.setInt(1, x); prepared.setInt(2, y); prepared.setInt(3, z); prepared.setString(4, world); prepared.executeUpdate(); } catch(final SQLException ex) { logger.log(Level.SEVERE, null, ex); } }); } public Map<Location, String> getAllBlocks() { try(Connection con = databaseManager.getConnection()) { ResultSet set = con.prepareStatement("SELECT * FROM blocks").executeQuery(); Map<Location, String> map = new HashMap<>(); while(set.next()) { Location loc = new Location(Bukkit.getWorld(set.getString("world")), set.getInt("x"), set.getInt("y"), set.getInt("z")); String id = set.getString("id"); map.put(loc, id); } return map; } catch(final SQLException ex) { logger.log(Level.SEVERE, null, ex); return new HashMap<>(); } } }
3,887
0.587085
0.58477
110
34.336365
27.931173
136
false
false
0
0
0
0
0
0
0.881818
false
false
2
2a7b23043150fa1f6571863af2b29fb1bceddf59
19,387,482,389,160
5531f08532afaef446544935e5138422c815c936
/algorithms/offer/src/main/java/cn/lastwhisper/offer/interview_5/Solution_5_1.java
1c89d075ff5ef9fa5e5384041aae873f23a955f2
[]
no_license
chenxi3021/Code
https://github.com/chenxi3021/Code
19342c9f06d9f001d63b7dc46db67ec42a39e682
8236ffe7f9ba37701c1d26419a3dc16822270180
refs/heads/master
2021-01-13T21:04:17.506000
2020-02-22T10:36:30
2020-02-22T10:36:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.lastwhisper.offer.interview_5; /** * 面试题 5:替换空格 * @author cn.lastwhisper */ public class Solution_5_1 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); // 1.正常数据 //sb.append("We are happy"); // 2.前、后、连续空格 //sb.append(" We are happy "); // 3.没有空格 //sb.append("Wearehappy"); // 4.特殊测试数据:null、一个空格字符 sb.append(" "); String space = new Solution_5_1().replaceSpace(sb); System.out.println(space); } /** * 运行时间:19ms * 占用内存:9576k * @param str * @return java.lang.String */ public String replaceSpace(StringBuffer str) { // 校验数据 if (str == null || str.length() == 0) { return ""; } int spacenum = 0;//spacenum为计算空格数 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') spacenum++; } // 新字符串长度 int newlength = str.length() + spacenum * 2; // 原字符串的尾指针 int indexOfOrigin = str.length() - 1; // 新字符串的尾指针 int indexOfNew = newlength - 1; //使str的长度扩大到转换成%20之后的长度,防止下标越界 str.setLength(newlength);//底层新建数组后copy元素 for (; indexOfOrigin >= 0; indexOfOrigin--) { if (str.charAt(indexOfOrigin) == ' ') { // str.setCharAt(indexOfNew--, '0'); str.setCharAt(indexOfNew--, '2'); str.setCharAt(indexOfNew--, '%'); } else { str.setCharAt(indexOfNew--, str.charAt(indexOfOrigin)); } } return str.toString(); } /** * 运行时间:17ms * 占用内存:9580k * * @param str * @return java.lang.String */ public String replaceSpace1(StringBuffer str) { return str.toString().replace(" ", "%20"); } }
UTF-8
Java
2,114
java
Solution_5_1.java
Java
[ { "context": "r.offer.interview_5;\n\n/**\n * 面试题 5:替换空格\n * @author cn.lastwhisper\n */\npublic class Solution_5_1 {\n public static", "end": 86, "score": 0.9996589422225952, "start": 72, "tag": "USERNAME", "value": "cn.lastwhisper" } ]
null
[]
package cn.lastwhisper.offer.interview_5; /** * 面试题 5:替换空格 * @author cn.lastwhisper */ public class Solution_5_1 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); // 1.正常数据 //sb.append("We are happy"); // 2.前、后、连续空格 //sb.append(" We are happy "); // 3.没有空格 //sb.append("Wearehappy"); // 4.特殊测试数据:null、一个空格字符 sb.append(" "); String space = new Solution_5_1().replaceSpace(sb); System.out.println(space); } /** * 运行时间:19ms * 占用内存:9576k * @param str * @return java.lang.String */ public String replaceSpace(StringBuffer str) { // 校验数据 if (str == null || str.length() == 0) { return ""; } int spacenum = 0;//spacenum为计算空格数 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') spacenum++; } // 新字符串长度 int newlength = str.length() + spacenum * 2; // 原字符串的尾指针 int indexOfOrigin = str.length() - 1; // 新字符串的尾指针 int indexOfNew = newlength - 1; //使str的长度扩大到转换成%20之后的长度,防止下标越界 str.setLength(newlength);//底层新建数组后copy元素 for (; indexOfOrigin >= 0; indexOfOrigin--) { if (str.charAt(indexOfOrigin) == ' ') { // str.setCharAt(indexOfNew--, '0'); str.setCharAt(indexOfNew--, '2'); str.setCharAt(indexOfNew--, '%'); } else { str.setCharAt(indexOfNew--, str.charAt(indexOfOrigin)); } } return str.toString(); } /** * 运行时间:17ms * 占用内存:9580k * * @param str * @return java.lang.String */ public String replaceSpace1(StringBuffer str) { return str.toString().replace(" ", "%20"); } }
2,114
0.498399
0.479189
68
26.558823
17.86994
71
false
false
0
0
0
0
0
0
0.485294
false
false
2
6bfe76305b2115bd2bce6acedc1637bc4abdf86c
13,967,233,662,921
2b2f5fbf6fe383e42f770a905bb2f4f836ca9145
/app/src/main/java/com/videolibrary/puhser/activity/LiveNoticeActivity.java
dcbbe1fed4cf2794dad386f42a47abb9023a4e87
[ "Apache-2.0" ]
permissive
ybx945ybx/yhy
https://github.com/ybx945ybx/yhy
8426e918be0fc234bc32992ba497815ee41fca68
1eaefbff5654d5d9a809a812de35adb103857486
refs/heads/master
2020-04-23T19:42:23.225000
2019-02-19T05:59:01
2019-02-19T05:59:01
171,414,121
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.videolibrary.puhser.activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.quanyan.base.BaseActivity; import com.quanyan.base.view.BaseNavView; import com.quanyan.yhy.R; import com.videolibrary.utils.IntentUtil; import com.yhy.common.utils.SPUtils; /** * Created with Android Studio. * Title:LiveNoticeActivity * Description:直播公告 * Copyright:Copyright (c) 2015 * Company:quanyan * Author:邓明佳 * Date:2016/8/26 * Time:9:33 * Version 1.0 */ public class LiveNoticeActivity extends BaseActivity implements View.OnClickListener { BaseNavView navView; private String notice; private String defaultNotice; EditText mEdittext; TextView mWordCounts; TextView mFinish; @Override protected void initView(Bundle savedInstanceState) { mEdittext = (EditText) findViewById(R.id.ac_live_notice_edit); mWordCounts = (TextView) findViewById(R.id.ac_live_notice_words_count); mFinish = (TextView) findViewById(R.id.ac_live_notice_finish); initListener(); initData(); } private void initData() { defaultNotice = getString(R.string.user_live_notice, SPUtils.getNickName(this)); notice = getIntent().getStringExtra("notice"); mEdittext.setHint(defaultNotice); mEdittext.setText(notice); navView.setTitleText("直播公告"); } private void initListener() { mEdittext.addTextChangedListener(mTextWatcher); mFinish.setOnClickListener(this); } TextWatcher mTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { notice = s.toString(); mWordCounts.setText(String.valueOf(100 - mEdittext.getText().toString().length())); } }; @Override public View onLoadContentView() { return LayoutInflater.from(this).inflate(R.layout.ac_live_notice, null); } @Override public View onLoadNavView() { return navView = new BaseNavView(this); } @Override public boolean isTopCover() { return false; } @Override public void onClick(View v) { int id = v.getId(); if (id == mFinish.getId()) { Intent intent = new Intent(); intent.putExtra(IntentUtil.BUNDLE_NOTICE, TextUtils.isEmpty(notice) ? defaultNotice : notice); setResult(RESULT_OK, intent); finish(); } } }
UTF-8
Java
2,921
java
LiveNoticeActivity.java
Java
[ { "context": "t:Copyright (c) 2015\n * Company:quanyan\n * Author:邓明佳\n * Date:2016/8/26\n * Time:9:33\n * Version 1.0\n */", "end": 655, "score": 0.999804675579071, "start": 652, "tag": "NAME", "value": "邓明佳" } ]
null
[]
package com.videolibrary.puhser.activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.quanyan.base.BaseActivity; import com.quanyan.base.view.BaseNavView; import com.quanyan.yhy.R; import com.videolibrary.utils.IntentUtil; import com.yhy.common.utils.SPUtils; /** * Created with Android Studio. * Title:LiveNoticeActivity * Description:直播公告 * Copyright:Copyright (c) 2015 * Company:quanyan * Author:邓明佳 * Date:2016/8/26 * Time:9:33 * Version 1.0 */ public class LiveNoticeActivity extends BaseActivity implements View.OnClickListener { BaseNavView navView; private String notice; private String defaultNotice; EditText mEdittext; TextView mWordCounts; TextView mFinish; @Override protected void initView(Bundle savedInstanceState) { mEdittext = (EditText) findViewById(R.id.ac_live_notice_edit); mWordCounts = (TextView) findViewById(R.id.ac_live_notice_words_count); mFinish = (TextView) findViewById(R.id.ac_live_notice_finish); initListener(); initData(); } private void initData() { defaultNotice = getString(R.string.user_live_notice, SPUtils.getNickName(this)); notice = getIntent().getStringExtra("notice"); mEdittext.setHint(defaultNotice); mEdittext.setText(notice); navView.setTitleText("直播公告"); } private void initListener() { mEdittext.addTextChangedListener(mTextWatcher); mFinish.setOnClickListener(this); } TextWatcher mTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { notice = s.toString(); mWordCounts.setText(String.valueOf(100 - mEdittext.getText().toString().length())); } }; @Override public View onLoadContentView() { return LayoutInflater.from(this).inflate(R.layout.ac_live_notice, null); } @Override public View onLoadNavView() { return navView = new BaseNavView(this); } @Override public boolean isTopCover() { return false; } @Override public void onClick(View v) { int id = v.getId(); if (id == mFinish.getId()) { Intent intent = new Intent(); intent.putExtra(IntentUtil.BUNDLE_NOTICE, TextUtils.isEmpty(notice) ? defaultNotice : notice); setResult(RESULT_OK, intent); finish(); } } }
2,921
0.669541
0.662987
103
27.145632
24.275286
106
false
false
0
0
0
0
0
0
0.524272
false
false
2
07308ebc8c32a41d4eebc9954f7d2e3e314417b4
28,346,784,172,691
e71ea13673150053f9cdc09faa7699aebeb09e41
/src/fr/iutvalence/java/mp/clickToShoot/Target.java
407cfbc0b25f28ac466759c60a8fc9e96d6ab84e
[]
no_license
guillaumerosado/iutvalence-java-mp-2013-2014-ie2-p5
https://github.com/guillaumerosado/iutvalence-java-mp-2013-2014-ie2-p5
8cbf3e6c2b3cd2563423effb1d18caa29948787f
f5e98810cb9988ee9fb83c90d0af9c133a69c654
refs/heads/master
2021-01-18T17:15:30.363000
2013-12-10T16:35:34
2013-12-10T16:35:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.iutvalence.java.mp.clickToShoot; import fr.iutvalence.java.mp.clickToShoot.Position; /** * This class is the model of a target * * @author rosadog */ public class Target { /** * Default value of points */ public static final int DEFAULT_POINTS = 100; /** * Default malus value of points */ public static final int DEFAULT_MALUS_POINTS = -50; /** * The position of the target */ private Position position; /** * The amount of point of a target */ private int points; /** * Creation of a target with a default score at a given position * @param position the Position of the target */ public Target(Position position) { this.points = Target.DEFAULT_POINTS; this.position = position; } /** * Get points given by the target * * @return The points */ public int getPoints() { return this.points; } /** * Return the position * * @return position */ public Position getPosition() { return this.position; } }
UTF-8
Java
1,138
java
Target.java
Java
[ { "context": "This class is the model of a target\n * \n * @author rosadog\n */\npublic class Target\n{\n /**\n * Default ", "end": 163, "score": 0.9992469549179077, "start": 156, "tag": "USERNAME", "value": "rosadog" } ]
null
[]
package fr.iutvalence.java.mp.clickToShoot; import fr.iutvalence.java.mp.clickToShoot.Position; /** * This class is the model of a target * * @author rosadog */ public class Target { /** * Default value of points */ public static final int DEFAULT_POINTS = 100; /** * Default malus value of points */ public static final int DEFAULT_MALUS_POINTS = -50; /** * The position of the target */ private Position position; /** * The amount of point of a target */ private int points; /** * Creation of a target with a default score at a given position * @param position the Position of the target */ public Target(Position position) { this.points = Target.DEFAULT_POINTS; this.position = position; } /** * Get points given by the target * * @return The points */ public int getPoints() { return this.points; } /** * Return the position * * @return position */ public Position getPosition() { return this.position; } }
1,138
0.57645
0.572056
62
17.354839
17.202866
68
false
false
0
0
0
0
0
0
0.16129
false
false
2
f72f4ae6ac6dc24632ae190432fa77db23e9676e
26,869,315,422,489
69d527b84d3d4783385f5df2544919c10189322d
/src/main/java/com/spring/quartz/springquartz/myjob/CheckStatusTask2.java
a52dc2841f8e6e18b34d713aec42d7987d7860bc
[]
no_license
eiven-xxw/springquartz
https://github.com/eiven-xxw/springquartz
2599ebd2323fc41b6ee532d709dfed18837400cf
6a60ac0e0383d9b46cabb446e3e22ed573ee7a6e
refs/heads/master
2020-03-12T10:09:14.417000
2018-04-22T12:54:22
2018-04-22T12:54:22
130,567,155
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spring.quartz.springquartz.myjob; import org.jboss.logging.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CheckStatusTask2 implements Job { private Logger log = Logger.getLogger(CheckStatusTask2.class); public void execute(JobExecutionContext context) throws JobExecutionException { log.info("===============checkStatus2 开始=============="); } }
UTF-8
Java
465
java
CheckStatusTask2.java
Java
[]
null
[]
package com.spring.quartz.springquartz.myjob; import org.jboss.logging.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CheckStatusTask2 implements Job { private Logger log = Logger.getLogger(CheckStatusTask2.class); public void execute(JobExecutionContext context) throws JobExecutionException { log.info("===============checkStatus2 开始=============="); } }
465
0.731019
0.724512
18
24.611111
27.168484
83
false
false
0
0
0
0
0
0
0.388889
false
false
2
590effe4d69f3fabf90633d16b88c6f34cdeff8b
31,765,578,141,753
d7ef64743023f14b5f2e741e071446ddb24fccb2
/app/src/main/java/uci/mswe/swe246p/todofragments/TodoListActivity.java
9715b70098b801111526db75596cbb4044d45494
[]
no_license
Joxon/swe246p-ex5-fragments
https://github.com/Joxon/swe246p-ex5-fragments
60ae4abd4f4ed79f55ab25977f5984264f8a5362
25966d0f7226e6737f392c2443322bc309cd5e2a
refs/heads/master
2020-09-21T22:53:24.555000
2019-12-11T09:26:34
2019-12-11T09:26:34
224,961,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uci.mswe.swe246p.todofragments; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.Objects; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.RecyclerView; public class TodoListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_todolist); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { Intent fromTodoListsAdapter = getIntent(); String listId = fromTodoListsAdapter.getStringExtra(TodoListFragment.ARG_LIST_ID); Bundle toListFragment = new Bundle(); toListFragment.putString(TodoListFragment.ARG_LIST_ID, listId); TodoListFragment listFragment = new TodoListFragment(); listFragment.setArguments(toListFragment); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_todolist_container, listFragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); // NavUtils.navigateUpTo(this, new Intent(this, TodoListsActivity.class)); return true; } return super.onOptionsItemSelected(item); } public void onClickAddItem(View view) { final EditText input = new EditText(this); new AlertDialog.Builder(this) .setTitle(getString(R.string.dialog_add_item_title)) .setMessage(getString(R.string.dialog_add_item_message)) .setView(input) .setPositiveButton(getString(R.string.dialog_positive_button_text), (dialog, whichButton) -> { String content = input.getText().toString(); if (content.isEmpty()) { Toast.makeText(this, R.string.dialog_add_item_content_empty, Toast.LENGTH_SHORT).show(); return; } TodoList listCurrent = Data.getListCurrent(); listCurrent.addItem(new TodoItem(content)); RecyclerView listView = findViewById(R.id.fragment_todolist); assert listView != null; Objects.requireNonNull(listView.getAdapter()).notifyDataSetChanged(); }) .setNegativeButton(getString(R.string.dialog_negative_button_text), (dialog, whichButton) -> { // Do nothing. }).show(); } }
UTF-8
Java
2,865
java
TodoListActivity.java
Java
[]
null
[]
package uci.mswe.swe246p.todofragments; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.Objects; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.RecyclerView; public class TodoListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_todolist); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { Intent fromTodoListsAdapter = getIntent(); String listId = fromTodoListsAdapter.getStringExtra(TodoListFragment.ARG_LIST_ID); Bundle toListFragment = new Bundle(); toListFragment.putString(TodoListFragment.ARG_LIST_ID, listId); TodoListFragment listFragment = new TodoListFragment(); listFragment.setArguments(toListFragment); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_todolist_container, listFragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); // NavUtils.navigateUpTo(this, new Intent(this, TodoListsActivity.class)); return true; } return super.onOptionsItemSelected(item); } public void onClickAddItem(View view) { final EditText input = new EditText(this); new AlertDialog.Builder(this) .setTitle(getString(R.string.dialog_add_item_title)) .setMessage(getString(R.string.dialog_add_item_message)) .setView(input) .setPositiveButton(getString(R.string.dialog_positive_button_text), (dialog, whichButton) -> { String content = input.getText().toString(); if (content.isEmpty()) { Toast.makeText(this, R.string.dialog_add_item_content_empty, Toast.LENGTH_SHORT).show(); return; } TodoList listCurrent = Data.getListCurrent(); listCurrent.addItem(new TodoItem(content)); RecyclerView listView = findViewById(R.id.fragment_todolist); assert listView != null; Objects.requireNonNull(listView.getAdapter()).notifyDataSetChanged(); }) .setNegativeButton(getString(R.string.dialog_negative_button_text), (dialog, whichButton) -> { // Do nothing. }).show(); } }
2,865
0.704014
0.702967
82
33.939026
26.086792
102
false
false
0
0
0
0
0
0
0.634146
false
false
2
16dacf16477eee3cbd8b7541d307b120481944ea
20,753,281,988,929
480006688ecb543bf58aa35aa9d40350253410a3
/src/main/java/com/InfinityRaider/AgriCraft/utility/CrossCropHelper.java
cd2f54bb6d4c823021b4d722d6852a3cca9fcb36
[ "MIT" ]
permissive
Mazdallier/AgriCraft
https://github.com/Mazdallier/AgriCraft
96258a43b81ebdbd2663831006c6392ec2b56da1
96e3505cc4b9352609d58f0ea4842f261970597f
refs/heads/master
2021-01-17T12:03:58.350000
2014-11-20T14:57:29
2014-11-20T14:57:29
26,917,342
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.InfinityRaider.AgriCraft.utility; import com.InfinityRaider.AgriCraft.handler.ConfigurationHandler; import com.InfinityRaider.AgriCraft.tileentity.TileEntityCrop; import net.minecraft.item.Item; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemStack; import java.util.ArrayList; public abstract class CrossCropHelper { private static ItemStack[] mutations; private static ItemStack[] parents1; private static ItemStack[] parents2; public static void init() { //Read mutations & initialize the mutation arrays setMutations(IOHelper.getLinesArrayFromData(ConfigurationHandler.readMutationData())); LogHelper.info("Registered Mutations:"); for(int i=0;i< mutations.length;i++) { String mutation = mutations[i].getItem()!=null?(Item.itemRegistry.getNameForObject(mutations[i].getItem())+':'+mutations[i].getItemDamage()):"null"; String parent1 = parents1[i].getItem()!=null?(Item.itemRegistry.getNameForObject(parents1[i].getItem()))+':'+parents1[i].getItemDamage():"null"; String parent2 = parents2[i].getItem()!=null?(Item.itemRegistry.getNameForObject(parents2[i].getItem()))+':'+parents2[i].getItemDamage():"null"; LogHelper.info(mutation + " = " + parent1 + " + " + parent2); } } //initializes the mutations arrays private static void setMutations(String[] data) { mutations = new ItemStack[data.length]; parents1 = new ItemStack[data.length]; parents2 = new ItemStack[data.length]; for(int i=0;i<data.length;i++) { mutations[i] = IOHelper.getSeedStack(IOHelper.correctSeedName(data[i].substring(0,data[i].indexOf('=')))); parents1[i] = IOHelper.getSeedStack(IOHelper.correctSeedName(data[i].substring(data[i].indexOf('=')+1,data[i].indexOf('+')))); parents2[i] = IOHelper.getSeedStack(IOHelper.correctSeedName(data[i].substring(data[i].indexOf('+')+1))); } } //gets all the possible crossovers public static ItemStack[] getCrossOvers(TileEntityCrop[] crops) { TileEntityCrop[] parents = CrossCropHelper.getParents(crops); ArrayList<ItemStack> list = new ArrayList<ItemStack>(); switch (parents.length) { case 2: list.addAll(CrossCropHelper.getMutation(parents[0], parents[1])); break; case 3: list.addAll(CrossCropHelper.getMutation(parents[0], parents[1])); list.addAll(CrossCropHelper.getMutation(parents[0], parents[2])); list.addAll(CrossCropHelper.getMutation(parents[1], parents[2])); break; case 4: list.addAll(CrossCropHelper.getMutation(parents[0], parents[1])); list.addAll(CrossCropHelper.getMutation(parents[0], parents[2])); list.addAll(CrossCropHelper.getMutation(parents[0], parents[3])); list.addAll(CrossCropHelper.getMutation(parents[1], parents[2])); list.addAll(CrossCropHelper.getMutation(parents[1], parents[3])); list.addAll(CrossCropHelper.getMutation(parents[2], parents[3])); break; } return cleanItemStackArray(list.toArray(new ItemStack[list.size()])); } //gets an array of all the possible parents from the array containing all the neighbouring crops private static TileEntityCrop[] getParents(TileEntityCrop[] input) { ArrayList<TileEntityCrop> list = new ArrayList<TileEntityCrop>(); for(TileEntityCrop crop:input) { if (crop != null && crop.isMature()) { list.add(crop); } } return list.toArray(new TileEntityCrop[list.size()]); } //finds the product of two parents private static ArrayList<ItemStack> getMutation(TileEntityCrop parent1, TileEntityCrop parent2) { ItemSeeds seed1 = (ItemSeeds) parent1.seed; ItemSeeds seed2 = (ItemSeeds) parent2.seed; int meta1 = parent1.seedMeta; int meta2 = parent2.seedMeta; ArrayList<ItemStack> list = new ArrayList<ItemStack>(); for(int i=0;i<mutations.length;i++) { if((seed1==parents1[i].getItem() && seed2==parents2[i].getItem()) && (meta1==parents1[i].getItemDamage() && meta2==parents2[i].getItemDamage())) { list.add(mutations[i]); } if((seed1==parents2[i].getItem() && seed2==parents1[i].getItem()) && (meta1==parents2[i].getItemDamage() && meta2==parents1[i].getItemDamage())) { list.add(mutations[i]); } } return list; } //logic for stat inheritance public static int[] getStats(TileEntityCrop[] input) { int[] output = new int[3]; TileEntityCrop[] neighbors = getParents(input); int size = neighbors.length; int[] growth = new int[size]; int[] gain = new int[size]; int[] strength = new int[size]; for(int i=0;i<size;i++) { growth[i] = neighbors[i].growth; gain[i] = neighbors[i].gain; strength[i] = neighbors[i].strength; } int meanGrowth = getMean(growth); int meanGain = getMean(gain); int meanStrength = getMean(strength); output[0] = getGain(meanGrowth, size); output[1] = getGain(meanGain, size); output[2] = getGain(meanStrength, size); for(int i=0;i<output.length;i++) { output[i] = output[i]>10?10:output[i]; } return output; } //returns the mean value of an int array private static int getMean(int[] input) { int mean = 0; if(input.length>0) { for (int nr : input) { mean = mean + nr; } mean = Math.round(((float) mean) / ((float) input.length)); } return mean; } //returns the added value for a statistic private static int getGain(int input, int neighbors) { return input+ (int) Math.round(Math.abs(neighbors-2)*Math.random()); } //removes null instance from an ItemSeeds array private static ItemStack[] cleanItemStackArray(ItemStack[] input) { ArrayList<ItemStack> list = new ArrayList<ItemStack>(); for(ItemStack seed:input) { if (seed != null) { list.add(seed); } } return list.toArray(new ItemStack[list.size()]); } //public methods to read data from the mutations and parents arrays //gets all the mutations public static ItemStack[] getMutations() { return mutations.clone(); } //gets all the parents public static ItemStack[][] getParents() { ItemStack[][] parents = new ItemStack[mutations.length][2]; for(int i=0;i<mutations.length;i++) { parents[i][0] = parents1[i]; parents[i][1] = parents2[i]; } return parents; } //gets all the crops this crop can mutate to //the mutation at a certain index corresponds to the co parent at the index of the array returned by getCoParents(ItemStack stack) public static ItemStack[] getMutations(ItemStack stack) { ArrayList<ItemStack> list = new ArrayList<ItemStack>(); if(stack.getItem() instanceof ItemSeeds) { for (int i = 0; i < parents1.length; i++) { if (parents2[i].getItem() == stack.getItem() && parents2[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(mutations[i].getItem(), 1, mutations[i].getItemDamage())); } if (parents1[i].getItem() == stack.getItem() && parents1[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(mutations[i].getItem(), 1, mutations[i].getItemDamage())); } } } return list.toArray(new ItemStack[list.size()]); } //gets all the other parents this crop can mutate with //the parent at a certain index corresponds to the mutation at the index of the array returned by getMutations(ItemStack stack) public static ItemStack[] getCoParents(ItemStack stack) { ArrayList<ItemStack> list = new ArrayList<ItemStack>(); if(stack.getItem() instanceof ItemSeeds) { for (int i = 0; i < parents1.length; i++) { if (parents2[i].getItem() == stack.getItem() && parents2[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(parents1[i].getItem(), 1, parents1[i].getItemDamage())); } if (parents1[i].getItem() == stack.getItem() && parents1[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(parents2[i].getItem(), 1, parents2[i].getItemDamage())); } } } return list.toArray(new ItemStack[list.size()]); } //gets the parents this crop mutates from public static ItemStack[][] getParents(ItemStack stack) { ArrayList<ItemStack[]> list = new ArrayList<ItemStack[]>(); if(stack.getItem() instanceof ItemSeeds) { for(int i=0;i<mutations.length;i++) { if(mutations[i].getItem() == stack.getItem() && mutations[i].getItemDamage() == stack.getItemDamage()) { ItemStack[] entry = {new ItemStack(parents1[i].getItem(), 1, parents1[i].getItemDamage()), new ItemStack(parents2[i].getItem(), 1, parents2[i].getItemDamage())}; list.add(entry); } } } ItemStack[][] result = new ItemStack[list.size()][2]; for(int i=0;i<list.size();i++) { result[i] = list.get(i); } return result; } }
UTF-8
Java
9,804
java
CrossCropHelper.java
Java
[]
null
[]
package com.InfinityRaider.AgriCraft.utility; import com.InfinityRaider.AgriCraft.handler.ConfigurationHandler; import com.InfinityRaider.AgriCraft.tileentity.TileEntityCrop; import net.minecraft.item.Item; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemStack; import java.util.ArrayList; public abstract class CrossCropHelper { private static ItemStack[] mutations; private static ItemStack[] parents1; private static ItemStack[] parents2; public static void init() { //Read mutations & initialize the mutation arrays setMutations(IOHelper.getLinesArrayFromData(ConfigurationHandler.readMutationData())); LogHelper.info("Registered Mutations:"); for(int i=0;i< mutations.length;i++) { String mutation = mutations[i].getItem()!=null?(Item.itemRegistry.getNameForObject(mutations[i].getItem())+':'+mutations[i].getItemDamage()):"null"; String parent1 = parents1[i].getItem()!=null?(Item.itemRegistry.getNameForObject(parents1[i].getItem()))+':'+parents1[i].getItemDamage():"null"; String parent2 = parents2[i].getItem()!=null?(Item.itemRegistry.getNameForObject(parents2[i].getItem()))+':'+parents2[i].getItemDamage():"null"; LogHelper.info(mutation + " = " + parent1 + " + " + parent2); } } //initializes the mutations arrays private static void setMutations(String[] data) { mutations = new ItemStack[data.length]; parents1 = new ItemStack[data.length]; parents2 = new ItemStack[data.length]; for(int i=0;i<data.length;i++) { mutations[i] = IOHelper.getSeedStack(IOHelper.correctSeedName(data[i].substring(0,data[i].indexOf('=')))); parents1[i] = IOHelper.getSeedStack(IOHelper.correctSeedName(data[i].substring(data[i].indexOf('=')+1,data[i].indexOf('+')))); parents2[i] = IOHelper.getSeedStack(IOHelper.correctSeedName(data[i].substring(data[i].indexOf('+')+1))); } } //gets all the possible crossovers public static ItemStack[] getCrossOvers(TileEntityCrop[] crops) { TileEntityCrop[] parents = CrossCropHelper.getParents(crops); ArrayList<ItemStack> list = new ArrayList<ItemStack>(); switch (parents.length) { case 2: list.addAll(CrossCropHelper.getMutation(parents[0], parents[1])); break; case 3: list.addAll(CrossCropHelper.getMutation(parents[0], parents[1])); list.addAll(CrossCropHelper.getMutation(parents[0], parents[2])); list.addAll(CrossCropHelper.getMutation(parents[1], parents[2])); break; case 4: list.addAll(CrossCropHelper.getMutation(parents[0], parents[1])); list.addAll(CrossCropHelper.getMutation(parents[0], parents[2])); list.addAll(CrossCropHelper.getMutation(parents[0], parents[3])); list.addAll(CrossCropHelper.getMutation(parents[1], parents[2])); list.addAll(CrossCropHelper.getMutation(parents[1], parents[3])); list.addAll(CrossCropHelper.getMutation(parents[2], parents[3])); break; } return cleanItemStackArray(list.toArray(new ItemStack[list.size()])); } //gets an array of all the possible parents from the array containing all the neighbouring crops private static TileEntityCrop[] getParents(TileEntityCrop[] input) { ArrayList<TileEntityCrop> list = new ArrayList<TileEntityCrop>(); for(TileEntityCrop crop:input) { if (crop != null && crop.isMature()) { list.add(crop); } } return list.toArray(new TileEntityCrop[list.size()]); } //finds the product of two parents private static ArrayList<ItemStack> getMutation(TileEntityCrop parent1, TileEntityCrop parent2) { ItemSeeds seed1 = (ItemSeeds) parent1.seed; ItemSeeds seed2 = (ItemSeeds) parent2.seed; int meta1 = parent1.seedMeta; int meta2 = parent2.seedMeta; ArrayList<ItemStack> list = new ArrayList<ItemStack>(); for(int i=0;i<mutations.length;i++) { if((seed1==parents1[i].getItem() && seed2==parents2[i].getItem()) && (meta1==parents1[i].getItemDamage() && meta2==parents2[i].getItemDamage())) { list.add(mutations[i]); } if((seed1==parents2[i].getItem() && seed2==parents1[i].getItem()) && (meta1==parents2[i].getItemDamage() && meta2==parents1[i].getItemDamage())) { list.add(mutations[i]); } } return list; } //logic for stat inheritance public static int[] getStats(TileEntityCrop[] input) { int[] output = new int[3]; TileEntityCrop[] neighbors = getParents(input); int size = neighbors.length; int[] growth = new int[size]; int[] gain = new int[size]; int[] strength = new int[size]; for(int i=0;i<size;i++) { growth[i] = neighbors[i].growth; gain[i] = neighbors[i].gain; strength[i] = neighbors[i].strength; } int meanGrowth = getMean(growth); int meanGain = getMean(gain); int meanStrength = getMean(strength); output[0] = getGain(meanGrowth, size); output[1] = getGain(meanGain, size); output[2] = getGain(meanStrength, size); for(int i=0;i<output.length;i++) { output[i] = output[i]>10?10:output[i]; } return output; } //returns the mean value of an int array private static int getMean(int[] input) { int mean = 0; if(input.length>0) { for (int nr : input) { mean = mean + nr; } mean = Math.round(((float) mean) / ((float) input.length)); } return mean; } //returns the added value for a statistic private static int getGain(int input, int neighbors) { return input+ (int) Math.round(Math.abs(neighbors-2)*Math.random()); } //removes null instance from an ItemSeeds array private static ItemStack[] cleanItemStackArray(ItemStack[] input) { ArrayList<ItemStack> list = new ArrayList<ItemStack>(); for(ItemStack seed:input) { if (seed != null) { list.add(seed); } } return list.toArray(new ItemStack[list.size()]); } //public methods to read data from the mutations and parents arrays //gets all the mutations public static ItemStack[] getMutations() { return mutations.clone(); } //gets all the parents public static ItemStack[][] getParents() { ItemStack[][] parents = new ItemStack[mutations.length][2]; for(int i=0;i<mutations.length;i++) { parents[i][0] = parents1[i]; parents[i][1] = parents2[i]; } return parents; } //gets all the crops this crop can mutate to //the mutation at a certain index corresponds to the co parent at the index of the array returned by getCoParents(ItemStack stack) public static ItemStack[] getMutations(ItemStack stack) { ArrayList<ItemStack> list = new ArrayList<ItemStack>(); if(stack.getItem() instanceof ItemSeeds) { for (int i = 0; i < parents1.length; i++) { if (parents2[i].getItem() == stack.getItem() && parents2[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(mutations[i].getItem(), 1, mutations[i].getItemDamage())); } if (parents1[i].getItem() == stack.getItem() && parents1[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(mutations[i].getItem(), 1, mutations[i].getItemDamage())); } } } return list.toArray(new ItemStack[list.size()]); } //gets all the other parents this crop can mutate with //the parent at a certain index corresponds to the mutation at the index of the array returned by getMutations(ItemStack stack) public static ItemStack[] getCoParents(ItemStack stack) { ArrayList<ItemStack> list = new ArrayList<ItemStack>(); if(stack.getItem() instanceof ItemSeeds) { for (int i = 0; i < parents1.length; i++) { if (parents2[i].getItem() == stack.getItem() && parents2[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(parents1[i].getItem(), 1, parents1[i].getItemDamage())); } if (parents1[i].getItem() == stack.getItem() && parents1[i].getItemDamage() == stack.getItemDamage()) { list.add(new ItemStack(parents2[i].getItem(), 1, parents2[i].getItemDamage())); } } } return list.toArray(new ItemStack[list.size()]); } //gets the parents this crop mutates from public static ItemStack[][] getParents(ItemStack stack) { ArrayList<ItemStack[]> list = new ArrayList<ItemStack[]>(); if(stack.getItem() instanceof ItemSeeds) { for(int i=0;i<mutations.length;i++) { if(mutations[i].getItem() == stack.getItem() && mutations[i].getItemDamage() == stack.getItemDamage()) { ItemStack[] entry = {new ItemStack(parents1[i].getItem(), 1, parents1[i].getItemDamage()), new ItemStack(parents2[i].getItem(), 1, parents2[i].getItemDamage())}; list.add(entry); } } } ItemStack[][] result = new ItemStack[list.size()][2]; for(int i=0;i<list.size();i++) { result[i] = list.get(i); } return result; } }
9,804
0.603733
0.591595
218
43.972477
37.075539
181
false
false
0
0
0
0
0
0
0.655963
false
false
2
b762cd9abbcd561f54b2482112be8c22b3a08a7f
23,106,924,104,140
153d866484a23801edec2c0a27289bd2e9342538
/src/com/lqlsoftware/ATGUIGU/dao/iAccountMapper.java
ca25427b6a4839b11f5ad73a749014a9670a1e9e
[]
no_license
Lqlsoftware/BookStore
https://github.com/Lqlsoftware/BookStore
9f57545ad9b63d37e68d59181fa024dd3eba1860
b4c08d2ff5ba34af236cb18499489f04f8f0e071
refs/heads/master
2021-03-16T07:40:17.429000
2018-06-21T04:32:30
2018-06-21T04:32:30
96,394,189
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lqlsoftware.ATGUIGU.dao; import com.lqlsoftware.ATGUIGU.entity.Account; /** * Created by robinlu on 2017/5/8. */ public interface iAccountMapper { public Account getAccountById(String account_id); public Account getAccountByUserId(String user_id); public void updateAccount(Account account); }
UTF-8
Java
325
java
iAccountMapper.java
Java
[ { "context": "oftware.ATGUIGU.entity.Account;\n\n/**\n * Created by robinlu on 2017/5/8.\n */\npublic interface iAccountMapper ", "end": 111, "score": 0.9996418356895447, "start": 104, "tag": "USERNAME", "value": "robinlu" } ]
null
[]
package com.lqlsoftware.ATGUIGU.dao; import com.lqlsoftware.ATGUIGU.entity.Account; /** * Created by robinlu on 2017/5/8. */ public interface iAccountMapper { public Account getAccountById(String account_id); public Account getAccountByUserId(String user_id); public void updateAccount(Account account); }
325
0.756923
0.738462
15
20.666666
21.913973
54
false
false
0
0
0
0
0
0
0.333333
false
false
2
0147ad82b5bf3a93f2e50f0c48573d30b70cae00
36,266,703,872,905
a9843027711ff2ac36bda9bb87c28a0bd06ee10e
/server/src/java/org/jppf/server/nio/nodeserver/async/AsyncJobScheduler.java
1780fc3bc3d005f5549863347a850ac306f8b6af
[ "Apache-2.0" ]
permissive
jppf-grid/JPPF
https://github.com/jppf-grid/JPPF
1da761712173029b138f273f965acb8bb295580b
f7d0ddfb2f4f333cecdf62d6752d650175ca9f35
refs/heads/master
2022-06-10T16:24:05.882000
2021-11-26T06:35:21
2021-11-26T06:35:21
129,232,623
54
15
Apache-2.0
false
2021-11-20T07:25:47
2018-04-12T10:13:36
2021-11-15T09:29:19
2021-11-20T07:25:47
463,932
49
13
8
Java
false
false
/* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.org * * 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.jppf.server.nio.nodeserver.async; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import org.jppf.execute.ExecutorStatus; import org.jppf.load.balancer.*; import org.jppf.load.balancer.spi.JPPFBundlerFactory; import org.jppf.management.*; import org.jppf.node.policy.ExecutionPolicy; import org.jppf.node.protocol.*; import org.jppf.server.nio.nodeserver.*; import org.jppf.server.protocol.*; import org.jppf.server.queue.*; import org.jppf.utils.*; import org.jppf.utils.collections.*; import org.jppf.utils.configuration.JPPFProperties; import org.jppf.utils.stats.JPPFStatistics; import org.slf4j.*; /** * This class ensures that idle nodes get assigned pending tasks in the queue. */ public class AsyncJobScheduler extends AbstractAsyncJobScheduler { /** * Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(AsyncJobScheduler.class); /** * Determines whether DEBUG logging level is enabled. */ private static final boolean debugEnabled = log.isDebugEnabled(); /** * Initialize this task queue checker with the specified node server. * @param server the node server. * @param queue the reference queue to use. * @param stats reference to the statistics. * @param bundlerFactory the load-balancer factory. */ AsyncJobScheduler(final AsyncNodeNioServer server, final JPPFPriorityQueue queue, final JPPFStatistics stats, final JPPFBundlerFactory bundlerFactory) { super(server, queue, stats, bundlerFactory); } /** * Perform the assignment of tasks. */ @Override public void run() { if (debugEnabled) log.debug("starting {}", getClass().getSimpleName()); reservationHandler = server.getNodeReservationHandler(); try { while (!isStopped()) { if (!dispatch()) goToSleep(1000L); } } catch (final Throwable t) { log.error("error in driver dispatch loop", t); } } /** * Perform the assignment of jobs to nodes. * @return true if a job was dispatched, false otherwise. */ private boolean dispatch() { try { queue.getBroadcastManager().processPendingBroadcasts(); if (queue.isEmpty()) return false; BaseNodeContext channel = null; ServerTaskBundleNode nodeBundle = null; synchronized(idleChannels) { if (idleChannels.isEmpty()) return false; final List<ServerJob> allJobs = queue.getAllJobsFromPriorityMap(); if (debugEnabled) log.debug("there are {} idle channels and {} jobs in the queue", idleChannels.size(), allJobs.size()); try { final Iterator<ServerJob> jobIterator = allJobs.iterator(); while ((channel == null) && jobIterator.hasNext() && !idleChannels.isEmpty()) { final ServerJob job = jobIterator.next(); if (debugEnabled) log.debug("checking {}", job); if (!performJobChecks(job)) continue; channel = findIdleChannelIndex(job); if (channel == null) continue; synchronized(channel.getMonitor()) { if (job.getSLA().getDesiredNodeConfiguration() != null) { final String readyJobUUID = reservationHandler.getReadyJobUUID(channel); final String pendingJobUUID = reservationHandler.getPendingJobUUID(channel); if ((pendingJobUUID == null) && (readyJobUUID == null)) { if (debugEnabled) log.debug("reserving {} with {}", job, channel); reservationHandler.doReservation(job, channel); channel = null; continue; } } if (channel.getCurrentNbJobs() >= channel.getMaxJobs()) removeIdleChannel(channel); if (!channel.isEnabled()) { if (debugEnabled) log.debug("channel is disabled [}", channel); channel = null; continue; } nodeBundle = prepareJobDispatch(channel, job); if (debugEnabled) log.debug("prepareJobDispatch() returned {}", nodeBundle); if (nodeBundle != null) { try { dispatchJobToChannel(channel, nodeBundle); return true; } catch (final Exception e) { log.error("{}\nchannel={}\njob={}\nstack trace: {}", ExceptionUtils.getMessage(e), channel, nodeBundle, ExceptionUtils.getStackTrace(e)); channel.setClosed(false); channel.handleException(e); } } } } if (debugEnabled) log.debug((channel == null) ? "no channel found for bundle " : "channel found for bundle " + channel); } catch(final Exception e) { log.error("An error occurred while attempting to dispatch task bundles. This is most likely due to an error in the load balancer implementation.", e); } } } catch (final Exception e) { log.error("An error occurred while preparing for bundle creation and dispatching.", e); } return false; } /** * Prepare the specified job for the selected channel, after applying the load balancer to the job. * @param channel the node channel to prepare dispatch the job to. * @param selectedJob the job to dispatch. * @return the task bundle to dispatch to the specified node. */ private ServerTaskBundleNode prepareJobDispatch(final BaseNodeContext channel, final ServerJob selectedJob) { if (debugEnabled) log.debug("dispatching jobUuid=" + selectedJob.getUuid() + " to node " + channel + ", nodeUuid=" + channel.getConnectionUuid()); int size = 1; try { updateBundler(selectedJob.getJob(), channel); size = channel.getBundler().getBundleSize(); if (selectedJob.getSLA().getMaxDispatchSize() < size) size = selectedJob.getSLA().getMaxDispatchSize(); } catch (final Exception e) { log.error("Error in load balancer implementation, switching to 'manual' with a bundle size of 1", e); size = bundlerFactory.getFallbackBundler().getBundleSize(); } return selectedJob.isCancelled() ? null : queue.nextBundle(selectedJob, size, channel); } /** * Dispatch the specified job to the selected channel, after applying the load balancer to the job. * @param channel the node channel to dispatch the job to. * @param nodeBundle the job to dispatch. * @throws Exception if any error occurs. */ private static void dispatchJobToChannel(final BaseNodeContext channel, final ServerTaskBundleNode nodeBundle) throws Exception { if (debugEnabled) log.debug("dispatching {} tasks of job '{}' to node {}", nodeBundle.getTaskCount(), nodeBundle.getJob().getName(), channel.getUuid()); if (log.isTraceEnabled()) { final Set<Long> set = new TreeSet<>(); for (final ServerTask task: nodeBundle.getTaskList()) { final long id = task.getBundle().getId(); if (!set.contains(id)) set.add(id); } StringBuilder sb = new StringBuilder(); int count = 0; for (final long id: set) { if (count > 0) sb.append(", "); sb.append("ServerTaskBundleClient[id=").append(id).append(']'); count++; } log.trace("client bundles in dispatch: {}", sb); sb = new StringBuilder(); count = 0; for (final ServerTask task: nodeBundle.getTaskList()) { if (count > 0) sb.append(", "); sb.append(task.getPosition()); count++; } log.trace("tasks positions in dispatch: {}", sb); } synchronized(channel.getMonitor()) { final Future<?> future = channel.submit(nodeBundle); nodeBundle.jobDispatched(channel, future); } if (debugEnabled) log.debug("dispatched {} tasks of job '{}' to node {}", nodeBundle.getTaskCount(), nodeBundle.getJob().getName(), channel.getUuid()); } /** * Find a channel that can send the specified task bundle for execution. * @param job the bundle to execute. * @return the index of an available and acceptable channel, or -1 if no channel could be found. */ private BaseNodeContext findIdleChannelIndex(final ServerJob job) { if (debugEnabled) log.debug("checking {}", job); final JobSLA sla = job.getSLA(); final JPPFNodeConfigSpec spec = sla.getDesiredNodeConfiguration(); final TypedProperties desiredConfiguration = (spec == null) ? null : spec.getConfiguration(); List<BaseNodeContext> acceptableChannels = new ArrayList<>(idleChannels.size()); final List<BaseNodeContext> toRemove = new LinkedList<>(); Iterator<BaseNodeContext> nodeIterator = null; if (sla.getPreferencePolicy() != null) { final Set<BaseNodeContext> preferedChannels = filterPreferredNodes(job); if (preferedChannels.isEmpty()) return null; nodeIterator = preferedChannels.iterator(); } else nodeIterator = idleChannels.iterator(); while (nodeIterator.hasNext()) { final AsyncNodeContext channel = (AsyncNodeContext) nodeIterator.next(); synchronized(channel.getMonitor()) { if ((channel.getExecutionStatus() != ExecutorStatus.ACTIVE) || channel.isClosed() || !channel.isEnabled()) { if (debugEnabled) log.debug("channel is not opened: {}", channel); toRemove.add(channel); continue; } if (!channel.isActive() || !channel.isAcceptingNewJobs()) { if (debugEnabled) log.debug("node not accepting jobs: {}", channel); continue; } if (channel.isPeer() && (server.nodeConnectionHandler.getConnectedRealNodes() >= peerLoadBalanceThreshold)) { if (debugEnabled) log.debug("this driver has {} nodes and the threshold is {}", server.nodeConnectionHandler.getConnectedNodes(), peerLoadBalanceThreshold); continue; } if (channel.getCurrentNbJobs() >= channel.getMaxJobs()) { if (debugEnabled) log.debug("[currentNbJobs = {}] >= maxJobs = {}] for {}", channel.getCurrentNbJobs(), channel.getMaxJobs(), channel); continue; } if (!checkJobAgainstChannel(channel, job)) continue; if (job.getBroadcastUUID() != null && !job.getBroadcastUUID().equals(channel.getUuid())) continue; final JPPFSystemInformation info = channel.getSystemInformation(); if (channel.isPeer() && !disptachtoPeersWithoutNode) { if ((info != null) && (info.getJppf().getInt(PeerAttributesHandler.PEER_TOTAL_NODES, 0) <= 0)) { if (debugEnabled) log.debug("peer has no attached node: {}", channel.getUuid()); continue; } } if (!checkExecutionPolicy(channel, job, sla.getExecutionPolicy(), info, job.getNbChannels())) continue; if (!checkMaxNodeGroups(channel, job)) continue; final Collection<String> readyNodes = (spec == null) ? null : reservationHandler.getReadyNodes(job.getUuid()); if (debugEnabled) log.debug("jobUuid={}, readyNodes={}", job.getUuid(), readyNodes); if (!checkDesiredConfiguration(desiredConfiguration, channel, job, readyNodes, reservationHandler.getNbReservedNodes(job.getUuid()))) continue; if (channel.isLocal() && localNodeBiasEnabled) { // add a bias toward local node if (desiredConfiguration != null) continue; else return channel; } acceptableChannels.add(channel); } } if (!toRemove.isEmpty()) { for (final BaseNodeContext c: toRemove) removeIdleChannel(c); } if (!checkJobNotCancelled(job)) return null; if (!acceptableChannels.isEmpty() && (desiredConfiguration != null)) acceptableChannels = filterLowestDistances(job, acceptableChannels); return selectChannel(acceptableChannels); } /** * Select a single channle from a list of channels eligible for a job. * @param acceptableChannels the list of channels to select from. * @return an instance of {@link BaseNodeContext}, or {@code null} if the list is empty or no channel passes the selection criteria. */ private BaseNodeContext selectChannel(final List<BaseNodeContext> acceptableChannels) { if (acceptableChannels.isEmpty()) return null; final int size = acceptableChannels.size(); if (debugEnabled) log.debug("found {} acceptable channels", size); final BaseNodeContext channel = (size > 0) ? acceptableChannels.get(size > 1 ? random.nextInt(size) : 0) : null; return channel; } /** * * @param job the job to check. * @return {@code true} if the job can be scheduiled, {@code false} otherwise. */ private boolean performJobChecks(final ServerJob job) { final JobDependencySpec dependencySpec = job.getSLA().getDependencySpec(); //if (debugEnabled) log.debug("job graph node: {}", dependencyHandler.getGraph().getNode(dependencySpec.getId())); if ((dependencySpec.getId() != null) && !job.isJobGraphAlreadyHandled() && dependencySpec.hasDependency() && dependencyHandler.hasPendingDependencyOrCancelled(dependencySpec.getId())) { if (debugEnabled) log.debug("job dependency check false for {}", job); return false; } final JPPFNodeConfigSpec spec = job.getSLA().getDesiredNodeConfiguration(); if (spec != null) { if ((reservationHandler.getNbReservedNodes(job.getUuid()) >= job.getSLA().getMaxNodes()) && !reservationHandler.hasReadyNode(job.getUuid())) { if (debugEnabled) log.debug("node config check false for {}", job); return false; } } if ((job.getTaskGraph() != null) && !job.hasAvailableGraphNode()) { if (debugEnabled) log.debug("tasks graph check false for {}", job); return false; } if (!checkGridPolicy(job)) return false; return checkJobState(job); } /** * Check that the job did not already get through the specified channel (collision avoidance) and that the SLA's max driver depth is not reached. * @param channel the node to check. * @param job the job to check against. * @return {@code true} if the check succeeds, {@code false} otherwise. */ private boolean checkJobAgainstChannel(final AsyncNodeContext channel, final ServerJob job) { final List<String> uuidPath = job.getJob().getUuidPath().getList(); if (debugEnabled) log.debug("uuid path={}, node uuid={}", uuidPath, channel.getUuid()); final String driverUuid = server.getDriver().getUuid(); final int index = uuidPath.indexOf(driverUuid); if ((index >= 0) && (index != uuidPath.size() - 1)) log.warn("uuid path contains this driver's uuid {}: uuidPath={}", driverUuid, uuidPath); if (uuidPath.contains(channel.getUuid())) { if (debugEnabled) log.debug("bundle uuid path already contains node {} : uuidPath={}, nodeUuid={}", channel, uuidPath, channel.getUuid()); return false; } if (channel.isPeer() && (uuidPath.size() - 1 >= job.getSLA().getMaxDriverDepth())) { if (debugEnabled) log.debug("job [name={}, uuid={}, uuidPath={}] reached max driver depth of {}", job.getName(), job.getUuid(), uuidPath, job.getSLA().getMaxDriverDepth()); return false; } if (!job.getSLA().isAllowMultipleDispatchesToSameChannel()) { final int nbDispatches = channel.getNbBundlesForJob(job.getUuid()); if (nbDispatches > 0) return false; } return true; } /** * Check if the node is ready for the job's configuration. * @param config the desired node configuration * @param channel the node to check. * @param job the job to check against. * @param readyNodes the set of nodes ready for the desried configuration.. * @param nbReservedNodes number of nodes reserved for the job. * @return {@code true} if the check succeeds, {@code false} otherwise. */ private boolean checkDesiredConfiguration(final TypedProperties config, final BaseNodeContext channel, final ServerJob job, final Collection<String> readyNodes, final int nbReservedNodes) { if (config != null) { if (reservationHandler.getPendingJobUUID(channel) != null) return false; final String readyJobUuid = reservationHandler.getReadyJobUUID(channel); boolean b = true; if (readyNodes != null) b = readyNodes.contains(channel.getUuid()); if (debugEnabled) log.debug("nodeUuid={}, readyJobUuid={}, jobUuid={}, b={}", channel.getUuid(), readyJobUuid, job.getUuid(), b); if (!b && (nbReservedNodes >= job.getSLA().getMaxNodes())) return false; } return true; } /** * Check whether the job's execution policy, if any, matches the node. * @param channel the node on which to matach the policy. * @param job the job to check. * @param policy the execution policy to evaluate. * @param info the information against which the policy is evaluated. * @param nbJobChannels the number of nodes to which the job is already dispatched, passed on to the policy context. * @return {@code true} if the policy is {@code null} or if the node matches, {@code false} otherwise. */ private boolean checkExecutionPolicy(final BaseNodeContext channel, final ServerJob job, final ExecutionPolicy policy, final JPPFSystemInformation info, final int nbJobChannels) { if (policy == null) return true; if (debugEnabled) log.debug("job has an execution policy: {}\n{}", job, policy.toString().trim()); boolean b = false; try { preparePolicy(policy, job, stats, nbJobChannels); b = policy.evaluate(info); } catch(final Exception ex) { log.error("An error occurred while running the execution policy to determine node participation.", ex); } if (debugEnabled) log.debug("rule execution is *{}* for job [name={}, uuid={}] on channel {}", b, job.getName(), job.getUuid(), channel); return b; } /** * Check if the job state allows it to be dispatched on another node. * There are two cases when this method will return false: when the job is suspended and * when the job is already executing on its maximum allowed number of nodes. * @param job encapsulates the job information. * @return true if the job can be dispatched to at least one more node, false otherwise. */ private static boolean checkJobState(final ServerJob job) { if (job.isCancelled()) { if (debugEnabled) log.debug("job is cancelled: {}", job); return false; } final JobSLA sla = job.getSLA(); if (debugEnabled) log.debug("job '{}', suspended={}, pending={}, expired={}", new Object[] {job.getName(), sla.isSuspended(), job.isPending(), job.isJobExpired()}); if (sla.isSuspended() || job.isPending() || job.isJobExpired()) return false; if (debugEnabled) log.debug("current nodes = " + job.getNbChannels() + ", maxNodes = " + sla.getMaxNodes()); return job.getNbChannels() < sla.getMaxNodes(); } /** * Check that the job is not cancelled. * @param job encapsulates the job information. * @return {@code true} if the job is NOT cancelled, {@code false} otherwise. */ private static boolean checkJobNotCancelled(final ServerJob job) { final Lock lock = job.getLock(); lock.lock(); try { return !job.isCancelled(); } finally { lock.unlock(); } } /** * Check if the job state allows it to be dispatched to a specific master/slaves group of nodes. * @param currentNode the node currently being evaluated. * @param job the bundle from which to get the job information. * @return true if the job can be dispatched to at least one more node, false otherwise. */ private static boolean checkMaxNodeGroups(final BaseNodeContext currentNode, final ServerJob job) { final JPPFManagementInfo currentInfo = currentNode.getManagementInfo(); if (currentInfo == null) return true; final String currentMasterUuid = getMasterUuid(currentInfo); if (currentMasterUuid == null) return true; final int maxNodeGroups = job.getSLA().getMaxNodeProvisioningGroupss(); if ((maxNodeGroups == Integer.MAX_VALUE) || (maxNodeGroups <= 0)) return true; final Set<ServerTaskBundleNode> nodes = job.getDispatchSet(); final Set<String> masterUuids = new HashSet<>(); masterUuids.add(currentMasterUuid); for (final ServerTaskBundleNode node: nodes) { final AsyncNodeContext ctx = (AsyncNodeContext) node.getChannel(); final JPPFManagementInfo info = ctx.getManagementInfo(); final String uuid = getMasterUuid(info); if (uuid != null) { if (!masterUuids.contains(uuid)) masterUuids.add(uuid); if (masterUuids.size() > maxNodeGroups) { if (log.isTraceEnabled()) log.trace("[masterUuids.size() = {}] > [maxNodeGroups = {}] for {}", masterUuids.size(), maxNodeGroups, currentNode); return false; } } } return true; } /** * Get the master node uuid for a node that is either a master or a slave. * @param info represents the node information. * @return the corresponding master uuid. */ private static String getMasterUuid(final JPPFManagementInfo info) { if (info.isMasterNode()) return info.getUuid(); else if (info.isSlaveNode()) { final JPPFSystemInformation systemInfo = info.getSystemInfo(); if (systemInfo != null) return systemInfo.getJppf().get(JPPFProperties.PROVISIONING_MASTER_UUID); } return null; } /** * Perform the checks on the bundler before submitting a job. * @param taskBundle the job. * @param context the current node context. */ private void updateBundler(final TaskBundle taskBundle, final BaseNodeContext context) { context.checkBundler(bundlerFactory, jppfContext); final Bundler<?> ctxBundler = context.getBundler(); if (ctxBundler instanceof JobAwareness) ((JobAwareness) ctxBundler).setJob(taskBundle); } /** * Check whether the grid state and job's grid policy match. * If no grid policy is defined for the job, then it is considered matching. * @param job the job to check. * @return {@code true} if the job has no grid policy or the policy matches with the current grid state, {@code false} otherwise. */ private boolean checkGridPolicy(final ServerJob job) { final ExecutionPolicy policy = job.getSLA().getGridExecutionPolicy(); boolean result = true; if (policy != null) { preparePolicy(policy, job, stats, job.getNbChannels()); result = policy.evaluate(this.driverInfo); if (!result && debugEnabled) log.debug("grid policy check false for {}", job); } return result; } /** * Keep only the nodes whose configuration have the lowest distance when compared to the desired configuration. * @param job the job that specifies the desired node configuration. * @param channels the list of eligible channels. * @return one or more channels with the minimum computed score. */ private List<BaseNodeContext> filterLowestDistances(final ServerJob job, final List<BaseNodeContext> channels) { final JPPFNodeConfigSpec spec = job.getSLA().getDesiredNodeConfiguration(); final TypedProperties desiredConfiguration = (spec == null) ? null : spec.getConfiguration(); final CollectionSortedMap<Integer, BaseNodeContext> scoreMap = new SetSortedMap<>(); if (debugEnabled) log.debug("computing scores for job '{}', uuid={}", job.getName(), job.getUuid()); for (final BaseNodeContext channel: channels) { if (!channel.isLocal() && !channel.isOffline() && !channel.isPeer()) { final String reservedJobUuid = server.getNodeReservationHandler().getPendingJobUUID(channel); if ((reservedJobUuid != null) && reservedJobUuid.equals(job.getUuid())) continue; else { final TypedProperties props = channel.getSystemInformation().getJppf(); final int score = TypedPropertiesSimilarityEvaluator.computeDistance(desiredConfiguration, props); channel.setReservationScore(score); scoreMap.putValue(score, channel); } } } if (debugEnabled) { final CollectionMap<Integer, String> map = new SetSortedMap<>(); for (Map.Entry<Integer, Collection<BaseNodeContext>> entry: scoreMap.entrySet()) { for (final BaseNodeContext c: entry.getValue()) map.putValue(entry.getKey(), c.getUuid()); } log.debug("computed scores: {}", map); } final int n = scoreMap.firstKey(); return (scoreMap.isEmpty()) ? Collections.<BaseNodeContext>emptyList() : new ArrayList<>(scoreMap.getValues(n)); } }
UTF-8
Java
25,057
java
AsyncJobScheduler.java
Java
[]
null
[]
/* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.org * * 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.jppf.server.nio.nodeserver.async; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import org.jppf.execute.ExecutorStatus; import org.jppf.load.balancer.*; import org.jppf.load.balancer.spi.JPPFBundlerFactory; import org.jppf.management.*; import org.jppf.node.policy.ExecutionPolicy; import org.jppf.node.protocol.*; import org.jppf.server.nio.nodeserver.*; import org.jppf.server.protocol.*; import org.jppf.server.queue.*; import org.jppf.utils.*; import org.jppf.utils.collections.*; import org.jppf.utils.configuration.JPPFProperties; import org.jppf.utils.stats.JPPFStatistics; import org.slf4j.*; /** * This class ensures that idle nodes get assigned pending tasks in the queue. */ public class AsyncJobScheduler extends AbstractAsyncJobScheduler { /** * Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(AsyncJobScheduler.class); /** * Determines whether DEBUG logging level is enabled. */ private static final boolean debugEnabled = log.isDebugEnabled(); /** * Initialize this task queue checker with the specified node server. * @param server the node server. * @param queue the reference queue to use. * @param stats reference to the statistics. * @param bundlerFactory the load-balancer factory. */ AsyncJobScheduler(final AsyncNodeNioServer server, final JPPFPriorityQueue queue, final JPPFStatistics stats, final JPPFBundlerFactory bundlerFactory) { super(server, queue, stats, bundlerFactory); } /** * Perform the assignment of tasks. */ @Override public void run() { if (debugEnabled) log.debug("starting {}", getClass().getSimpleName()); reservationHandler = server.getNodeReservationHandler(); try { while (!isStopped()) { if (!dispatch()) goToSleep(1000L); } } catch (final Throwable t) { log.error("error in driver dispatch loop", t); } } /** * Perform the assignment of jobs to nodes. * @return true if a job was dispatched, false otherwise. */ private boolean dispatch() { try { queue.getBroadcastManager().processPendingBroadcasts(); if (queue.isEmpty()) return false; BaseNodeContext channel = null; ServerTaskBundleNode nodeBundle = null; synchronized(idleChannels) { if (idleChannels.isEmpty()) return false; final List<ServerJob> allJobs = queue.getAllJobsFromPriorityMap(); if (debugEnabled) log.debug("there are {} idle channels and {} jobs in the queue", idleChannels.size(), allJobs.size()); try { final Iterator<ServerJob> jobIterator = allJobs.iterator(); while ((channel == null) && jobIterator.hasNext() && !idleChannels.isEmpty()) { final ServerJob job = jobIterator.next(); if (debugEnabled) log.debug("checking {}", job); if (!performJobChecks(job)) continue; channel = findIdleChannelIndex(job); if (channel == null) continue; synchronized(channel.getMonitor()) { if (job.getSLA().getDesiredNodeConfiguration() != null) { final String readyJobUUID = reservationHandler.getReadyJobUUID(channel); final String pendingJobUUID = reservationHandler.getPendingJobUUID(channel); if ((pendingJobUUID == null) && (readyJobUUID == null)) { if (debugEnabled) log.debug("reserving {} with {}", job, channel); reservationHandler.doReservation(job, channel); channel = null; continue; } } if (channel.getCurrentNbJobs() >= channel.getMaxJobs()) removeIdleChannel(channel); if (!channel.isEnabled()) { if (debugEnabled) log.debug("channel is disabled [}", channel); channel = null; continue; } nodeBundle = prepareJobDispatch(channel, job); if (debugEnabled) log.debug("prepareJobDispatch() returned {}", nodeBundle); if (nodeBundle != null) { try { dispatchJobToChannel(channel, nodeBundle); return true; } catch (final Exception e) { log.error("{}\nchannel={}\njob={}\nstack trace: {}", ExceptionUtils.getMessage(e), channel, nodeBundle, ExceptionUtils.getStackTrace(e)); channel.setClosed(false); channel.handleException(e); } } } } if (debugEnabled) log.debug((channel == null) ? "no channel found for bundle " : "channel found for bundle " + channel); } catch(final Exception e) { log.error("An error occurred while attempting to dispatch task bundles. This is most likely due to an error in the load balancer implementation.", e); } } } catch (final Exception e) { log.error("An error occurred while preparing for bundle creation and dispatching.", e); } return false; } /** * Prepare the specified job for the selected channel, after applying the load balancer to the job. * @param channel the node channel to prepare dispatch the job to. * @param selectedJob the job to dispatch. * @return the task bundle to dispatch to the specified node. */ private ServerTaskBundleNode prepareJobDispatch(final BaseNodeContext channel, final ServerJob selectedJob) { if (debugEnabled) log.debug("dispatching jobUuid=" + selectedJob.getUuid() + " to node " + channel + ", nodeUuid=" + channel.getConnectionUuid()); int size = 1; try { updateBundler(selectedJob.getJob(), channel); size = channel.getBundler().getBundleSize(); if (selectedJob.getSLA().getMaxDispatchSize() < size) size = selectedJob.getSLA().getMaxDispatchSize(); } catch (final Exception e) { log.error("Error in load balancer implementation, switching to 'manual' with a bundle size of 1", e); size = bundlerFactory.getFallbackBundler().getBundleSize(); } return selectedJob.isCancelled() ? null : queue.nextBundle(selectedJob, size, channel); } /** * Dispatch the specified job to the selected channel, after applying the load balancer to the job. * @param channel the node channel to dispatch the job to. * @param nodeBundle the job to dispatch. * @throws Exception if any error occurs. */ private static void dispatchJobToChannel(final BaseNodeContext channel, final ServerTaskBundleNode nodeBundle) throws Exception { if (debugEnabled) log.debug("dispatching {} tasks of job '{}' to node {}", nodeBundle.getTaskCount(), nodeBundle.getJob().getName(), channel.getUuid()); if (log.isTraceEnabled()) { final Set<Long> set = new TreeSet<>(); for (final ServerTask task: nodeBundle.getTaskList()) { final long id = task.getBundle().getId(); if (!set.contains(id)) set.add(id); } StringBuilder sb = new StringBuilder(); int count = 0; for (final long id: set) { if (count > 0) sb.append(", "); sb.append("ServerTaskBundleClient[id=").append(id).append(']'); count++; } log.trace("client bundles in dispatch: {}", sb); sb = new StringBuilder(); count = 0; for (final ServerTask task: nodeBundle.getTaskList()) { if (count > 0) sb.append(", "); sb.append(task.getPosition()); count++; } log.trace("tasks positions in dispatch: {}", sb); } synchronized(channel.getMonitor()) { final Future<?> future = channel.submit(nodeBundle); nodeBundle.jobDispatched(channel, future); } if (debugEnabled) log.debug("dispatched {} tasks of job '{}' to node {}", nodeBundle.getTaskCount(), nodeBundle.getJob().getName(), channel.getUuid()); } /** * Find a channel that can send the specified task bundle for execution. * @param job the bundle to execute. * @return the index of an available and acceptable channel, or -1 if no channel could be found. */ private BaseNodeContext findIdleChannelIndex(final ServerJob job) { if (debugEnabled) log.debug("checking {}", job); final JobSLA sla = job.getSLA(); final JPPFNodeConfigSpec spec = sla.getDesiredNodeConfiguration(); final TypedProperties desiredConfiguration = (spec == null) ? null : spec.getConfiguration(); List<BaseNodeContext> acceptableChannels = new ArrayList<>(idleChannels.size()); final List<BaseNodeContext> toRemove = new LinkedList<>(); Iterator<BaseNodeContext> nodeIterator = null; if (sla.getPreferencePolicy() != null) { final Set<BaseNodeContext> preferedChannels = filterPreferredNodes(job); if (preferedChannels.isEmpty()) return null; nodeIterator = preferedChannels.iterator(); } else nodeIterator = idleChannels.iterator(); while (nodeIterator.hasNext()) { final AsyncNodeContext channel = (AsyncNodeContext) nodeIterator.next(); synchronized(channel.getMonitor()) { if ((channel.getExecutionStatus() != ExecutorStatus.ACTIVE) || channel.isClosed() || !channel.isEnabled()) { if (debugEnabled) log.debug("channel is not opened: {}", channel); toRemove.add(channel); continue; } if (!channel.isActive() || !channel.isAcceptingNewJobs()) { if (debugEnabled) log.debug("node not accepting jobs: {}", channel); continue; } if (channel.isPeer() && (server.nodeConnectionHandler.getConnectedRealNodes() >= peerLoadBalanceThreshold)) { if (debugEnabled) log.debug("this driver has {} nodes and the threshold is {}", server.nodeConnectionHandler.getConnectedNodes(), peerLoadBalanceThreshold); continue; } if (channel.getCurrentNbJobs() >= channel.getMaxJobs()) { if (debugEnabled) log.debug("[currentNbJobs = {}] >= maxJobs = {}] for {}", channel.getCurrentNbJobs(), channel.getMaxJobs(), channel); continue; } if (!checkJobAgainstChannel(channel, job)) continue; if (job.getBroadcastUUID() != null && !job.getBroadcastUUID().equals(channel.getUuid())) continue; final JPPFSystemInformation info = channel.getSystemInformation(); if (channel.isPeer() && !disptachtoPeersWithoutNode) { if ((info != null) && (info.getJppf().getInt(PeerAttributesHandler.PEER_TOTAL_NODES, 0) <= 0)) { if (debugEnabled) log.debug("peer has no attached node: {}", channel.getUuid()); continue; } } if (!checkExecutionPolicy(channel, job, sla.getExecutionPolicy(), info, job.getNbChannels())) continue; if (!checkMaxNodeGroups(channel, job)) continue; final Collection<String> readyNodes = (spec == null) ? null : reservationHandler.getReadyNodes(job.getUuid()); if (debugEnabled) log.debug("jobUuid={}, readyNodes={}", job.getUuid(), readyNodes); if (!checkDesiredConfiguration(desiredConfiguration, channel, job, readyNodes, reservationHandler.getNbReservedNodes(job.getUuid()))) continue; if (channel.isLocal() && localNodeBiasEnabled) { // add a bias toward local node if (desiredConfiguration != null) continue; else return channel; } acceptableChannels.add(channel); } } if (!toRemove.isEmpty()) { for (final BaseNodeContext c: toRemove) removeIdleChannel(c); } if (!checkJobNotCancelled(job)) return null; if (!acceptableChannels.isEmpty() && (desiredConfiguration != null)) acceptableChannels = filterLowestDistances(job, acceptableChannels); return selectChannel(acceptableChannels); } /** * Select a single channle from a list of channels eligible for a job. * @param acceptableChannels the list of channels to select from. * @return an instance of {@link BaseNodeContext}, or {@code null} if the list is empty or no channel passes the selection criteria. */ private BaseNodeContext selectChannel(final List<BaseNodeContext> acceptableChannels) { if (acceptableChannels.isEmpty()) return null; final int size = acceptableChannels.size(); if (debugEnabled) log.debug("found {} acceptable channels", size); final BaseNodeContext channel = (size > 0) ? acceptableChannels.get(size > 1 ? random.nextInt(size) : 0) : null; return channel; } /** * * @param job the job to check. * @return {@code true} if the job can be scheduiled, {@code false} otherwise. */ private boolean performJobChecks(final ServerJob job) { final JobDependencySpec dependencySpec = job.getSLA().getDependencySpec(); //if (debugEnabled) log.debug("job graph node: {}", dependencyHandler.getGraph().getNode(dependencySpec.getId())); if ((dependencySpec.getId() != null) && !job.isJobGraphAlreadyHandled() && dependencySpec.hasDependency() && dependencyHandler.hasPendingDependencyOrCancelled(dependencySpec.getId())) { if (debugEnabled) log.debug("job dependency check false for {}", job); return false; } final JPPFNodeConfigSpec spec = job.getSLA().getDesiredNodeConfiguration(); if (spec != null) { if ((reservationHandler.getNbReservedNodes(job.getUuid()) >= job.getSLA().getMaxNodes()) && !reservationHandler.hasReadyNode(job.getUuid())) { if (debugEnabled) log.debug("node config check false for {}", job); return false; } } if ((job.getTaskGraph() != null) && !job.hasAvailableGraphNode()) { if (debugEnabled) log.debug("tasks graph check false for {}", job); return false; } if (!checkGridPolicy(job)) return false; return checkJobState(job); } /** * Check that the job did not already get through the specified channel (collision avoidance) and that the SLA's max driver depth is not reached. * @param channel the node to check. * @param job the job to check against. * @return {@code true} if the check succeeds, {@code false} otherwise. */ private boolean checkJobAgainstChannel(final AsyncNodeContext channel, final ServerJob job) { final List<String> uuidPath = job.getJob().getUuidPath().getList(); if (debugEnabled) log.debug("uuid path={}, node uuid={}", uuidPath, channel.getUuid()); final String driverUuid = server.getDriver().getUuid(); final int index = uuidPath.indexOf(driverUuid); if ((index >= 0) && (index != uuidPath.size() - 1)) log.warn("uuid path contains this driver's uuid {}: uuidPath={}", driverUuid, uuidPath); if (uuidPath.contains(channel.getUuid())) { if (debugEnabled) log.debug("bundle uuid path already contains node {} : uuidPath={}, nodeUuid={}", channel, uuidPath, channel.getUuid()); return false; } if (channel.isPeer() && (uuidPath.size() - 1 >= job.getSLA().getMaxDriverDepth())) { if (debugEnabled) log.debug("job [name={}, uuid={}, uuidPath={}] reached max driver depth of {}", job.getName(), job.getUuid(), uuidPath, job.getSLA().getMaxDriverDepth()); return false; } if (!job.getSLA().isAllowMultipleDispatchesToSameChannel()) { final int nbDispatches = channel.getNbBundlesForJob(job.getUuid()); if (nbDispatches > 0) return false; } return true; } /** * Check if the node is ready for the job's configuration. * @param config the desired node configuration * @param channel the node to check. * @param job the job to check against. * @param readyNodes the set of nodes ready for the desried configuration.. * @param nbReservedNodes number of nodes reserved for the job. * @return {@code true} if the check succeeds, {@code false} otherwise. */ private boolean checkDesiredConfiguration(final TypedProperties config, final BaseNodeContext channel, final ServerJob job, final Collection<String> readyNodes, final int nbReservedNodes) { if (config != null) { if (reservationHandler.getPendingJobUUID(channel) != null) return false; final String readyJobUuid = reservationHandler.getReadyJobUUID(channel); boolean b = true; if (readyNodes != null) b = readyNodes.contains(channel.getUuid()); if (debugEnabled) log.debug("nodeUuid={}, readyJobUuid={}, jobUuid={}, b={}", channel.getUuid(), readyJobUuid, job.getUuid(), b); if (!b && (nbReservedNodes >= job.getSLA().getMaxNodes())) return false; } return true; } /** * Check whether the job's execution policy, if any, matches the node. * @param channel the node on which to matach the policy. * @param job the job to check. * @param policy the execution policy to evaluate. * @param info the information against which the policy is evaluated. * @param nbJobChannels the number of nodes to which the job is already dispatched, passed on to the policy context. * @return {@code true} if the policy is {@code null} or if the node matches, {@code false} otherwise. */ private boolean checkExecutionPolicy(final BaseNodeContext channel, final ServerJob job, final ExecutionPolicy policy, final JPPFSystemInformation info, final int nbJobChannels) { if (policy == null) return true; if (debugEnabled) log.debug("job has an execution policy: {}\n{}", job, policy.toString().trim()); boolean b = false; try { preparePolicy(policy, job, stats, nbJobChannels); b = policy.evaluate(info); } catch(final Exception ex) { log.error("An error occurred while running the execution policy to determine node participation.", ex); } if (debugEnabled) log.debug("rule execution is *{}* for job [name={}, uuid={}] on channel {}", b, job.getName(), job.getUuid(), channel); return b; } /** * Check if the job state allows it to be dispatched on another node. * There are two cases when this method will return false: when the job is suspended and * when the job is already executing on its maximum allowed number of nodes. * @param job encapsulates the job information. * @return true if the job can be dispatched to at least one more node, false otherwise. */ private static boolean checkJobState(final ServerJob job) { if (job.isCancelled()) { if (debugEnabled) log.debug("job is cancelled: {}", job); return false; } final JobSLA sla = job.getSLA(); if (debugEnabled) log.debug("job '{}', suspended={}, pending={}, expired={}", new Object[] {job.getName(), sla.isSuspended(), job.isPending(), job.isJobExpired()}); if (sla.isSuspended() || job.isPending() || job.isJobExpired()) return false; if (debugEnabled) log.debug("current nodes = " + job.getNbChannels() + ", maxNodes = " + sla.getMaxNodes()); return job.getNbChannels() < sla.getMaxNodes(); } /** * Check that the job is not cancelled. * @param job encapsulates the job information. * @return {@code true} if the job is NOT cancelled, {@code false} otherwise. */ private static boolean checkJobNotCancelled(final ServerJob job) { final Lock lock = job.getLock(); lock.lock(); try { return !job.isCancelled(); } finally { lock.unlock(); } } /** * Check if the job state allows it to be dispatched to a specific master/slaves group of nodes. * @param currentNode the node currently being evaluated. * @param job the bundle from which to get the job information. * @return true if the job can be dispatched to at least one more node, false otherwise. */ private static boolean checkMaxNodeGroups(final BaseNodeContext currentNode, final ServerJob job) { final JPPFManagementInfo currentInfo = currentNode.getManagementInfo(); if (currentInfo == null) return true; final String currentMasterUuid = getMasterUuid(currentInfo); if (currentMasterUuid == null) return true; final int maxNodeGroups = job.getSLA().getMaxNodeProvisioningGroupss(); if ((maxNodeGroups == Integer.MAX_VALUE) || (maxNodeGroups <= 0)) return true; final Set<ServerTaskBundleNode> nodes = job.getDispatchSet(); final Set<String> masterUuids = new HashSet<>(); masterUuids.add(currentMasterUuid); for (final ServerTaskBundleNode node: nodes) { final AsyncNodeContext ctx = (AsyncNodeContext) node.getChannel(); final JPPFManagementInfo info = ctx.getManagementInfo(); final String uuid = getMasterUuid(info); if (uuid != null) { if (!masterUuids.contains(uuid)) masterUuids.add(uuid); if (masterUuids.size() > maxNodeGroups) { if (log.isTraceEnabled()) log.trace("[masterUuids.size() = {}] > [maxNodeGroups = {}] for {}", masterUuids.size(), maxNodeGroups, currentNode); return false; } } } return true; } /** * Get the master node uuid for a node that is either a master or a slave. * @param info represents the node information. * @return the corresponding master uuid. */ private static String getMasterUuid(final JPPFManagementInfo info) { if (info.isMasterNode()) return info.getUuid(); else if (info.isSlaveNode()) { final JPPFSystemInformation systemInfo = info.getSystemInfo(); if (systemInfo != null) return systemInfo.getJppf().get(JPPFProperties.PROVISIONING_MASTER_UUID); } return null; } /** * Perform the checks on the bundler before submitting a job. * @param taskBundle the job. * @param context the current node context. */ private void updateBundler(final TaskBundle taskBundle, final BaseNodeContext context) { context.checkBundler(bundlerFactory, jppfContext); final Bundler<?> ctxBundler = context.getBundler(); if (ctxBundler instanceof JobAwareness) ((JobAwareness) ctxBundler).setJob(taskBundle); } /** * Check whether the grid state and job's grid policy match. * If no grid policy is defined for the job, then it is considered matching. * @param job the job to check. * @return {@code true} if the job has no grid policy or the policy matches with the current grid state, {@code false} otherwise. */ private boolean checkGridPolicy(final ServerJob job) { final ExecutionPolicy policy = job.getSLA().getGridExecutionPolicy(); boolean result = true; if (policy != null) { preparePolicy(policy, job, stats, job.getNbChannels()); result = policy.evaluate(this.driverInfo); if (!result && debugEnabled) log.debug("grid policy check false for {}", job); } return result; } /** * Keep only the nodes whose configuration have the lowest distance when compared to the desired configuration. * @param job the job that specifies the desired node configuration. * @param channels the list of eligible channels. * @return one or more channels with the minimum computed score. */ private List<BaseNodeContext> filterLowestDistances(final ServerJob job, final List<BaseNodeContext> channels) { final JPPFNodeConfigSpec spec = job.getSLA().getDesiredNodeConfiguration(); final TypedProperties desiredConfiguration = (spec == null) ? null : spec.getConfiguration(); final CollectionSortedMap<Integer, BaseNodeContext> scoreMap = new SetSortedMap<>(); if (debugEnabled) log.debug("computing scores for job '{}', uuid={}", job.getName(), job.getUuid()); for (final BaseNodeContext channel: channels) { if (!channel.isLocal() && !channel.isOffline() && !channel.isPeer()) { final String reservedJobUuid = server.getNodeReservationHandler().getPendingJobUUID(channel); if ((reservedJobUuid != null) && reservedJobUuid.equals(job.getUuid())) continue; else { final TypedProperties props = channel.getSystemInformation().getJppf(); final int score = TypedPropertiesSimilarityEvaluator.computeDistance(desiredConfiguration, props); channel.setReservationScore(score); scoreMap.putValue(score, channel); } } } if (debugEnabled) { final CollectionMap<Integer, String> map = new SetSortedMap<>(); for (Map.Entry<Integer, Collection<BaseNodeContext>> entry: scoreMap.entrySet()) { for (final BaseNodeContext c: entry.getValue()) map.putValue(entry.getKey(), c.getUuid()); } log.debug("computed scores: {}", map); } final int n = scoreMap.firstKey(); return (scoreMap.isEmpty()) ? Collections.<BaseNodeContext>emptyList() : new ArrayList<>(scoreMap.getValues(n)); } }
25,057
0.673265
0.671908
521
47.094051
39.948971
191
false
false
0
0
0
0
0
0
0.767754
false
false
2