proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
gz-yami_mall4j
|
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/filter/AuthFilter.java
|
AuthFilter
|
doFilter
|
class AuthFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);
@Autowired
private AuthConfigAdapter authConfigAdapter;
@Autowired
private HttpHandler httpHandler;
@Autowired
private TokenStore tokenStore;
@Value("${sa-token.token-name}")
private String tokenName;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {<FILL_FUNCTION_BODY>}
}
|
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String requestUri = req.getRequestURI();
List<String> excludePathPatterns = authConfigAdapter.excludePathPatterns();
AntPathMatcher pathMatcher = new AntPathMatcher();
// 如果匹配不需要授权的路径,就不需要校验是否需要授权
if (CollectionUtil.isNotEmpty(excludePathPatterns)) {
for (String excludePathPattern : excludePathPatterns) {
if (pathMatcher.match(excludePathPattern, requestUri)) {
chain.doFilter(req, resp);
return;
}
}
}
String accessToken = req.getHeader(tokenName);
// 也许需要登录,不登陆也能用的uri
boolean mayAuth = pathMatcher.match(AuthConfigAdapter.MAYBE_AUTH_URI, requestUri);
UserInfoInTokenBO userInfoInToken = null;
try {
// 如果有token,就要获取token
if (StrUtil.isNotBlank(accessToken)) {
// 校验登录,并从缓存中取出用户信息
try {
StpUtil.checkLogin();
} catch (Exception e) {
httpHandler.printServerResponseToWeb(ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED));
return;
}
userInfoInToken = tokenStore.getUserInfoByAccessToken(accessToken, true);
}
else if (!mayAuth) {
// 返回前端401
httpHandler.printServerResponseToWeb(ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED));
return;
}
// 保存上下文
AuthUserContext.set(userInfoInToken);
chain.doFilter(req, resp);
}catch (Exception e) {
// 手动捕获下非controller异常
if (e instanceof YamiShopBindException) {
httpHandler.printServerResponseToWeb((YamiShopBindException) e);
} else {
throw e;
}
} finally {
AuthUserContext.clean();
}
| 149
| 556
| 705
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/manager/PasswordCheckManager.java
|
PasswordCheckManager
|
checkPassword
|
class PasswordCheckManager {
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 半小时内最多错误10次
*/
private static final int TIMES_CHECK_INPUT_PASSWORD_NUM = 10;
/**
* 检查用户输入错误的验证码次数
*/
private static final String CHECK_VALID_CODE_NUM_PREFIX = "checkUserInputErrorPassword_";
public void checkPassword(SysTypeEnum sysTypeEnum,String userNameOrMobile, String rawPassword, String encodedPassword) {<FILL_FUNCTION_BODY>}
}
|
String checkPrefix = sysTypeEnum.value() + CHECK_VALID_CODE_NUM_PREFIX + IpHelper.getIpAddr();
int count = 0;
if(RedisUtil.hasKey(checkPrefix + userNameOrMobile)){
count = RedisUtil.get(checkPrefix + userNameOrMobile);
}
if(count > TIMES_CHECK_INPUT_PASSWORD_NUM){
throw new YamiShopBindException("密码输入错误十次,已限制登录30分钟");
}
// 半小时后失效
RedisUtil.set(checkPrefix + userNameOrMobile,count,1800);
// 密码不正确
if (StrUtil.isBlank(encodedPassword) || !passwordEncoder.matches(rawPassword,encodedPassword)){
count++;
// 半小时后失效
RedisUtil.set(checkPrefix + userNameOrMobile,count,1800);
throw new YamiShopBindException("账号或密码不正确");
}
| 158
| 262
| 420
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/manager/PasswordManager.java
|
PasswordManager
|
decryptPassword
|
class PasswordManager {
private static final Logger logger = LoggerFactory.getLogger(PasswordManager.class);
/**
* 用于aes签名的key,16位
*/
@Value("${auth.password.signKey:-mall4j-password}")
public String passwordSignKey;
public String decryptPassword(String data) {<FILL_FUNCTION_BODY>}
}
|
// 在使用oracle的JDK时,JAR包必须签署特殊的证书才能使用。
// 解决方案 1.使用openJDK或者非oracle的JDK(建议) 2.添加证书
// hutool的aes报错可以打开下面那段代码
// SecureUtil.disableBouncyCastle();
AES aes = new AES(passwordSignKey.getBytes(StandardCharsets.UTF_8));
String decryptStr;
String decryptPassword;
try {
decryptStr = aes.decryptStr(data);
decryptPassword = decryptStr.substring(13);
} catch (Exception e) {
logger.error("Exception:", e);
throw new YamiShopBindException("AES解密错误", e);
}
return decryptPassword;
| 105
| 211
| 316
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/manager/TokenStore.java
|
TokenStore
|
deleteAllToken
|
class TokenStore {
private static final Logger logger = LoggerFactory.getLogger(TokenStore.class);
private final RedisTemplate<String, Object> redisTemplate;
public TokenStore(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 以Sa-Token技术生成token,并返回token信息
* @param userInfoInToken
* @return
*/
public TokenInfoBO storeAccessSaToken(UserInfoInTokenBO userInfoInToken) {
// token生成
int timeoutSecond = getExpiresIn(userInfoInToken.getSysType());
String uid = this.getUid(userInfoInToken.getSysType().toString(), userInfoInToken.getUserId());
StpUtil.login(uid, timeoutSecond);
String token = StpUtil.getTokenValue();
// 用户信息存入缓存
String keyName = OauthCacheNames.USER_INFO + token;
redisTemplate.delete(keyName);
redisTemplate.opsForValue().set(
keyName,
JSON.toJSONString(userInfoInToken),
timeoutSecond,
TimeUnit.SECONDS
);
// 数据封装返回(token不用加密)
TokenInfoBO tokenInfoBO = new TokenInfoBO();
tokenInfoBO.setUserInfoInToken(userInfoInToken);
tokenInfoBO.setExpiresIn(timeoutSecond);
tokenInfoBO.setAccessToken(token);
tokenInfoBO.setRefreshToken(token);
return tokenInfoBO;
}
/**
* 计算过期时间(单位:秒)
* @param sysType
* @return
*/
private int getExpiresIn(int sysType) {
// 3600秒
int expiresIn = 3600;
// 普通用户token过期时间
if (Objects.equals(sysType, SysTypeEnum.ORDINARY.value())) {
expiresIn = expiresIn * 24 * 30;
}
// 系统管理员的token过期时间
if (Objects.equals(sysType, SysTypeEnum.ADMIN.value())) {
expiresIn = expiresIn * 24 * 30;
}
return expiresIn;
}
/**
* 根据accessToken 获取用户信息
* @param accessToken accessToken
* @param needDecrypt 是否需要解密
* @return 用户信息
*/
public UserInfoInTokenBO getUserInfoByAccessToken(String accessToken, boolean needDecrypt) {
if (StrUtil.isBlank(accessToken)) {
throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED,"accessToken is blank");
}
String keyName = OauthCacheNames.USER_INFO + accessToken;
Object redisCache = redisTemplate.opsForValue().get(keyName);
if (redisCache == null) {
throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED,"登录过期,请重新登录");
}
return JSON.parseObject(redisCache.toString(), UserInfoInTokenBO.class);
}
/**
* 刷新token,并返回新的token
* @param refreshToken
* @return
*/
public TokenInfoBO refreshToken(String refreshToken) {
if (StrUtil.isBlank(refreshToken)) {
throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED,"refreshToken is blank");
}
// 删除旧token
UserInfoInTokenBO userInfoInTokenBO = getUserInfoByAccessToken(refreshToken, false);
this.deleteCurrentToken(refreshToken);
// 保存一份新的token
return storeAccessSaToken(userInfoInTokenBO);
}
/**
* 删除指定用户的全部的token
*/
public void deleteAllToken(String sysType, String userId) {<FILL_FUNCTION_BODY>}
/**
* 生成token,并返回token展示信息
* @param userInfoInToken
* @return
*/
public TokenInfoVO storeAndGetVo(UserInfoInTokenBO userInfoInToken) {
if (!userInfoInToken.getEnabled()){
// 用户已禁用,请联系客服
throw new YamiShopBindException("yami.user.disabled");
}
TokenInfoBO tokenInfoBO = storeAccessSaToken(userInfoInToken);
// 数据封装返回
TokenInfoVO tokenInfoVO = new TokenInfoVO();
tokenInfoVO.setAccessToken(tokenInfoBO.getAccessToken());
tokenInfoVO.setRefreshToken(tokenInfoBO.getRefreshToken());
tokenInfoVO.setExpiresIn(tokenInfoBO.getExpiresIn());
return tokenInfoVO;
}
/**
* 删除当前登录的token
* @param accessToken 令牌
*/
public void deleteCurrentToken(String accessToken) {
// 删除用户缓存
String keyName = OauthCacheNames.USER_INFO + accessToken;
redisTemplate.delete(keyName);
// 移除token
StpUtil.logoutByTokenValue(accessToken);
}
/**
* 生成各系统唯一uid
* @param sysType 系统类型
* @param userId 用户id
* @return
*/
private String getUid(String sysType, String userId) {
return sysType + ":" + userId;
}
}
|
// 删除用户缓存
String uid = this.getUid(sysType, userId);
List<String> tokens = StpUtil.getTokenValueListByLoginId(uid);
if (!CollectionUtils.isEmpty(tokens)) {
List<String> keyNames = new ArrayList<>();
for (String token : tokens) {
keyNames.add(OauthCacheNames.USER_INFO + token);
}
redisTemplate.delete(keyNames);
}
// 移除token
StpUtil.logout(userId);
| 1,436
| 142
| 1,578
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/permission/PermissionService.java
|
PermissionService
|
hasPermission
|
class PermissionService {
/**
* 判断接口是否有xxx:xxx权限
*
* @param permission 权限
* @return {boolean}
*/
public boolean hasPermission(String permission) {<FILL_FUNCTION_BODY>}
}
|
if (StrUtil.isBlank(permission)) {
return false;
}
return AuthUserContext.get().getPerms()
.stream()
.filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
| 71
| 75
| 146
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/AttachFileServiceImpl.java
|
AttachFileServiceImpl
|
uploadFile
|
class AttachFileServiceImpl extends ServiceImpl<AttachFileMapper, AttachFile> implements AttachFileService {
@Autowired
private AttachFileMapper attachFileMapper;
@Autowired
private UploadManager uploadManager;
@Autowired
private BucketManager bucketManager;
@Autowired
private Qiniu qiniu;
@Autowired
private Auth auth;
@Autowired
private ImgUploadUtil imgUploadUtil;
public final static String NORM_MONTH_PATTERN = "yyyy/MM/";
@Override
@Transactional(rollbackFor = Exception.class)
public String uploadFile(MultipartFile file) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void deleteFile(String fileName){
attachFileMapper.delete(new LambdaQueryWrapper<AttachFile>().eq(AttachFile::getFilePath,fileName));
try {
if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
imgUploadUtil.delete(fileName);
} else if (Objects.equals(imgUploadUtil.getUploadType(), 2)) {
bucketManager.delete(qiniu.getBucket(), fileName);
}
} catch (QiniuException e) {
throw new RuntimeException(e);
}
}
}
|
String extName = FileUtil.extName(file.getOriginalFilename());
String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;
AttachFile attachFile = new AttachFile();
attachFile.setFilePath(fileName);
attachFile.setFileSize(file.getBytes().length);
attachFile.setFileType(extName);
attachFile.setUploadTime(new Date());
if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
// 本地文件上传
attachFileMapper.insert(attachFile);
return imgUploadUtil.upload(file, fileName);
} else {
// 七牛云文件上传
String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
Response response = uploadManager.put(file.getBytes(), fileName, upToken);
Json.parseObject(response.bodyString(), DefaultPutRet.class);
return fileName;
}
| 340
| 279
| 619
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/BasketServiceImpl.java
|
BasketServiceImpl
|
getShopCarts
|
class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> implements BasketService {
private final BasketMapper basketMapper;
private final CacheManagerUtil cacheManagerUtil;
private final ApplicationContext applicationContext;
private final SkuService skuService;
private final ShopDetailService shopDetailService;
private final ProductService productService;
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
public void deleteShopCartItemsByBasketIds(String userId, List<Long> basketIds) {
basketMapper.deleteShopCartItemsByBasketIds(userId, basketIds);
}
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
public void addShopCartItem(ChangeShopCartParam param, String userId) {
Basket basket = new Basket();
basket.setBasketCount(param.getCount());
basket.setBasketDate(new Date());
basket.setProdId(param.getProdId());
basket.setShopId(param.getShopId());
basket.setUserId(userId);
basket.setSkuId(param.getSkuId());
basket.setDistributionCardNo(param.getDistributionCardNo());
basketMapper.insert(basket);
}
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#basket.userId")
public void updateShopCartItem(Basket basket) {
basketMapper.updateById(basket);
}
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
public void deleteAllShopCartItems(String userId) {
basketMapper.deleteAllShopCartItems(userId);
}
@Override
public List<ShopCartItemDto> getShopCartItems(String userId) {
// 在这个类里面要调用这里的缓存信息,并没有使用aop,所以不使用注解
List<ShopCartItemDto> shopCartItemDtoList = cacheManagerUtil.getCache("ShopCartItems", userId);
if (shopCartItemDtoList != null) {
return shopCartItemDtoList;
}
shopCartItemDtoList = basketMapper.getShopCartItems(userId);
for (ShopCartItemDto shopCartItemDto : shopCartItemDtoList) {
shopCartItemDto.setProductTotalAmount(Arith.mul(shopCartItemDto.getProdCount(), shopCartItemDto.getPrice()));
}
cacheManagerUtil.putCache("ShopCartItems", userId, shopCartItemDtoList);
return shopCartItemDtoList;
}
@Override
public List<ShopCartItemDto> getShopCartExpiryItems(String userId) {
return basketMapper.getShopCartExpiryItems(userId);
}
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
public void cleanExpiryProdList(String userId) {
basketMapper.cleanExpiryProdList(userId);
}
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
public void updateBasketByShopCartParam(String userId, Map<Long, ShopCartParam> basketIdShopCartParamMap) {
basketMapper.updateDiscountItemId(userId, basketIdShopCartParamMap);
}
@Override
@CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
public void removeShopCartItemsCacheByUserId(String userId) {
}
@Override
public List<String> listUserIdByProdId(Long prodId) {
return basketMapper.listUserIdByProdId(prodId);
}
@Override
public List<ShopCartDto> getShopCarts(List<ShopCartItemDto> shopCartItems) {<FILL_FUNCTION_BODY>}
@Override
public List<ShopCartItemDto> getShopCartItemsByOrderItems(List<Long> basketId, OrderItemParam orderItem,String userId) {
if (orderItem == null && CollectionUtil.isEmpty(basketId)) {
return Collections.emptyList();
}
// 当立即购买时,没有提交的订单是没有购物车信息的
if (CollectionUtil.isEmpty(basketId) && orderItem != null) {
Sku sku = skuService.getSkuBySkuId(orderItem.getSkuId());
if (sku == null) {
throw new RuntimeException("订单包含无法识别的商品");
}
Product prod = productService.getProductByProdId(orderItem.getProdId());
if (prod == null) {
throw new RuntimeException("订单包含无法识别的商品");
}
// 拿到购物车的所有item
ShopCartItemDto shopCartItemDto = new ShopCartItemDto();
shopCartItemDto.setBasketId(-1L);
shopCartItemDto.setSkuId(orderItem.getSkuId());
shopCartItemDto.setProdCount(orderItem.getProdCount());
shopCartItemDto.setProdId(orderItem.getProdId());
shopCartItemDto.setSkuName(sku.getSkuName());
shopCartItemDto.setPic(StrUtil.isBlank(sku.getPic())? prod.getPic() : sku.getPic());
shopCartItemDto.setProdName(sku.getProdName());
shopCartItemDto.setProductTotalAmount(Arith.mul(sku.getPrice(),orderItem.getProdCount()));
shopCartItemDto.setPrice(sku.getPrice());
shopCartItemDto.setDistributionCardNo(orderItem.getDistributionCardNo());
shopCartItemDto.setBasketDate(new Date());
ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(orderItem.getShopId());
shopCartItemDto.setShopId(shopDetail.getShopId());
shopCartItemDto.setShopName(shopDetail.getShopName());
return Collections.singletonList(shopCartItemDto);
}
List<ShopCartItemDto> dbShopCartItems = getShopCartItems(userId);
// 返回购物车选择的商品信息
return dbShopCartItems
.stream()
.filter(shopCartItemDto -> basketId.contains(shopCartItemDto.getBasketId()))
.collect(Collectors.toList());
}
}
|
// 根据店铺ID划分item
Map<Long, List<ShopCartItemDto>> shopCartMap = shopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemDto::getShopId));
// 返回一个店铺的所有信息
List<ShopCartDto> shopCartDtos = Lists.newArrayList();
for (Long shopId : shopCartMap.keySet()) {
//获取店铺的所有商品项
List<ShopCartItemDto> shopCartItemDtoList = shopCartMap.get(shopId);
// 构建每个店铺的购物车信息
ShopCartDto shopCart = new ShopCartDto();
//店铺信息
shopCart.setShopId(shopId);
shopCart.setShopName(shopCartItemDtoList.get(0).getShopName());
applicationContext.publishEvent(new ShopCartEvent(shopCart, shopCartItemDtoList));
shopCartDtos.add(shopCart);
}
return shopCartDtos;
| 1,686
| 267
| 1,953
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/CategoryServiceImpl.java
|
CategoryServiceImpl
|
categoryListToTree
|
class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{
@Autowired
private CategoryMapper categoryMapper;
@Autowired
private CategoryBrandMapper categoryBrandMapper;
@Autowired
private CategoryPropMapper categoryPropMapper;
@Autowired
private AttachFileService attachFileService;
@Override
public List<Category> listByParentId(Long parentId) {
return categoryMapper.listByParentId(parentId);
}
@Override
public List<Category> tableCategory(Long shopId) {
return categoryMapper.tableCategory(shopId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void saveCategory(Category category) {
category.setRecTime(new Date());
// 保存分类信息
categoryMapper.insert(category);
insertBrandsAndAttributes(category);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCategory(Category category) {
Category dbCategory = categoryMapper.selectById(category.getCategoryId());
category.setUpdateTime(new Date());
// 保存分类信息
categoryMapper.updateById(category);
// 先删除后增加
deleteBrandsAndAttributes(category.getCategoryId());
insertBrandsAndAttributes(category);
// 如果以前有图片,并且图片与现在不同,则删除以前的图片
// if (StrUtil.isNotBlank(dbCategory.getPic()) && !dbCategory.getPic().equals(category.getPic())) {
// attachFileService.deleteFile(dbCategory.getPic());
// }
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCategory(Long categoryId) {
Category category = categoryMapper.selectById(categoryId);
categoryMapper.deleteById(categoryId);
deleteBrandsAndAttributes(categoryId);
// if (StrUtil.isNotBlank(category.getPic())) {
// attachFileService.deleteFile(category.getPic());
// }
}
private void deleteBrandsAndAttributes(Long categoryId) {
// 删除所有分类所关联的品牌
categoryBrandMapper.deleteByCategoryId(categoryId);
// 删除所有分类所关联的参数
categoryPropMapper.deleteByCategoryId(categoryId);
}
private void insertBrandsAndAttributes(Category category) {
//保存分类与品牌信息
if(CollUtil.isNotEmpty(category.getBrandIds())){
categoryBrandMapper.insertCategoryBrand(category.getCategoryId(), category.getBrandIds());
}
//保存分类与参数信息
if(CollUtil.isNotEmpty(category.getAttributeIds())){
categoryPropMapper.insertCategoryProp(category.getCategoryId(), category.getAttributeIds());
}
}
@Override
public List<Category> treeSelect(Long shopId,int grade) {
List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>().le(Category::getGrade,grade).eq(Category::getShopId,shopId));
return categoryListToTree(categories);
}
public List<Category> categoryListToTree(List<Category> categorys){<FILL_FUNCTION_BODY>}
public void transformCategoryTree(List<Category> categorys,Map<Long, List<Category>> categoryMap) {
for (Category category : categorys) {
List<Category> nextList = categoryMap.get(category.getCategoryId());
if (CollectionUtils.isEmpty(nextList)) {
continue;
}
// 将排序完成的list设为下一层级
category.setCategories(nextList);
// 处理下 下一层级
transformCategoryTree(nextList, categoryMap);
}
}
}
|
if (CollectionUtils.isEmpty(categorys)) {
return Lists.newArrayList();
}
Map<Long, List<Category>> categoryMap = categorys.stream().collect(Collectors.groupingBy(Category::getParentId));
List<Category> rootList = categoryMap.get(0L);
transformCategoryTree(rootList,categoryMap);
return rootList;
| 978
| 100
| 1,078
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/OrderServiceImpl.java
|
OrderServiceImpl
|
cancelOrders
|
class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
private final OrderMapper orderMapper;
private final SkuMapper skuMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final ApplicationEventPublisher eventPublisher;
@Override
public Order getOrderByOrderNumber(String orderNumber) {
return orderMapper.getOrderByOrderNumber(orderNumber);
}
@Override
@CachePut(cacheNames = "ConfirmOrderCache", key = "#userId")
public ShopCartOrderMergerDto putConfirmOrderCache(String userId, ShopCartOrderMergerDto shopCartOrderMergerDto) {
return shopCartOrderMergerDto;
}
@Override
@Cacheable(cacheNames = "ConfirmOrderCache", key = "#userId")
public ShopCartOrderMergerDto getConfirmOrderCache(String userId) {
return null;
}
@Override
@CacheEvict(cacheNames = "ConfirmOrderCache", key = "#userId")
public void removeConfirmOrderCache(String userId) {
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<Order> submit(String userId, ShopCartOrderMergerDto mergerOrder) {
List<Order> orderList = new ArrayList<>();
// 通过事务提交订单
eventPublisher.publishEvent(new SubmitOrderEvent(mergerOrder, orderList));
// 插入订单
saveBatch(orderList);
List<OrderItem> orderItems = orderList.stream().flatMap(order -> order.getOrderItems().stream()).collect(Collectors.toList());
// 插入订单项,返回主键
orderItemMapper.insertBatch(orderItems);
return orderList;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delivery(Order order) {
orderMapper.updateById(order);
}
@Override
public List<Order> listOrderAndOrderItems(Integer orderStatus, DateTime lessThanUpdateTime) {
return orderMapper.listOrderAndOrderItems(orderStatus, lessThanUpdateTime);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void cancelOrders(List<Order> orders) {<FILL_FUNCTION_BODY>}
@Override
@Transactional(rollbackFor = Exception.class)
public void confirmOrder(List<Order> orders) {
orderMapper.confirmOrder(orders);
for (Order order : orders) {
eventPublisher.publishEvent(new ReceiptOrderEvent(order));
}
}
@Override
public List<Order> listOrdersDetailByOrder(Order order, Date startTime, Date endTime) {
return orderMapper.listOrdersDetailByOrder(order, startTime, endTime);
}
@Override
public IPage<Order> pageOrdersDetailByOrderParam(Page<Order> page, OrderParam orderParam) {
page.setRecords(orderMapper.listOrdersDetailByOrderParam(new PageAdapter(page), orderParam));
page.setTotal(orderMapper.countOrderDetail(orderParam));
return page;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteOrders(List<Order> orders) {
orderMapper.deleteOrders(orders);
}
@Override
public OrderCountData getOrderCount(String userId) {
return orderMapper.getOrderCount(userId);
}
}
|
orderMapper.cancelOrders(orders);
List<OrderItem> allOrderItems = new ArrayList<>();
for (Order order : orders) {
List<OrderItem> orderItems = order.getOrderItems();
allOrderItems.addAll(orderItems);
eventPublisher.publishEvent(new CancelOrderEvent(order));
}
if (CollectionUtil.isEmpty(allOrderItems)) {
return;
}
Map<Long, Integer> prodCollect = new HashMap<>(16);
Map<Long, Integer> skuCollect = new HashMap<>(16);
allOrderItems.stream().collect(Collectors.groupingBy(OrderItem::getProdId)).forEach((prodId, orderItems) -> {
int prodTotalNum = orderItems.stream().mapToInt(OrderItem::getProdCount).sum();
prodCollect.put(prodId, prodTotalNum);
});
productMapper.returnStock(prodCollect);
allOrderItems.stream().collect(Collectors.groupingBy(OrderItem::getSkuId)).forEach((skuId, orderItems) -> {
int prodTotalNum = orderItems.stream().mapToInt(OrderItem::getProdCount).sum();
skuCollect.put(skuId, prodTotalNum);
});
skuMapper.returnStock(skuCollect);
| 926
| 338
| 1,264
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/PayServiceImpl.java
|
PayServiceImpl
|
pay
|
class PayServiceImpl implements PayService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderSettlementMapper orderSettlementMapper;
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private Snowflake snowflake;
/**
* 不同的订单号,同一个支付流水号
*/
@Override
@Transactional(rollbackFor = Exception.class)
public PayInfoDto pay(String userId, PayParam payParam) {<FILL_FUNCTION_BODY>}
@Override
@Transactional(rollbackFor = Exception.class)
public List<String> paySuccess(String payNo, String bizPayNo) {
List<OrderSettlement> orderSettlements = orderSettlementMapper.selectList(new LambdaQueryWrapper<OrderSettlement>().eq(OrderSettlement::getPayNo, payNo));
OrderSettlement settlement = orderSettlements.get(0);
// 订单已支付
if (settlement.getPayStatus() == 1) {
throw new YamiShopBindException("订单已支付");
}
// 修改订单结算信息
if (orderSettlementMapper.updateToPay(payNo, settlement.getVersion()) < 1) {
throw new YamiShopBindException("结算信息已更改");
}
List<String> orderNumbers = orderSettlements.stream().map(OrderSettlement::getOrderNumber).collect(Collectors.toList());
// 将订单改为已支付状态
orderMapper.updateByToPaySuccess(orderNumbers, PayType.WECHATPAY.value());
List<Order> orders = orderNumbers.stream().map(orderNumber -> orderMapper.getOrderByOrderNumber(orderNumber)).collect(Collectors.toList());
eventPublisher.publishEvent(new PaySuccessOrderEvent(orders));
return orderNumbers;
}
}
|
// 不同的订单号的产品名称
StringBuilder prodName = new StringBuilder();
// 支付单号
String payNo = String.valueOf(snowflake.nextId());
String[] orderNumbers = payParam.getOrderNumbers().split(StrUtil.COMMA);
// 修改订单信息
for (String orderNumber : orderNumbers) {
OrderSettlement orderSettlement = new OrderSettlement();
orderSettlement.setPayNo(payNo);
orderSettlement.setPayType(payParam.getPayType());
orderSettlement.setUserId(userId);
orderSettlement.setOrderNumber(orderNumber);
orderSettlementMapper.updateByOrderNumberAndUserId(orderSettlement);
Order order = orderMapper.getOrderByOrderNumber(orderNumber);
prodName.append(order.getProdName()).append(StrUtil.COMMA);
}
// 除了ordernumber不一样,其他都一样
List<OrderSettlement> settlements = orderSettlementMapper.getSettlementsByPayNo(payNo);
// 应支付的总金额
double payAmount = 0.0;
for (OrderSettlement orderSettlement : settlements) {
payAmount = Arith.add(payAmount, orderSettlement.getPayAmount());
}
prodName.substring(0, Math.min(100, prodName.length() - 1));
PayInfoDto payInfoDto = new PayInfoDto();
payInfoDto.setBody(prodName.toString());
payInfoDto.setPayAmount(payAmount);
payInfoDto.setPayNo(payNo);
return payInfoDto;
| 510
| 440
| 950
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/ProdCommServiceImpl.java
|
ProdCommServiceImpl
|
getProdCommDataByProdId
|
class ProdCommServiceImpl extends ServiceImpl<ProdCommMapper, ProdComm> implements ProdCommService {
@Autowired
private ProdCommMapper prodCommMapper;
@Override
public ProdCommDataDto getProdCommDataByProdId(Long prodId) {<FILL_FUNCTION_BODY>}
@Override
public IPage<ProdCommDto> getProdCommDtoPageByUserId(Page page, String userId) {
return prodCommMapper.getProdCommDtoPageByUserId(page,userId);
}
@Override
public IPage<ProdCommDto> getProdCommDtoPageByProdId(Page page, Long prodId, Integer evaluate) {
IPage<ProdCommDto> prodCommDtos = prodCommMapper.getProdCommDtoPageByProdId(page, prodId, evaluate);
prodCommDtos.getRecords().forEach(prodCommDto -> {
// 匿名评价
if (prodCommDto.getIsAnonymous() == 1) {
prodCommDto.setNickName(null);
}
});
return prodCommDtos;
}
@Override
public IPage<ProdComm> getProdCommPage(Page page,ProdComm prodComm) {
return prodCommMapper.getProdCommPage(page,prodComm);
}
}
|
ProdCommDataDto prodCommDataDto=prodCommMapper.getProdCommDataByProdId(prodId);
//计算出好评率
if(prodCommDataDto.getPraiseNumber() == 0||prodCommDataDto.getNumber() == 0){
prodCommDataDto.setPositiveRating(0.0);
}else{
prodCommDataDto.setPositiveRating(Arith.mul(Arith.div(prodCommDataDto.getPraiseNumber(),prodCommDataDto.getNumber()),100));
}
return prodCommDataDto;
| 361
| 156
| 517
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/ProdPropServiceImpl.java
|
ProdPropServiceImpl
|
deleteProdPropAndValues
|
class ProdPropServiceImpl extends ServiceImpl<ProdPropMapper, ProdProp> implements ProdPropService {
@Autowired
private ProdPropMapper prodPropMapper;
@Autowired
private ProdPropValueMapper prodPropValueMapper;
@Autowired
private CategoryPropMapper categoryPropMapper;
@Override
public IPage<ProdProp> pagePropAndValue(ProdProp prodProp, Page<ProdProp> page) {
page.setRecords(prodPropMapper.listPropAndValue(new PageAdapter(page), prodProp));
page.setTotal(prodPropMapper.countPropAndValue(prodProp));
return page;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void saveProdPropAndValues(@Valid ProdProp prodProp) {
ProdProp dbProdProp = prodPropMapper.getProdPropByPropNameAndShopId(prodProp.getPropName(), prodProp.getShopId(), prodProp.getRule());
if (dbProdProp != null) {
throw new YamiShopBindException("已有相同名称规格");
}
prodPropMapper.insert(prodProp);
if (CollUtil.isEmpty(prodProp.getProdPropValues())) {
return;
}
prodPropValueMapper.insertPropValues(prodProp.getPropId(), prodProp.getProdPropValues());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateProdPropAndValues(ProdProp prodProp) {
ProdProp dbProdProp = prodPropMapper.getProdPropByPropNameAndShopId(prodProp.getPropName(), prodProp.getShopId(), prodProp.getRule());
if (dbProdProp != null && !Objects.equals(prodProp.getPropId(), dbProdProp.getPropId())) {
throw new YamiShopBindException("已有相同名称规格");
}
prodPropMapper.updateById(prodProp);
// 先删除原有的属性值,再添加新的属性值
prodPropValueMapper.deleteByPropId(prodProp.getPropId());
if (CollUtil.isEmpty(prodProp.getProdPropValues())) {
return;
}
prodPropValueMapper.insertPropValues(prodProp.getPropId(), prodProp.getProdPropValues());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteProdPropAndValues(Long propId, Integer propRule, Long shopId) {<FILL_FUNCTION_BODY>}
}
|
int deleteRows = prodPropMapper.deleteByPropId(propId, propRule, shopId);
if (deleteRows == 0) {
return;
}
// 删除原有的属性值
prodPropValueMapper.deleteByPropId(propId);
// 如果是参数,删除参数与分类关联信息
if (ProdPropRule.ATTRIBUTE.value().equals(propRule)) {
categoryPropMapper.deleteByPropId(propId);
}
| 655
| 124
| 779
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/ProductServiceImpl.java
|
ProductServiceImpl
|
removeProductByProdId
|
class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
@Autowired
private ProductMapper productMapper;
@Autowired
private SkuMapper skuMapper;
@Autowired
private AttachFileService attachFileService;
@Autowired
private ProdTagReferenceMapper prodTagReferenceMapper;
private static final Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);
@Override
@Transactional(rollbackFor = Exception.class)
public void saveProduct(Product product) {
productMapper.insert(product);
if (CollectionUtil.isNotEmpty(product.getSkuList())) {
skuMapper.insertBatch(product.getProdId(), product.getSkuList());
}
prodTagReferenceMapper.insertBatch(product.getShopId(), product.getProdId(), product.getTagList());
}
@Override
@Transactional(rollbackFor = Exception.class)
@Caching(evict = {
@CacheEvict(cacheNames = "product", key = "#product.prodId"),
@CacheEvict(cacheNames = "skuList", key = "#product.prodId")
})
public void updateProduct(Product product, Product dbProduct) {
productMapper.updateById(product);
List<Long> dbSkuIds = dbProduct.getSkuList().stream().map(Sku::getSkuId).collect(Collectors.toList());
// 将所有该商品的sku标记为已删除状态
skuMapper.deleteByProdId(product.getProdId());
// 接口传入sku列表
List<Sku> skuList = product.getSkuList();
if (CollectionUtil.isEmpty(skuList)) {
return;
}
List<Sku> insertSkuList = new ArrayList<>();
for (Sku sku : skuList) {
sku.setIsDelete(0);
// 如果数据库中原有sku就更新,否者就插入
if (dbSkuIds.contains(sku.getSkuId())) {
skuMapper.updateById(sku);
} else {
insertSkuList.add(sku);
}
}
// 批量插入sku
if (CollectionUtil.isNotEmpty(insertSkuList)) {
skuMapper.insertBatch(product.getProdId(), insertSkuList);
}
//更新分组信息
List<Long> tagList = product.getTagList();
if (CollectionUtil.isNotEmpty(tagList)) {
prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>().eq(ProdTagReference::getProdId, product.getProdId()));
prodTagReferenceMapper.insertBatch(dbProduct.getShopId(), product.getProdId(), tagList);
}
}
@Override
@Cacheable(cacheNames = "product", key = "#prodId")
public Product getProductByProdId(Long prodId) {
return productMapper.selectById(prodId);
}
@Override
@Transactional(rollbackFor = Exception.class)
@Caching(evict = {
@CacheEvict(cacheNames = "product", key = "#prodId"),
@CacheEvict(cacheNames = "skuList", key = "#prodId")
})
public void removeProductByProdId(Long prodId) {<FILL_FUNCTION_BODY>}
@Override
@Caching(evict = {
@CacheEvict(cacheNames = "product", key = "#prodId"),
@CacheEvict(cacheNames = "skuList", key = "#prodId")
})
public void removeProductCacheByProdId(Long prodId) {
}
@Override
public IPage<ProductDto> pageByPutAwayTime(IPage<ProductDto> page) {
return productMapper.pageByPutAwayTime(page);
}
@Override
public IPage<ProductDto> pageByTagId(Page<ProductDto> page, Long tagId) {
return productMapper.pageByTagId(page, tagId);
}
@Override
public IPage<ProductDto> moreBuyProdList(Page<ProductDto> page) {
return productMapper.moreBuyProdList(page);
}
@Override
public IPage<ProductDto> pageByCategoryId(Page<ProductDto> page, Long categoryId) {
return productMapper.pageByCategoryId(page, categoryId);
}
@Override
public IPage<SearchProdDto> getSearchProdDtoPageByProdName(Page page, String prodName, Integer sort, Integer orderBy) {
IPage<SearchProdDto> searchProdDtoPage = productMapper.getSearchProdDtoPageByProdName(page, prodName, sort, orderBy);
for (SearchProdDto searchProdDto : searchProdDtoPage.getRecords()) {
//计算出好评率
if (searchProdDto.getPraiseNumber() == 0 || searchProdDto.getProdCommNumber() == 0) {
searchProdDto.setPositiveRating(0.0);
} else {
searchProdDto.setPositiveRating(Arith.mul(Arith.div(searchProdDto.getPraiseNumber(), searchProdDto.getProdCommNumber()), 100));
}
}
return searchProdDtoPage;
}
@Override
public List<TagProductDto> tagProdList() {
return productMapper.tagProdList();
}
@Override
public IPage<ProductDto> collectionProds(PageParam page, String userId) {
return productMapper.collectionProds(page, userId);
}
}
|
Product dbProduct = getProductByProdId(prodId);
productMapper.deleteById(prodId);
skuMapper.deleteByProdId(prodId);
//删除商品关联的分组标签
prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>()
.eq(ProdTagReference::getProdId, prodId));
// 删除数据库中的商品图片
// if (StrUtil.isNotBlank(dbProduct.getImgs())) {
// String[] imgs = dbProduct.getImgs().split(StrUtil.COMMA);
// for (String img : imgs) {
// attachFileService.deleteFile(img);
// }
// }
| 1,507
| 188
| 1,695
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/ShopDetailServiceImpl.java
|
ShopDetailServiceImpl
|
updateShopDetail
|
class ShopDetailServiceImpl extends ServiceImpl<ShopDetailMapper, ShopDetail> implements ShopDetailService {
@Autowired
private ShopDetailMapper shopDetailMapper;
@Autowired
private AttachFileService attachFileService;
@Override
@Transactional(rollbackFor=Exception.class)
@CacheEvict(cacheNames = "shop_detail", key = "#shopDetail.shopId")
public void updateShopDetail(ShopDetail shopDetail,ShopDetail dbShopDetail) {<FILL_FUNCTION_BODY>}
@Override
@Transactional(rollbackFor=Exception.class)
@CacheEvict(cacheNames = "shop_detail", key = "#shopId")
public void deleteShopDetailByShopId(Long shopId) {
shopDetailMapper.deleteById(shopId);
}
@Override
@Cacheable(cacheNames = "shop_detail", key = "#shopId")
public ShopDetail getShopDetailByShopId(Long shopId) {
return shopDetailMapper.selectById(shopId);
}
@Override
@CacheEvict(cacheNames = "shop_detail", key = "#shopId")
public void removeShopDetailCacheByShopId(Long shopId) {
}
}
|
// 更新除数据库中的信息,再删除图片
shopDetailMapper.updateById(shopDetail);
// if (!Objects.equals(dbShopDetail.getShopLogo(), shopDetail.getShopLogo())) {
// // 删除logo
// attachFileService.deleteFile(shopDetail.getShopLogo());
// }
// // 店铺图片
// String shopPhotos = shopDetail.getShopPhotos();
// String[] shopPhotoArray =StrUtil.isBlank(shopPhotos)?new String[]{}: shopPhotos.split(",");
//
// // 数据库中的店铺图片
// String dbShopPhotos = dbShopDetail.getShopPhotos();
// String[] dbShopPhotoArray =StrUtil.isBlank(dbShopPhotos)?new String[]{}: dbShopPhotos.split(",");
// for (String dbShopPhoto : dbShopPhotoArray) {
// // 如果新插入的图片中没有旧数据中的图片,则删除旧数据中的图片
// if (!ArrayUtil.contains(shopPhotoArray, dbShopPhoto)) {
// attachFileService.deleteFile(dbShopPhoto);
// }
// }
| 298
| 299
| 597
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/SmsLogServiceImpl.java
|
SmsLogServiceImpl
|
sendSms
|
class SmsLogServiceImpl extends ServiceImpl<SmsLogMapper, SmsLog> implements SmsLogService {
private final SmsLogMapper smsLogMapper;
private final AliDaYu aLiDaYu;
/**
* 产品名称:云通信短信API产品,开发者无需替换
*/
private static final String PRODUCT = "Dysmsapi";
/**
* 产品域名,开发者无需替换
*/
private static final String DOMAIN = "dysmsapi.aliyuncs.com";
/**
* 当天最大验证码短信发送量
*/
private static final int TODAY_MAX_SEND_VALID_SMS_NUMBER = 10;
/**
* 短信发送成功的标志
*/
private static final String SEND_SMS_SUCCESS_FLAG = "OK";
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public void sendSms(SmsType smsType, String userId, String mobile, Map<String, String> params) {
SmsLog smsLog = new SmsLog();
if (smsType.equals(SmsType.VALID)) {
// 阿里云短信规定:使用同一个签名,默认情况下对同一个手机号码发送验证码,最多支持1条/分钟,5条/小时,10条/天。
long todaySendSmsNumber = smsLogMapper.selectCount(new LambdaQueryWrapper<SmsLog>()
.gt(SmsLog::getRecDate, DateUtil.beginOfDay(new Date()))
.lt(SmsLog::getRecDate, DateUtil.endOfDay(new Date()))
.eq(SmsLog::getUserId, userId)
.eq(SmsLog::getType, smsType.value()));
if (todaySendSmsNumber >= TODAY_MAX_SEND_VALID_SMS_NUMBER) {
throw new YamiShopBindException("今日发送短信验证码次数已达到上限");
}
// 将上一条验证码失效
smsLogMapper.invalidSmsByMobileAndType(mobile, smsType.value());
String code = RandomUtil.randomNumbers(6);
params.put("code", code);
}
smsLog.setType(smsType.value());
smsLog.setMobileCode(params.get("code"));
smsLog.setRecDate(new Date());
smsLog.setStatus(1);
smsLog.setUserId(userId);
smsLog.setUserPhone(mobile);
smsLog.setContent(formatContent(smsType, params));
smsLogMapper.insert(smsLog);
try {
this.sendSms(mobile, smsType.getTemplateCode(), params);
} catch (ClientException e) {
throw new YamiShopBindException("发送短信失败,请稍后再试");
}
}
private void sendSms(String mobile, String templateCode, Map<String, String> params) throws ClientException {<FILL_FUNCTION_BODY>}
private String formatContent(SmsType smsType, Map<String, String> params) {
if (CollectionUtil.isEmpty(params)) {
return smsType.getContent();
}
String content = smsType.getContent();
for (Entry<String, String> element : params.entrySet()) {
content = content.replace("${" + element.getKey() + "}", element.getValue());
}
return content;
}
}
|
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aLiDaYu.getAccessKeyId(), aLiDaYu.getAccessKeySecret());
DefaultProfile.addEndpoint("cn-hangzhou", PRODUCT, DOMAIN);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(mobile);
//必填:短信签名-可在短信控制台中找到
request.setSignName(aLiDaYu.getSignName());
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode(templateCode);
request.setTemplateParam(Json.toJsonString(params));
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
log.debug(Json.toJsonString(sendSmsResponse));
if (sendSmsResponse.getCode() == null || !SEND_SMS_SUCCESS_FLAG.equals(sendSmsResponse.getCode())) {
throw new YamiShopBindException("发送短信失败,请稍后再试:" + sendSmsResponse.getMessage());
}
| 929
| 424
| 1,353
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/TransportManagerServiceImpl.java
|
TransportManagerServiceImpl
|
getPiece
|
class TransportManagerServiceImpl implements TransportManagerService {
@Autowired
private ProductService productService;
@Autowired
private SkuService skuService;
@Autowired
private TransportService transportService;
@Override
public Double calculateTransfee(ProductItemDto productItem, UserAddr userAddr) {
Product product = productService.getProductByProdId(productItem.getProdId());
// 用户所在城市id
Long cityId = userAddr.getCityId();
Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
// 没有店铺配送的方式
if (!deliveryModeVO.getHasShopDelivery()) {
return 0.0;
}
if (product.getDeliveryTemplateId() == null) {
return 0.0;
}
//找出该产品的运费项
Transport transport = transportService.getTransportAndAllItems(product.getDeliveryTemplateId());
//商家把运费模板删除
if (transport == null) {
return 0.0;
}
Sku sku = skuService.getSkuBySkuId(productItem.getSkuId());
// 用于计算运费的件数
Double piece = getPiece(productItem, transport, sku);
//如果有包邮的条件
if (transport.getHasFreeCondition() == 1) {
// 获取所有的包邮条件
List<TransfeeFree> transfeeFrees = transport.getTransfeeFrees();
for (TransfeeFree transfeeFree : transfeeFrees) {
List<Area> freeCityList = transfeeFree.getFreeCityList();
for (Area freeCity : freeCityList) {
if (!Objects.equals(freeCity.getAreaId(), cityId)) {
continue;
}
//包邮方式 (0 满x件/重量/体积包邮 1满金额包邮 2满x件/重量/体积且满金额包邮)
boolean isFree = (transfeeFree.getFreeType() == 0 && piece >= transfeeFree.getPiece()) ||
(transfeeFree.getFreeType() == 1 && productItem.getProductTotalAmount() >= transfeeFree.getAmount()) ||
(transfeeFree.getFreeType() == 2 && piece >= transfeeFree.getPiece() && productItem.getProductTotalAmount() >= transfeeFree.getAmount());
if (isFree) {
return 0.0;
}
}
}
}
//订单的运费项
Transfee transfee = null;
List<Transfee> transfees = transport.getTransfees();
for (Transfee dbTransfee : transfees) {
// 将该商品的运费设置为默认运费
if (transfee == null && CollectionUtil.isEmpty(dbTransfee.getCityList())) {
transfee = dbTransfee;
}
// 如果在运费模板中的城市找到该商品的运费,则将该商品由默认运费设置为该城市的运费
for (Area area : dbTransfee.getCityList()) {
if (area.getAreaId().equals(cityId)) {
transfee = dbTransfee;
break;
}
}
// 如果在运费模板中的城市找到该商品的运费,则退出整个循环
if (transfee != null && CollectionUtil.isNotEmpty(transfee.getCityList())) {
break;
}
}
// 如果无法获取到任何运费相关信息,则返回0运费
if (transfee == null) {
return 0.0;
}
// 产品的运费
Double fee = transfee.getFirstFee();
// 如果件数大于首件数量,则开始计算超出的运费
if (piece > transfee.getFirstPiece()) {
// 续件数量
Double prodContinuousPiece = Arith.sub(piece, transfee.getFirstPiece());
// 续件数量的倍数,向上取整
Integer mulNumber = (int) Math.ceil(Arith.div(prodContinuousPiece, transfee.getContinuousPiece()));
// 续件数量运费
Double continuousFee = Arith.mul(mulNumber, transfee.getContinuousFee());
fee = Arith.add(fee, continuousFee);
}
return fee;
}
private Double getPiece(ProductItemDto productItem, Transport transport, Sku sku) {<FILL_FUNCTION_BODY>}
}
|
Double piece = 0.0;
if (Objects.equals(TransportChargeType.COUNT.value(), transport.getChargeType())) {
// 按件数计算运费
piece = Double.valueOf(productItem.getProdCount());
} else if (Objects.equals(TransportChargeType.WEIGHT.value(), transport.getChargeType())) {
// 按重量计算运费
double weight = sku.getWeight() == null ? 0 : sku.getWeight();
piece = Arith.mul(weight, productItem.getProdCount());
} else if (Objects.equals(TransportChargeType.VOLUME.value(), transport.getChargeType())) {
// 按体积计算运费
double volume = sku.getVolume() == null ? 0 : sku.getVolume();
piece = Arith.mul(volume, productItem.getProdCount());
}
return piece;
| 1,204
| 237
| 1,441
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/TransportServiceImpl.java
|
TransportServiceImpl
|
updateTransportAndTransfee
|
class TransportServiceImpl extends ServiceImpl<TransportMapper, Transport> implements TransportService {
private final TransportMapper transportMapper;
private final TransfeeMapper transfeeMapper;
private final TranscityMapper transcityMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void insertTransportAndTransfee(Transport transport) {
// 插入运费模板
transportMapper.insert(transport);
// 插入所有的运费项和城市
insertTransfeeAndTranscity(transport);
// 插入所有的指定包邮条件项和城市
if (transport.getHasFreeCondition() == 1) {
insertTransfeeFreeAndTranscityFree(transport);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(cacheNames = "TransportAndAllItems", key = "#transport.transportId")
public void updateTransportAndTransfee(Transport transport) {<FILL_FUNCTION_BODY>}
private void insertTransfeeFreeAndTranscityFree(Transport transport) {
Long transportId = transport.getTransportId();
List<TransfeeFree> transfeeFrees = transport.getTransfeeFrees();
for (TransfeeFree transfeeFree : transfeeFrees) {
transfeeFree.setTransportId(transportId);
}
// 批量插入指定包邮条件项 并返回指定包邮条件项 id,供下面循环使用
transfeeMapper.insertTransfeeFrees(transfeeFrees);
List<TranscityFree> transcityFrees = new ArrayList<>();
for (TransfeeFree transfeeFree : transfeeFrees) {
List<Area> cityList = transfeeFree.getFreeCityList();
if (CollectionUtil.isEmpty(cityList)) {
throw new YamiShopBindException("请选择指定包邮城市");
}
// 当地址不为空时
for (Area area : cityList) {
TranscityFree transcityParam = new TranscityFree();
transcityParam.setTransfeeFreeId(transfeeFree.getTransfeeFreeId());
transcityParam.setFreeCityId(area.getAreaId());
transcityFrees.add(transcityParam);
}
}
// 批量插入指定包邮条件项中的城市
if (CollectionUtil.isNotEmpty(transcityFrees)) {
transcityMapper.insertTranscityFrees(transcityFrees);
}
}
private void insertTransfeeAndTranscity(Transport transport) {
Long transportId = transport.getTransportId();
List<Transfee> transfees = transport.getTransfees();
for (Transfee transfee : transfees) {
transfee.setTransportId(transportId);
}
// 批量插入运费项 并返回运费项id,供下面循环使用
transfeeMapper.insertTransfees(transfees);
List<Transcity> transcities = new ArrayList<>();
for (Transfee transfee : transfees) {
List<Area> cityList = transfee.getCityList();
if (CollectionUtil.isEmpty(cityList)) {
continue;
}
// 当地址不为空时
for (Area area : cityList) {
Transcity transcityParam = new Transcity();
transcityParam.setTransfeeId(transfee.getTransfeeId());
transcityParam.setCityId(area.getAreaId());
transcities.add(transcityParam);
}
}
// 批量插入运费项中的城市
if (CollectionUtil.isNotEmpty(transcities)) {
transcityMapper.insertTranscities(transcities);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteTransportAndTransfeeAndTranscity(Long[] ids) {
for (Long id : ids) {
Transport dbTransport = getTransportAndAllItems(id);
List<Long> transfeeIds = dbTransport.getTransfees().stream().map(Transfee::getTransfeeId).collect(Collectors.toList());
// 删除所有运费项包含的城市
transcityMapper.deleteBatchByTransfeeIds(transfeeIds);
// 删除所有的运费项
transfeeMapper.deleteByTransportId(id);
}
// 删除运费模板
transportMapper.deleteTransports(ids);
}
@Override
@Cacheable(cacheNames = "TransportAndAllItems", key = "#transportId")
public Transport getTransportAndAllItems(Long transportId) {
Transport transport = transportMapper.getTransportAndTransfeeAndTranscity(transportId);
if (transport == null) {
return null;
}
List<TransfeeFree> transfeeFrees = transportMapper.getTransfeeFreeAndTranscityFreeByTransportId(transportId);
transport.setTransfeeFrees(transfeeFrees);
return transport;
}
@Override
@CacheEvict(cacheNames = "TransportAndAllItems", key = "#transportId")
public void removeTransportAndAllItemsCache(Long transportId) {
}
}
|
Transport dbTransport = getTransportAndAllItems(transport.getTransportId());
// 删除所有的运费项
transfeeMapper.deleteByTransportId(transport.getTransportId());
// 删除所有的指定包邮条件项
transfeeMapper.deleteTransfeeFreesByTransportId(transport.getTransportId());
List<Long> transfeeIds = dbTransport.getTransfees().stream().map(Transfee::getTransfeeId).collect(Collectors.toList());
List<Long> transfeeFreeIds = dbTransport.getTransfeeFrees().stream().map(TransfeeFree::getTransfeeFreeId).collect(Collectors.toList());
// 删除所有运费项包含的城市
transcityMapper.deleteBatchByTransfeeIds(transfeeIds);
if(CollectionUtil.isNotEmpty(transfeeFreeIds)) {
// 删除所有指定包邮条件项包含的城市
transcityMapper.deleteBatchByTransfeeFreeIds(transfeeFreeIds);
}
// 更新运费模板
transportMapper.updateById(transport);
// 插入所有的运费项和城市
insertTransfeeAndTranscity(transport);
// 插入所有的指定包邮条件项和城市
if (transport.getHasFreeCondition() == 1) {
insertTransfeeFreeAndTranscityFree(transport);
}
| 1,342
| 366
| 1,708
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/UserAddrServiceImpl.java
|
UserAddrServiceImpl
|
getUserAddrByUserId
|
class UserAddrServiceImpl extends ServiceImpl<UserAddrMapper, UserAddr> implements UserAddrService {
@Autowired
private UserAddrMapper userAddrMapper;
@Override
public UserAddr getDefaultUserAddr(String userId) {
return userAddrMapper.getDefaultUserAddr(userId);
}
@Override
@Transactional(rollbackFor=Exception.class)
public void updateDefaultUserAddr(Long addrId, String userId) {
userAddrMapper.removeDefaultUserAddr(userId);
int setCount = userAddrMapper.setDefaultUserAddr(addrId,userId);
if (setCount == 0) {
throw new YamiShopBindException("无法修改用户默认地址,请稍后再试");
}
}
@Override
@CacheEvict(cacheNames = "UserAddrDto", key = "#userId+':'+#addrId")
public void removeUserAddrByUserId(Long addrId, String userId) {
}
@Override
@Cacheable(cacheNames = "UserAddrDto", key = "#userId+':'+#addrId")
public UserAddr getUserAddrByUserId(Long addrId, String userId) {<FILL_FUNCTION_BODY>}
}
|
if (addrId == 0) {
return userAddrMapper.getDefaultUserAddr(userId);
}
return userAddrMapper.getUserAddrByUserIdAndAddrId(userId, addrId);
| 306
| 54
| 360
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-service/src/main/java/com/yami/shop/service/impl/UserServiceImpl.java
|
UserServiceImpl
|
validate
|
class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
@Cacheable(cacheNames = "user", key = "#userId")
public User getUserByUserId(String userId) {
return userMapper.selectById(userId);
}
/**
* 看看有没有校验验证码成功的标识
* @param userRegisterParam
* @param checkRegisterSmsFlag
*/
@Override
public void validate(UserRegisterParam userRegisterParam, String checkRegisterSmsFlag) {<FILL_FUNCTION_BODY>}
}
|
if (StrUtil.isBlank(userRegisterParam.getCheckRegisterSmsFlag())) {
// 验证码已过期,请重新发送验证码校验
throw new YamiShopBindException("验证码已过期,请重新发送验证码校验");
} else {
String checkRegisterSmsFlagMobile = RedisUtil.get(checkRegisterSmsFlag);
if (!Objects.equals(checkRegisterSmsFlagMobile, userRegisterParam.getMobile())) {
// 验证码已过期,请重新发送验证码校验
throw new YamiShopBindException("验证码已过期,请重新发送验证码校验");
}
}
| 165
| 176
| 341
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/aspect/SysLogAspect.java
|
SysLogAspect
|
around
|
class SysLogAspect {
@Autowired
private SysLogService sysLogService;
private static Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
@Around("@annotation(sysLog)")
public Object around(ProceedingJoinPoint joinPoint,com.yami.shop.common.annotation.SysLog sysLog) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
long beginTime = SystemClock.now();
//执行方法
Object result = joinPoint.proceed();
//执行时长(毫秒)
long time = SystemClock.now() - beginTime;
SysLog sysLogEntity = new SysLog();
if(sysLog != null){
//注解上的描述
sysLogEntity.setOperation(sysLog.value());
}
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
sysLogEntity.setMethod(className + "." + methodName + "()");
//请求的参数
Object[] args = joinPoint.getArgs();
String params = Json.toJsonString(args[0]);
sysLogEntity.setParams(params);
//设置IP地址
sysLogEntity.setIp(IpHelper.getIpAddr());
//用户名
String username = SecurityUtils.getSysUser().getUsername();
sysLogEntity.setUsername(username);
sysLogEntity.setTime(time);
sysLogEntity.setCreateDate(new Date());
//保存系统日志
sysLogService.save(sysLogEntity);
return result;
| 108
| 335
| 443
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/controller/SysLogController.java
|
SysLogController
|
page
|
class SysLogController {
@Autowired
private SysLogService sysLogService;
/**
* 列表
*/
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('sys:log:page')")
public ServerResponseEntity<IPage<SysLog>> page(SysLog sysLog,PageParam<SysLog> page){<FILL_FUNCTION_BODY>}
}
|
IPage<SysLog> sysLogs = sysLogService.page(page,
new LambdaQueryWrapper<SysLog>()
.like(StrUtil.isNotBlank(sysLog.getUsername()),SysLog::getUsername, sysLog.getUsername())
.like(StrUtil.isNotBlank(sysLog.getOperation()), SysLog::getOperation,sysLog.getOperation()));
return ServerResponseEntity.success(sysLogs);
| 108
| 119
| 227
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/controller/SysMenuController.java
|
SysMenuController
|
delete
|
class SysMenuController{
private final SysMenuService sysMenuService;
@GetMapping("/nav")
@Operation(summary = "获取用户所拥有的菜单和权限" , description = "通过登陆用户的userId获取用户所拥有的菜单和权限")
public ServerResponseEntity<Map<Object, Object>> nav(){
List<SysMenu> menuList = sysMenuService.listMenuByUserId(SecurityUtils.getSysUser().getUserId());
return ServerResponseEntity.success(MapUtil.builder().put("menuList", menuList).put("authorities", SecurityUtils.getSysUser().getAuthorities()).build());
}
/**
* 获取菜单页面的表
* @return
*/
@GetMapping("/table")
public ServerResponseEntity<List<SysMenu>> table(){
List<SysMenu> sysMenuList = sysMenuService.listMenuAndBtn();
return ServerResponseEntity.success(sysMenuList);
}
/**
* 所有菜单列表(用于新建、修改角色时 获取菜单的信息)
*/
@GetMapping("/list")
@Operation(summary = "获取用户所拥有的菜单(不包括按钮)" , description = "通过登陆用户的userId获取用户所拥有的菜单和权限")
public ServerResponseEntity<List<SysMenu>> list(){
List<SysMenu> sysMenuList= sysMenuService.listSimpleMenuNoButton();
return ServerResponseEntity.success(sysMenuList);
}
/**
* 选择菜单
*/
@GetMapping("/listRootMenu")
public ServerResponseEntity<List<SysMenu>> listRootMenu(){
//查询列表数据
List<SysMenu> menuList = sysMenuService.listRootMenu();
return ServerResponseEntity.success(menuList);
}
/**
* 选择子菜单
*/
@GetMapping("/listChildrenMenu")
public ServerResponseEntity<List<SysMenu>> listChildrenMenu(Long parentId){
//查询列表数据
List<SysMenu> menuList = sysMenuService.listChildrenMenuByParentId(parentId);
return ServerResponseEntity.success(menuList);
}
/**
* 菜单信息
*/
@GetMapping("/info/{menuId}")
@PreAuthorize("@pms.hasPermission('sys:menu:info')")
public ServerResponseEntity<SysMenu> info(@PathVariable("menuId") Long menuId){
SysMenu menu = sysMenuService.getById(menuId);
return ServerResponseEntity.success(menu);
}
/**
* 保存
*/
@SysLog("保存菜单")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys:menu:save')")
public ServerResponseEntity<Void> save(@Valid @RequestBody SysMenu menu){
//数据校验
verifyForm(menu);
sysMenuService.save(menu);
return ServerResponseEntity.success();
}
/**
* 修改
*/
@SysLog("修改菜单")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:menu:update')")
public ServerResponseEntity<String> update(@Valid @RequestBody SysMenu menu){
//数据校验
verifyForm(menu);
if(menu.getType() == MenuType.MENU.getValue()){
if(StrUtil.isBlank(menu.getUrl())){
return ServerResponseEntity.showFailMsg("菜单URL不能为空");
}
}
sysMenuService.updateById(menu);
return ServerResponseEntity.success();
}
/**
* 删除
*/
@SysLog("删除菜单")
@DeleteMapping("/{menuId}")
@PreAuthorize("@pms.hasPermission('sys:menu:delete')")
public ServerResponseEntity<String> delete(@PathVariable Long menuId){<FILL_FUNCTION_BODY>}
/**
* 验证参数是否正确
*/
private void verifyForm(SysMenu menu){
if(menu.getType() == MenuType.MENU.getValue()){
if(StrUtil.isBlank(menu.getUrl())){
throw new YamiShopBindException("菜单URL不能为空");
}
}
if(Objects.equals(menu.getMenuId(), menu.getParentId())){
throw new YamiShopBindException("自己不能是自己的上级");
}
//上级菜单类型
int parentType = MenuType.CATALOG.getValue();
if(menu.getParentId() != 0){
SysMenu parentMenu = sysMenuService.getById(menu.getParentId());
parentType = parentMenu.getType();
}
//目录、菜单
if(menu.getType() == MenuType.CATALOG.getValue() ||
menu.getType() == MenuType.MENU.getValue()){
if(parentType != MenuType.CATALOG.getValue()){
throw new YamiShopBindException("上级菜单只能为目录类型");
}
return ;
}
//按钮
if(menu.getType() == MenuType.BUTTON.getValue()){
if(parentType != MenuType.MENU.getValue()){
throw new YamiShopBindException("上级菜单只能为菜单类型");
}
}
}
}
|
if(menuId <= Constant.SYS_MENU_MAX_ID){
return ServerResponseEntity.showFailMsg("系统菜单,不能删除");
}
//判断是否有子菜单或按钮
List<SysMenu> menuList = sysMenuService.listChildrenMenuByParentId(menuId);
if(menuList.size() > 0){
return ServerResponseEntity.showFailMsg("请先删除子菜单或按钮");
}
sysMenuService.deleteMenuAndRoleMenu(menuId);
return ServerResponseEntity.success();
| 1,376
| 149
| 1,525
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/controller/SysRoleController.java
|
SysRoleController
|
info
|
class SysRoleController{
@Autowired
private SysRoleService sysRoleService;
@Autowired
private SysMenuService sysMenuService;
/**
* 角色列表
*/
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('sys:role:page')")
public ServerResponseEntity<IPage<SysRole>> page(String roleName,PageParam<SysRole> page){
IPage<SysRole> sysRoles = sysRoleService.page(page,new LambdaQueryWrapper<SysRole>().like(StrUtil.isNotBlank(roleName),SysRole::getRoleName,roleName));
return ServerResponseEntity.success(sysRoles);
}
/**
* 角色列表
*/
@GetMapping("/list")
@PreAuthorize("@pms.hasPermission('sys:role:list')")
public ServerResponseEntity<List<SysRole>> list(){
List<SysRole> list = sysRoleService.list();
return ServerResponseEntity.success(list);
}
/**
* 角色信息
*/
@GetMapping("/info/{roleId}")
@PreAuthorize("@pms.hasPermission('sys:role:info')")
public ServerResponseEntity<SysRole> info(@PathVariable("roleId") Long roleId){<FILL_FUNCTION_BODY>}
/**
* 保存角色
*/
@SysLog("保存角色")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys:role:save')")
public ServerResponseEntity<Void> save(@RequestBody SysRole role){
sysRoleService.saveRoleAndRoleMenu(role);
return ServerResponseEntity.success();
}
/**
* 修改角色
*/
@SysLog("修改角色")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:role:update')")
public ServerResponseEntity<Void> update(@RequestBody SysRole role){
sysRoleService.updateRoleAndRoleMenu(role);
return ServerResponseEntity.success();
}
/**
* 删除角色
*/
@SysLog("删除角色")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys:role:delete')")
public ServerResponseEntity<Void> delete(@RequestBody Long[] roleIds){
sysRoleService.deleteBatch(roleIds);
return ServerResponseEntity.success();
}
}
|
SysRole role = sysRoleService.getById(roleId);
//查询角色对应的菜单
List<Long> menuList = sysMenuService.listMenuIdByRoleId(roleId);
role.setMenuIdList(menuList);
return ServerResponseEntity.success(role);
| 619
| 84
| 703
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/controller/SysUserController.java
|
SysUserController
|
update
|
class SysUserController {
@Autowired
private SysUserService sysUserService;
@Autowired
private SysRoleService sysRoleService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private PasswordManager passwordManager;
@Autowired
private TokenStore tokenStore;
/**
* 所有用户列表
*/
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('sys:user:page')")
public ServerResponseEntity<IPage<SysUser>> page(String username,PageParam<SysUser> page){
IPage<SysUser> sysUserPage = sysUserService.page(page, new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getShopId, SecurityUtils.getSysUser().getShopId())
.like(StrUtil.isNotBlank(username), SysUser::getUsername, username));
return ServerResponseEntity.success(sysUserPage);
}
/**
* 获取登录的用户信息
*/
@GetMapping("/info")
public ServerResponseEntity<SysUser> info(){
return ServerResponseEntity.success(sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId()));
}
/**
* 修改登录用户密码
*/
@SysLog("修改密码")
@PostMapping("/password")
@Operation(summary = "修改密码" , description = "修改当前登陆用户的密码")
public ServerResponseEntity<String> password(@RequestBody @Valid UpdatePasswordDto param){
Long userId = SecurityUtils.getSysUser().getUserId();
// 开源版代码,禁止用户修改admin 的账号密码
// 正式使用时,删除此部分代码即可
if (Objects.equals(1L,userId) && StrUtil.isNotBlank(param.getNewPassword())) {
throw new YamiShopBindException("禁止修改admin的账号密码");
}
SysUser dbUser = sysUserService.getSysUserById(userId);
String password = passwordManager.decryptPassword(param.getPassword());
if (!passwordEncoder.matches(password, dbUser.getPassword())) {
return ServerResponseEntity.showFailMsg("原密码不正确");
}
//新密码
String newPassword = passwordEncoder.encode(passwordManager.decryptPassword(param.getNewPassword()));
// 更新密码
sysUserService.updatePasswordByUserId(userId, newPassword);
tokenStore.deleteAllToken(String.valueOf(SysTypeEnum.ADMIN.value()),String.valueOf(userId));
return ServerResponseEntity.success();
}
/**
* 用户信息
*/
@GetMapping("/info/{userId}")
@PreAuthorize("@pms.hasPermission('sys:user:info')")
public ServerResponseEntity<SysUser> info(@PathVariable("userId") Long userId){
SysUser user = sysUserService.getSysUserById(userId);
user.setUserId(null);
if (!Objects.equals(user.getShopId(), SecurityUtils.getSysUser().getShopId())) {
throw new YamiShopBindException("没有权限获取该用户信息");
}
//获取用户所属的角色列表
List<Long> roleIdList = sysRoleService.listRoleIdByUserId(userId);
user.setRoleIdList(roleIdList);
return ServerResponseEntity.success(user);
}
/**
* 保存用户
*/
@SysLog("保存用户")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys:user:save')")
public ServerResponseEntity<String> save(@Valid @RequestBody SysUser user){
String username = user.getUsername();
SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getUsername, username));
if (dbUser!=null) {
return ServerResponseEntity.showFailMsg("该用户已存在");
}
user.setShopId(SecurityUtils.getSysUser().getShopId());
user.setPassword(passwordEncoder.encode(passwordManager.decryptPassword(user.getPassword())));
sysUserService.saveUserAndUserRole(user);
return ServerResponseEntity.success();
}
/**
* 修改用户
*/
@SysLog("修改用户")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:user:update')")
public ServerResponseEntity<String> update(@Valid @RequestBody SysUser user){<FILL_FUNCTION_BODY>}
/**
* 删除用户
*/
@SysLog("删除用户")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys:user:delete')")
public ServerResponseEntity<String> delete(@RequestBody Long[] userIds){
if (userIds.length == 0) {
return ServerResponseEntity.showFailMsg("请选择需要删除的用户");
}
if(ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)){
return ServerResponseEntity.showFailMsg("系统管理员不能删除");
}
if(ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())){
return ServerResponseEntity.showFailMsg("当前用户不能删除");
}
sysUserService.deleteBatch(userIds,SecurityUtils.getSysUser().getShopId());
return ServerResponseEntity.success();
}
}
|
String password = passwordManager.decryptPassword(user.getPassword());
SysUser dbUser = sysUserService.getSysUserById(user.getUserId());
if (!Objects.equals(dbUser.getShopId(), SecurityUtils.getSysUser().getShopId())) {
throw new YamiShopBindException("没有权限修改该用户信息");
}
SysUser dbUserNameInfo = sysUserService.getByUserName(user.getUsername());
if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getUserId(),user.getUserId())) {
return ServerResponseEntity.showFailMsg("该用户已存在");
}
if (StrUtil.isBlank(password)) {
user.setPassword(null);
}else {
user.setPassword(passwordEncoder.encode(password));
}
// 开源版代码,禁止用户修改admin 的账号密码密码
// 正式使用时,删除此部分代码即可
boolean is = Objects.equals(1L,dbUser.getUserId()) && (StrUtil.isNotBlank(password) || !StrUtil.equals("admin",user.getUsername()));
if (is) {
throw new YamiShopBindException("禁止修改admin的账号密码");
}
if (Objects.equals(1L,user.getUserId()) && user.getStatus()==0) {
throw new YamiShopBindException("admin用户不可以被禁用");
}
sysUserService.updateUserAndUserRole(user);
return ServerResponseEntity.success();
| 1,417
| 415
| 1,832
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/service/impl/SysMenuServiceImpl.java
|
SysMenuServiceImpl
|
listMenuByUserId
|
class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
private final SysRoleMenuMapper sysRoleMenuMapper;
private final SysMenuMapper sysMenuMapper;
@Override
public List<SysMenu> listMenuByUserId(Long userId) {<FILL_FUNCTION_BODY>}
@Override
public void deleteMenuAndRoleMenu(Long menuId){
//删除菜单
this.removeById(menuId);
//删除菜单与角色关联
sysRoleMenuMapper.deleteByMenuId(menuId);
}
@Override
public List<Long> listMenuIdByRoleId(Long roleId) {
return sysMenuMapper.listMenuIdByRoleId(roleId);
}
@Override
public List<SysMenu> listSimpleMenuNoButton() {
return sysMenuMapper.listSimpleMenuNoButton();
}
@Override
public List<SysMenu> listRootMenu() {
return sysMenuMapper.listRootMenu();
}
@Override
public List<SysMenu> listChildrenMenuByParentId(Long parentId) {
return sysMenuMapper.listChildrenMenuByParentId(parentId);
}
@Override
public List<SysMenu> listMenuAndBtn() {
return sysMenuMapper.listMenuAndBtn();
}
}
|
// 用户的所有菜单信息
List<SysMenu> sysMenus ;
//系统管理员,拥有最高权限
if(userId == Constant.SUPER_ADMIN_ID){
sysMenus = sysMenuMapper.listMenu();
}else {
sysMenus = sysMenuMapper.listMenuByUserId(userId);
}
Map<Long, List<SysMenu>> sysMenuLevelMap = sysMenus.stream()
.sorted(Comparator.comparing(SysMenu::getOrderNum))
.collect(Collectors.groupingBy(SysMenu::getParentId));
// 一级菜单
List<SysMenu> rootMenu = sysMenuLevelMap.get(0L);
if (CollectionUtil.isEmpty(rootMenu)) {
return Collections.emptyList();
}
// 二级菜单
for (SysMenu sysMenu : rootMenu) {
sysMenu.setList(sysMenuLevelMap.get(sysMenu.getMenuId()));
}
return rootMenu;
| 339
| 275
| 614
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/service/impl/SysRoleServiceImpl.java
|
SysRoleServiceImpl
|
saveRoleAndRoleMenu
|
class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
private final SysRoleMenuMapper sysRoleMenuMapper;
private final SysUserRoleMapper sysUserRoleMapper;
private final SysRoleMapper sysRoleMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void saveRoleAndRoleMenu(SysRole role) {<FILL_FUNCTION_BODY>}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateRoleAndRoleMenu(SysRole role) {
// 更新角色
sysRoleMapper.updateById(role);
//先删除角色与菜单关系
sysRoleMenuMapper.deleteBatch(new Long[]{role.getRoleId()});
if (CollectionUtil.isEmpty(role.getMenuIdList())) {
return;
}
//保存角色与菜单关系
sysRoleMenuMapper.insertRoleAndRoleMenu(role.getRoleId(), role.getMenuIdList());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteBatch(Long[] roleIds) {
//删除角色
sysRoleMapper.deleteBatch(roleIds);
//删除角色与菜单关联
sysRoleMenuMapper.deleteBatch(roleIds);
//删除角色与用户关联
sysUserRoleMapper.deleteBatch(roleIds);
}
@Override
public List<Long> listRoleIdByUserId(Long userId) {
return sysRoleMapper.listRoleIdByUserId(userId);
}
}
|
role.setCreateTime(new Date());
this.save(role);
if (CollectionUtil.isEmpty(role.getMenuIdList())) {
return;
}
//保存角色与菜单关系
sysRoleMenuMapper.insertRoleAndRoleMenu(role.getRoleId(), role.getMenuIdList());
| 396
| 86
| 482
|
<no_super_class>
|
gz-yami_mall4j
|
mall4j/yami-shop-sys/src/main/java/com/yami/shop/sys/service/impl/SysUserServiceImpl.java
|
SysUserServiceImpl
|
saveUserAndUserRole
|
class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
private SysUserRoleMapper sysUserRoleMapper;
private SysUserMapper sysUserMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void saveUserAndUserRole(SysUser user) {<FILL_FUNCTION_BODY>}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateUserAndUserRole(SysUser user) {
// 更新用户
sysUserMapper.updateById(user);
//先删除用户与角色关系
sysUserRoleMapper.deleteByUserId(user.getUserId());
if(CollUtil.isEmpty(user.getRoleIdList())){
return ;
}
//保存用户与角色关系
sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
}
@Override
public void updatePasswordByUserId(Long userId, String newPassword) {
SysUser user = new SysUser();
user.setPassword(newPassword);
user.setUserId(userId);
sysUserMapper.updateById(user);
}
@Override
public void deleteBatch(Long[] userIds,Long shopId) {
sysUserMapper.deleteBatch(userIds,shopId);
}
@Override
public SysUser getByUserName(String username) {
return sysUserMapper.selectByUsername(username);
}
@Override
public SysUser getSysUserById(Long userId) {
return sysUserMapper.selectById(userId);
}
@Override
public List<String> queryAllPerms(Long userId) {
return sysUserMapper.queryAllPerms(userId);
}
}
|
user.setCreateTime(new Date());
sysUserMapper.insert(user);
if(CollUtil.isEmpty(user.getRoleIdList())){
return ;
}
//保存用户与角色关系
sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
| 452
| 86
| 538
|
<no_super_class>
|
apache_maven
|
maven/api/maven-api-core/src/main/java/org/apache/maven/api/ExtensibleEnums.java
|
DefaultExtensibleEnum
|
equals
|
class DefaultExtensibleEnum implements ExtensibleEnum {
private final String id;
DefaultExtensibleEnum(String id) {
this.id = Objects.requireNonNull(id);
}
public String id() {
return id;
}
@Override
public int hashCode() {
return id().hashCode();
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + id() + "]";
}
}
|
return obj != null && getClass() == obj.getClass() && id().equals(((DefaultExtensibleEnum) obj).id());
| 158
| 36
| 194
|
<no_super_class>
|
apache_maven
|
maven/api/maven-api-core/src/main/java/org/apache/maven/api/feature/Features.java
|
Features
|
doGet
|
class Features {
/**
* Name of the Maven user property to enable or disable the build/consumer POM feature.
*/
public static final String BUILDCONSUMER = "maven.buildconsumer";
private Features() {}
/**
* Check if the build/consumer POM feature is active.
*/
public static boolean buildConsumer(@Nullable Properties userProperties) {
return doGet(userProperties, BUILDCONSUMER, true);
}
/**
* Check if the build/consumer POM feature is active.
*/
public static boolean buildConsumer(@Nullable Map<String, String> userProperties) {
return doGet(userProperties, BUILDCONSUMER, true);
}
/**
* Check if the build/consumer POM feature is active.
*/
public static boolean buildConsumer(@Nullable Session session) {
return buildConsumer(session != null ? session.getUserProperties() : null);
}
private static boolean doGet(Properties userProperties, String key, boolean def) {
return doGet(userProperties != null ? userProperties.get(key) : null, def);
}
private static boolean doGet(Map<String, ?> userProperties, String key, boolean def) {
return doGet(userProperties != null ? userProperties.get(key) : null, def);
}
private static boolean doGet(Object val, boolean def) {<FILL_FUNCTION_BODY>}
}
|
if (val instanceof Boolean) {
return (Boolean) val;
} else if (val != null) {
return Boolean.parseBoolean(val.toString());
} else {
return def;
}
| 370
| 57
| 427
|
<no_super_class>
|
apache_maven
|
maven/api/maven-api-core/src/main/java/org/apache/maven/api/services/BaseRequest.java
|
BaseRequest
|
unmodifiable
|
class BaseRequest {
private final Session session;
protected BaseRequest(@Nonnull Session session) {
this.session = nonNull(session, "session cannot be null");
}
@Nonnull
public Session getSession() {
return session;
}
public static <T> T nonNull(T obj, String message) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
return obj;
}
protected static <T> Collection<T> unmodifiable(Collection<T> obj) {<FILL_FUNCTION_BODY>}
}
|
return obj != null && !obj.isEmpty()
? Collections.unmodifiableCollection(new ArrayList<>(obj))
: Collections.emptyList();
| 153
| 42
| 195
|
<no_super_class>
|
apache_maven
|
maven/api/maven-api-core/src/main/java/org/apache/maven/api/services/ModelBuilderException.java
|
ModelBuilderException
|
getModelId
|
class ModelBuilderException extends MavenException {
private final ModelBuilderResult result;
/**
* Creates a new exception from the specified interim result and its associated problems.
*
* @param result The interim result, may be {@code null}.
*/
public ModelBuilderException(ModelBuilderResult result) {
super(result.toString());
this.result = result;
}
/**
* Gets the interim result of the model building up to the point where it failed.
*
* @return The interim model building result or {@code null} if not available.
*/
public ModelBuilderResult getResult() {
return result;
}
/**
* Gets the identifier of the POM whose effective model could not be built. The general format of the identifier is
* {@code <groupId>:<artifactId>:<version>} but some of these coordinates may still be unknown at the point the
* exception is thrown so this information is merely meant to assist the user.
*
* @return The identifier of the POM or an empty string if not known, never {@code null}.
*/
public String getModelId() {<FILL_FUNCTION_BODY>}
/**
* Gets the problems that caused this exception.
*
* @return The problems that caused this exception, never {@code null}.
*/
public List<ModelProblem> getProblems() {
if (result == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(result.getProblems());
}
}
|
if (result == null || result.getModelIds().isEmpty()) {
return "";
}
return result.getModelIds().get(0);
| 388
| 40
| 428
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.Throwable) <variables>
|
apache_maven
|
maven/api/maven-api-core/src/main/java/org/apache/maven/api/services/PathSource.java
|
PathSource
|
equals
|
class PathSource implements ModelSource {
private final Path path;
private final String location;
PathSource(Path path) {
this(path, null);
}
PathSource(Path path, String location) {
this.path = path;
this.location = location != null ? location : path.toString();
}
@Override
public Path getPath() {
return path;
}
@Override
public InputStream openStream() throws IOException {
return Files.newInputStream(path);
}
@Override
public String getLocation() {
return location;
}
@Override
public Source resolve(String relative) {
return new PathSource(path.resolve(relative));
}
@Override
public ModelSource resolve(ModelLocator locator, String relative) {
String norm = relative.replace('\\', File.separatorChar).replace('/', File.separatorChar);
Path path = getPath().getParent().resolve(norm);
Path relatedPom = locator.locateExistingPom(path);
if (relatedPom != null) {
return new PathSource(relatedPom.normalize(), null);
}
return null;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(path);
}
}
|
return this == o || o instanceof PathSource ps && Objects.equals(path, ps.path);
| 363
| 27
| 390
|
<no_super_class>
|
apache_maven
|
maven/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputLocation.java
|
InputLocation
|
merge
|
class InputLocation implements Serializable, InputLocationTracker {
private final int lineNumber;
private final int columnNumber;
private final InputSource source;
private final Map<Object, InputLocation> locations;
public InputLocation(InputSource source) {
this.lineNumber = -1;
this.columnNumber = -1;
this.source = source;
this.locations = Collections.singletonMap(0, this);
}
public InputLocation(int lineNumber, int columnNumber) {
this(lineNumber, columnNumber, null, null);
}
public InputLocation(int lineNumber, int columnNumber, InputSource source) {
this(lineNumber, columnNumber, source, null);
}
public InputLocation(int lineNumber, int columnNumber, InputSource source, Object selfLocationKey) {
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.source = source;
this.locations =
selfLocationKey != null ? Collections.singletonMap(selfLocationKey, this) : Collections.emptyMap();
}
public InputLocation(int lineNumber, int columnNumber, InputSource source, Map<Object, InputLocation> locations) {
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.source = source;
this.locations = ImmutableCollections.copy(locations);
}
public int getLineNumber() {
return lineNumber;
}
public int getColumnNumber() {
return columnNumber;
}
public InputSource getSource() {
return source;
}
public InputLocation getLocation(Object key) {
return locations != null ? locations.get(key) : null;
}
public Map<Object, InputLocation> getLocations() {
return locations;
}
/**
* Merges the {@code source} location into the {@code target} location.
*
* @param target the target location
* @param source the source location
* @param sourceDominant the boolean indicating of {@code source} is dominant compared to {@code target}
* @return the merged location
*/
public static InputLocation merge(InputLocation target, InputLocation source, boolean sourceDominant) {<FILL_FUNCTION_BODY>} // -- InputLocation merge( InputLocation, InputLocation, boolean )
/**
* Merges the {@code source} location into the {@code target} location.
* This method is used when the locations refer to lists and also merges the indices.
*
* @param target the target location
* @param source the source location
* @param indices the list of integers for the indices
* @return the merged location
*/
public static InputLocation merge(InputLocation target, InputLocation source, Collection<Integer> indices) {
if (source == null) {
return target;
} else if (target == null) {
return source;
}
Map<Object, InputLocation> locations;
Map<Object, InputLocation> sourceLocations = source.locations;
Map<Object, InputLocation> targetLocations = target.locations;
if (sourceLocations == null) {
locations = targetLocations;
} else if (targetLocations == null) {
locations = sourceLocations;
} else {
locations = new LinkedHashMap<>();
for (int index : indices) {
InputLocation location;
if (index < 0) {
location = sourceLocations.get(~index);
} else {
location = targetLocations.get(index);
}
locations.put(locations.size(), location);
}
}
return new InputLocation(-1, -1, InputSource.merge(source.getSource(), target.getSource()), locations);
} // -- InputLocation merge( InputLocation, InputLocation, java.util.Collection )
/**
* Class StringFormatter.
*
* @version $Revision$ $Date$
*/
public interface StringFormatter {
// -----------/
// - Methods -/
// -----------/
/**
* Method toString.
*/
String toString(InputLocation location);
}
}
|
if (source == null) {
return target;
} else if (target == null) {
return source;
}
Map<Object, InputLocation> locations;
Map<Object, InputLocation> sourceLocations = source.locations;
Map<Object, InputLocation> targetLocations = target.locations;
if (sourceLocations == null) {
locations = targetLocations;
} else if (targetLocations == null) {
locations = sourceLocations;
} else {
locations = new LinkedHashMap<>();
locations.putAll(sourceDominant ? targetLocations : sourceLocations);
locations.putAll(sourceDominant ? sourceLocations : targetLocations);
}
return new InputLocation(-1, -1, InputSource.merge(source.getSource(), target.getSource()), locations);
| 1,054
| 212
| 1,266
|
<no_super_class>
|
apache_maven
|
maven/api/maven-api-model/src/main/java/org/apache/maven/api/model/InputSource.java
|
InputSource
|
toString
|
class InputSource implements Serializable {
private final String modelId;
private final String location;
private final List<InputSource> inputs;
public InputSource(String modelId, String location) {
this.modelId = modelId;
this.location = location;
this.inputs = null;
}
public InputSource(Collection<InputSource> inputs) {
this.modelId = null;
this.location = null;
this.inputs = ImmutableCollections.copy(inputs);
}
/**
* Get the path/URL of the POM or {@code null} if unknown.
*
* @return the location
*/
public String getLocation() {
return this.location;
}
/**
* Get the identifier of the POM in the format {@code <groupId>:<artifactId>:<version>}.
*
* @return the model id
*/
public String getModelId() {
return this.modelId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InputSource that = (InputSource) o;
return Objects.equals(modelId, that.modelId)
&& Objects.equals(location, that.location)
&& Objects.equals(inputs, that.inputs);
}
@Override
public int hashCode() {
return Objects.hash(modelId, location, inputs);
}
Stream<InputSource> sources() {
return inputs != null ? inputs.stream() : Stream.of(this);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public static InputSource merge(InputSource src1, InputSource src2) {
return new InputSource(Stream.concat(src1.sources(), src2.sources()).collect(Collectors.toSet()));
}
}
|
if (inputs != null) {
return inputs.stream().map(InputSource::toString).collect(Collectors.joining(", ", "merged[", "]"));
}
return getModelId() + " " + getLocation();
| 514
| 63
| 577
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/AbstractNode.java
|
AbstractNode
|
accept
|
class AbstractNode implements Node {
abstract org.eclipse.aether.graph.DependencyNode getDependencyNode();
@Override
public boolean accept(NodeVisitor visitor) {<FILL_FUNCTION_BODY>}
@Override
public Node filter(Predicate<Node> filter) {
List<Node> children =
getChildren().stream().filter(filter).map(n -> n.filter(filter)).collect(Collectors.toList());
return new WrapperNode(this, Collections.unmodifiableList(children));
}
@Override
public String asString() {
StringBuilder sb = new StringBuilder();
DependencyNode node = getDependencyNode();
Artifact artifact = node.getArtifact();
sb.append(artifact);
Dependency dependency = node.getDependency();
if (dependency != null) {
sb.append(":").append(dependency.getScope());
}
return sb.toString();
}
@Override
public String toString() {
return getDependencyNode().toString();
}
}
|
if (visitor.enter(this)) {
for (Node child : getChildren()) {
if (!child.accept(visitor)) {
break;
}
}
}
return visitor.leave(this);
| 271
| 60
| 331
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinate.java
|
DefaultArtifactCoordinate
|
equals
|
class DefaultArtifactCoordinate implements ArtifactCoordinate {
private final @Nonnull InternalSession session;
private final @Nonnull org.eclipse.aether.artifact.Artifact coordinate;
public DefaultArtifactCoordinate(
@Nonnull InternalSession session, @Nonnull org.eclipse.aether.artifact.Artifact coordinate) {
this.session = nonNull(session, "session");
this.coordinate = nonNull(coordinate, "coordinate");
}
public org.eclipse.aether.artifact.Artifact getCoordinate() {
return coordinate;
}
@Nonnull
@Override
public String getGroupId() {
return coordinate.getGroupId();
}
@Nonnull
@Override
public String getArtifactId() {
return coordinate.getArtifactId();
}
@Nonnull
@Override
public VersionConstraint getVersion() {
return session.parseVersionConstraint(coordinate.getVersion());
}
@Override
public String getExtension() {
return coordinate.getExtension();
}
@Nonnull
@Override
public String getClassifier() {
return coordinate.getClassifier();
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(getGroupId(), getArtifactId(), getVersion(), getClassifier());
}
@Override
public String toString() {
return coordinate.toString();
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultArtifactCoordinate that = (DefaultArtifactCoordinate) o;
return Objects.equals(this.getGroupId(), that.getGroupId())
&& Objects.equals(this.getArtifactId(), that.getArtifactId())
&& Objects.equals(this.getVersion(), that.getVersion())
&& Objects.equals(this.getClassifier(), that.getClassifier());
| 390
| 145
| 535
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultArtifactCoordinateFactory.java
|
DefaultArtifactCoordinateFactory
|
create
|
class DefaultArtifactCoordinateFactory implements ArtifactCoordinateFactory {
@Override
public ArtifactCoordinate create(@Nonnull ArtifactCoordinateFactoryRequest request) {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
if (request.getCoordinateString() != null) {
return new DefaultArtifactCoordinate(
session, new org.eclipse.aether.artifact.DefaultArtifact(request.getCoordinateString()));
} else {
ArtifactType type = null;
if (request.getType() != null) {
type = session.getSession().getArtifactTypeRegistry().get(request.getType());
}
String str1 = request.getClassifier();
String classifier = str1 != null && !str1.isEmpty()
? request.getClassifier()
: type != null ? type.getClassifier() : "";
String str = request.getExtension();
String extension =
str != null && !str.isEmpty() ? request.getExtension() : type != null ? type.getExtension() : "";
return new DefaultArtifactCoordinate(
session,
new org.eclipse.aether.artifact.DefaultArtifact(
request.getGroupId(),
request.getArtifactId(),
classifier,
extension,
request.getVersion(),
type));
}
| 53
| 304
| 357
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultArtifactDeployer.java
|
DefaultArtifactDeployer
|
deploy
|
class DefaultArtifactDeployer implements ArtifactDeployer {
@Override
public void deploy(@Nonnull ArtifactDeployerRequest request) {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
Collection<Artifact> artifacts = nonNull(request.getArtifacts(), "request.artifacts");
RemoteRepository repository = nonNull(request.getRepository(), "request.repository");
try {
DeployRequest deployRequest = new DeployRequest()
.setRepository(session.toRepository(repository))
.setArtifacts(session.toArtifacts(artifacts));
DeployResult result = session.getRepositorySystem().deploy(session.getSession(), deployRequest);
} catch (DeploymentException e) {
throw new ArtifactDeployerException("Unable to deploy artifacts", e);
}
| 51
| 181
| 232
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultArtifactFactory.java
|
DefaultArtifactFactory
|
create
|
class DefaultArtifactFactory implements ArtifactFactory {
@Override
public Artifact create(@Nonnull ArtifactFactoryRequest request) {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
ArtifactType type = null;
if (request.getType() != null) {
type = session.getSession().getArtifactTypeRegistry().get(request.getType());
}
String str1 = request.getClassifier();
String classifier =
str1 != null && !str1.isEmpty() ? request.getClassifier() : type != null ? type.getClassifier() : null;
String str = request.getExtension();
String extension =
str != null && !str.isEmpty() ? request.getExtension() : type != null ? type.getExtension() : null;
return new DefaultArtifact(
session,
new org.eclipse.aether.artifact.DefaultArtifact(
request.getGroupId(),
request.getArtifactId(),
classifier,
extension,
request.getVersion(),
type));
| 45
| 243
| 288
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultArtifactInstaller.java
|
DefaultArtifactInstaller
|
install
|
class DefaultArtifactInstaller implements ArtifactInstaller {
private final RepositorySystem repositorySystem;
@Inject
DefaultArtifactInstaller(@Nonnull RepositorySystem repositorySystem) {
this.repositorySystem = nonNull(repositorySystem);
}
@Override
public void install(ArtifactInstallerRequest request) throws ArtifactInstallerException, IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
try {
InstallRequest installRequest =
new InstallRequest().setArtifacts(session.toArtifacts(request.getArtifacts()));
InstallResult result = repositorySystem.install(session.getSession(), installRequest);
} catch (InstallationException e) {
throw new ArtifactInstallerException(e.getMessage(), e);
}
| 105
| 115
| 220
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultArtifactResolver.java
|
DefaultArtifactResolver
|
resolve
|
class DefaultArtifactResolver implements ArtifactResolver {
@Override
public ArtifactResolverResult resolve(ArtifactResolverRequest request)
throws ArtifactResolverException, IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
try {
Map<Artifact, Path> paths = new HashMap<>();
ArtifactManager artifactManager = session.getService(ArtifactManager.class);
List<RemoteRepository> repositories = session.toRepositories(session.getRemoteRepositories());
List<ArtifactRequest> requests = new ArrayList<>();
for (ArtifactCoordinate coord : request.getCoordinates()) {
org.eclipse.aether.artifact.Artifact aetherArtifact = session.toArtifact(coord);
Artifact artifact = session.getArtifact(aetherArtifact);
Path path = artifactManager.getPath(artifact).orElse(null);
if (path != null) {
paths.put(artifact, path);
} else {
requests.add(new ArtifactRequest(aetherArtifact, repositories, null));
}
}
if (!requests.isEmpty()) {
List<ArtifactResult> results =
session.getRepositorySystem().resolveArtifacts(session.getSession(), requests);
for (ArtifactResult result : results) {
Artifact artifact = session.getArtifact(result.getArtifact());
Path path = result.getArtifact().getFile().toPath();
artifactManager.setPath(artifact, path);
paths.put(artifact, path);
}
}
return () -> paths;
} catch (ArtifactResolutionException e) {
throw new ArtifactResolverException("Unable to resolve artifact", e);
}
| 56
| 397
| 453
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultBuilderProblem.java
|
DefaultBuilderProblem
|
toString
|
class DefaultBuilderProblem implements BuilderProblem {
final String source;
final int lineNumber;
final int columnNumber;
final Exception exception;
final String message;
final Severity severity;
DefaultBuilderProblem(
String source, int lineNumber, int columnNumber, Exception exception, String message, Severity severity) {
this.source = source;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.exception = exception;
this.message = message;
this.severity = severity;
}
@Override
public String getSource() {
return source;
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public int getColumnNumber() {
return columnNumber;
}
@Override
public Exception getException() {
return exception;
}
@Override
public String getMessage() {
return message;
}
@Override
public Severity getSeverity() {
return severity;
}
@Override
public String getLocation() {
StringBuilder buffer = new StringBuilder(256);
if (!getSource().isEmpty()) {
buffer.append(getSource());
}
if (getLineNumber() > 0) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append("line ").append(getLineNumber());
}
if (getColumnNumber() > 0) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append("column ").append(getColumnNumber());
}
return buffer.toString();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder(128);
buffer.append('[').append(severity).append("]");
String msg = message != null ? message : exception != null ? exception.getMessage() : null;
if (msg != null && !msg.isEmpty()) {
buffer.append(" ").append(msg);
}
String location = getLocation();
if (!location.isEmpty()) {
buffer.append(" @ ").append(location);
}
return buffer.toString();
| 464
| 128
| 592
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultChecksumAlgorithmService.java
|
DefaultChecksumAlgorithmService
|
calculate
|
class DefaultChecksumAlgorithmService implements ChecksumAlgorithmService {
private final ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector;
@Inject
public DefaultChecksumAlgorithmService(ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector) {
this.checksumAlgorithmFactorySelector =
nonNull(checksumAlgorithmFactorySelector, "checksumAlgorithmFactorySelector");
}
@Override
public Collection<String> getChecksumAlgorithmNames() {
return checksumAlgorithmFactorySelector.getChecksumAlgorithmFactories().stream()
.map(ChecksumAlgorithmFactory::getName)
.collect(Collectors.toList());
}
@Override
public ChecksumAlgorithm select(String algorithmName) {
nonNull(algorithmName, "algorithmName");
try {
return new DefaultChecksumAlgorithm(checksumAlgorithmFactorySelector.select(algorithmName));
} catch (IllegalArgumentException e) {
throw new ChecksumAlgorithmServiceException("unsupported algorithm", e);
}
}
@Override
public Collection<ChecksumAlgorithm> select(Collection<String> algorithmNames) {
nonNull(algorithmNames, "algorithmNames");
try {
return checksumAlgorithmFactorySelector.selectList(new ArrayList<>(algorithmNames)).stream()
.map(DefaultChecksumAlgorithm::new)
.collect(Collectors.toList());
} catch (IllegalArgumentException e) {
throw new ChecksumAlgorithmServiceException("unsupported algorithm", e);
}
}
@Override
public Map<ChecksumAlgorithm, String> calculate(byte[] data, Collection<ChecksumAlgorithm> algorithms) {
nonNull(data, "data");
nonNull(algorithms, "algorithms");
try {
return calculate(new ByteArrayInputStream(data), algorithms);
} catch (IOException e) {
throw new UncheckedIOException(e); // really unexpected
}
}
@Override
public Map<ChecksumAlgorithm, String> calculate(ByteBuffer data, Collection<ChecksumAlgorithm> algorithms) {<FILL_FUNCTION_BODY>}
@Override
public Map<ChecksumAlgorithm, String> calculate(Path file, Collection<ChecksumAlgorithm> algorithms)
throws IOException {
nonNull(file, "file");
nonNull(algorithms, "algorithms");
try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file))) {
return calculate(inputStream, algorithms);
}
}
@Override
public Map<ChecksumAlgorithm, String> calculate(InputStream stream, Collection<ChecksumAlgorithm> algorithms)
throws IOException {
nonNull(stream, "stream");
nonNull(algorithms, "algorithms");
LinkedHashMap<ChecksumAlgorithm, ChecksumCalculator> algMap = new LinkedHashMap<>();
algorithms.forEach(f -> algMap.put(f, f.getCalculator()));
final byte[] buffer = new byte[1024 * 32];
for (; ; ) {
int read = stream.read(buffer);
if (read < 0) {
break;
}
for (ChecksumCalculator checksumCalculator : algMap.values()) {
checksumCalculator.update(ByteBuffer.wrap(buffer, 0, read));
}
}
LinkedHashMap<ChecksumAlgorithm, String> result = new LinkedHashMap<>();
algMap.forEach((k, v) -> result.put(k, v.checksum()));
return result;
}
private static class DefaultChecksumAlgorithm implements ChecksumAlgorithm {
private final ChecksumAlgorithmFactory factory;
DefaultChecksumAlgorithm(ChecksumAlgorithmFactory factory) {
this.factory = factory;
}
@Override
public String getName() {
return factory.getName();
}
@Override
public String getFileExtension() {
return factory.getFileExtension();
}
@Override
public ChecksumCalculator getCalculator() {
return new DefaultChecksumCalculator(factory.getAlgorithm());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultChecksumAlgorithm that = (DefaultChecksumAlgorithm) o;
return Objects.equals(factory.getName(), that.factory.getName());
}
@Override
public int hashCode() {
return Objects.hash(factory.getName());
}
}
private static class DefaultChecksumCalculator implements ChecksumCalculator {
private final org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithm algorithm;
DefaultChecksumCalculator(org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithm algorithm) {
this.algorithm = algorithm;
}
@Override
public void update(ByteBuffer input) {
algorithm.update(input);
}
@Override
public String checksum() {
return algorithm.checksum();
}
}
}
|
nonNull(data, "data");
nonNull(algorithms, "algorithms");
LinkedHashMap<ChecksumAlgorithm, ChecksumCalculator> algMap = new LinkedHashMap<>();
algorithms.forEach(f -> algMap.put(f, f.getCalculator()));
data.mark();
for (ChecksumCalculator checksumCalculator : algMap.values()) {
checksumCalculator.update(data);
data.reset();
}
LinkedHashMap<ChecksumAlgorithm, String> result = new LinkedHashMap<>();
algMap.forEach((k, v) -> result.put(k, v.checksum()));
return result;
| 1,334
| 172
| 1,506
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultDependency.java
|
DefaultDependency
|
getType
|
class DefaultDependency implements Dependency {
private final InternalSession session;
private final org.eclipse.aether.graph.Dependency dependency;
private final String key;
public DefaultDependency(
@Nonnull InternalSession session, @Nonnull org.eclipse.aether.graph.Dependency dependency) {
this.session = nonNull(session, "session");
this.dependency = nonNull(dependency, "dependency");
this.key = getGroupId()
+ ':'
+ getArtifactId()
+ ':'
+ getExtension()
+ (!getClassifier().isEmpty() ? ":" + getClassifier() : "")
+ ':'
+ getVersion();
}
@Override
public String key() {
return key;
}
@Nonnull
public org.eclipse.aether.graph.Dependency getDependency() {
return dependency;
}
@Override
public String getGroupId() {
return dependency.getArtifact().getGroupId();
}
@Override
public String getArtifactId() {
return dependency.getArtifact().getArtifactId();
}
@Override
public String getClassifier() {
return dependency.getArtifact().getClassifier();
}
@Override
public Version getVersion() {
return session.parseVersion(dependency.getArtifact().getVersion());
}
@Override
public Version getBaseVersion() {
return session.parseVersion(dependency.getArtifact().getBaseVersion());
}
@Override
public String getExtension() {
return dependency.getArtifact().getExtension();
}
@Override
public Type getType() {<FILL_FUNCTION_BODY>}
@Override
public boolean isSnapshot() {
return DefaultModelVersionParser.checkSnapshot(dependency.getArtifact().getVersion());
}
@Nonnull
@Override
public DependencyScope getScope() {
return session.requireDependencyScope(dependency.getScope());
}
@Nullable
@Override
public boolean isOptional() {
return dependency.isOptional();
}
@Nonnull
@Override
public DependencyCoordinate toCoordinate() {
return session.createDependencyCoordinate(this);
}
@Override
public boolean equals(Object o) {
return o instanceof Artifact && Objects.equals(key(), ((Artifact) o).key());
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return dependency.toString();
}
}
|
String type = dependency
.getArtifact()
.getProperty(ArtifactProperties.TYPE, dependency.getArtifact().getExtension());
return session.requireType(type);
| 664
| 47
| 711
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCollector.java
|
DefaultDependencyCollector
|
collect
|
class DefaultDependencyCollector implements DependencyCollector {
@Nonnull
@Override
public DependencyCollectorResult collect(@Nonnull DependencyCollectorRequest request)
throws DependencyCollectorException, IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
Artifact rootArtifact;
DependencyCoordinate root;
Collection<DependencyCoordinate> dependencies;
Collection<DependencyCoordinate> managedDependencies;
List<RemoteRepository> remoteRepositories;
if (request.getProject().isPresent()) {
Project project = request.getProject().get();
rootArtifact = project.getPomArtifact();
root = null;
dependencies = project.getDependencies();
managedDependencies = project.getManagedDependencies();
remoteRepositories = session.getService(ProjectManager.class).getRemoteProjectRepositories(project);
} else {
rootArtifact = request.getRootArtifact().orElse(null);
root = request.getRoot().orElse(null);
dependencies = request.getDependencies();
managedDependencies = request.getManagedDependencies();
remoteRepositories = session.getRemoteRepositories();
}
CollectRequest collectRequest = new CollectRequest()
.setRootArtifact(rootArtifact != null ? session.toArtifact(rootArtifact) : null)
.setRoot(root != null ? session.toDependency(root, false) : null)
.setDependencies(session.toDependencies(dependencies, false))
.setManagedDependencies(session.toDependencies(managedDependencies, true))
.setRepositories(session.toRepositories(remoteRepositories));
RepositorySystemSession systemSession = session.getSession();
if (request.getVerbose()) {
systemSession = new DefaultRepositorySystemSession(systemSession)
.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true)
.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true);
}
try {
final CollectResult result =
session.getRepositorySystem().collectDependencies(systemSession, collectRequest);
return new DependencyCollectorResult() {
@Override
public List<Exception> getExceptions() {
return result.getExceptions();
}
@Override
public Node getRoot() {
return session.getNode(result.getRoot(), request.getVerbose());
}
};
} catch (DependencyCollectionException e) {
throw new DependencyCollectorException("Unable to collect dependencies", e);
}
| 71
| 613
| 684
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinate.java
|
DefaultDependencyCoordinate
|
getType
|
class DefaultDependencyCoordinate implements DependencyCoordinate {
private final InternalSession session;
private final org.eclipse.aether.graph.Dependency dependency;
public DefaultDependencyCoordinate(
@Nonnull InternalSession session, @Nonnull org.eclipse.aether.graph.Dependency dependency) {
this.session = nonNull(session, "session");
this.dependency = nonNull(dependency, "dependency");
}
@Nonnull
public org.eclipse.aether.graph.Dependency getDependency() {
return dependency;
}
@Override
public String getGroupId() {
return dependency.getArtifact().getGroupId();
}
@Override
public String getArtifactId() {
return dependency.getArtifact().getArtifactId();
}
@Override
public String getClassifier() {
return dependency.getArtifact().getClassifier();
}
@Override
public VersionConstraint getVersion() {
return session.parseVersionConstraint(dependency.getArtifact().getVersion());
}
@Override
public String getExtension() {
return dependency.getArtifact().getExtension();
}
@Override
public Type getType() {<FILL_FUNCTION_BODY>}
@Nonnull
@Override
public DependencyScope getScope() {
return session.requireDependencyScope(dependency.getScope());
}
@Nullable
@Override
public Boolean getOptional() {
return dependency.getOptional();
}
@Nonnull
@Override
public Collection<Exclusion> getExclusions() {
return new MappedCollection<>(dependency.getExclusions(), this::toExclusion);
}
private Exclusion toExclusion(org.eclipse.aether.graph.Exclusion exclusion) {
return new Exclusion() {
@Nullable
@Override
public String getGroupId() {
return exclusion.getGroupId();
}
@Nullable
@Override
public String getArtifactId() {
return exclusion.getArtifactId();
}
};
}
}
|
String type = dependency
.getArtifact()
.getProperty(ArtifactProperties.TYPE, dependency.getArtifact().getExtension());
return session.requireType(type);
| 530
| 47
| 577
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultDependencyCoordinateFactory.java
|
DefaultDependencyCoordinateFactory
|
create
|
class DefaultDependencyCoordinateFactory implements DependencyCoordinateFactory {
@Nonnull
@Override
public DependencyCoordinate create(@Nonnull DependencyCoordinateFactoryRequest request) {<FILL_FUNCTION_BODY>}
private org.eclipse.aether.graph.Exclusion toExclusion(Exclusion exclusion) {
return new org.eclipse.aether.graph.Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*");
}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
ArtifactType type = null;
if (request.getType() != null) {
type = session.getSession().getArtifactTypeRegistry().get(request.getType());
}
if (request.getCoordinateString() != null) {
return new DefaultDependencyCoordinate(
session,
new org.eclipse.aether.graph.Dependency(
new org.eclipse.aether.artifact.DefaultArtifact(request.getCoordinateString()),
request.getScope(),
request.isOptional(),
map(request.getExclusions(), this::toExclusion)));
} else {
return new DefaultDependencyCoordinate(
session,
new org.eclipse.aether.graph.Dependency(
new org.eclipse.aether.artifact.DefaultArtifact(
request.getGroupId(),
request.getArtifactId(),
request.getClassifier(),
request.getExtension(),
request.getVersion(),
type),
request.getScope(),
request.isOptional(),
map(request.getExclusions(), this::toExclusion)));
}
| 126
| 298
| 424
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultLocalRepositoryManager.java
|
DefaultLocalRepositoryManager
|
getManager
|
class DefaultLocalRepositoryManager implements LocalRepositoryManager {
@Override
public Path getPathForLocalArtifact(Session session, LocalRepository local, Artifact artifact) {
InternalSession s = InternalSession.from(session);
String path = getManager(s, local).getPathForLocalArtifact(s.toArtifact(artifact));
return local.getPath().resolve(path);
}
@Override
public Path getPathForRemoteArtifact(
Session session, LocalRepository local, RemoteRepository remote, Artifact artifact) {
InternalSession s = InternalSession.from(session);
String path =
getManager(s, local).getPathForRemoteArtifact(s.toArtifact(artifact), s.toRepository(remote), null);
return local.getPath().resolve(path);
}
private org.eclipse.aether.repository.LocalRepositoryManager getManager(
InternalSession session, LocalRepository local) {<FILL_FUNCTION_BODY>}
}
|
org.eclipse.aether.repository.LocalRepository repository = session.toRepository(local);
if ("enhanced".equals(repository.getContentType())) {
repository = new org.eclipse.aether.repository.LocalRepository(repository.getBasedir(), "");
}
return session.getRepositorySystem().newLocalRepositoryManager(session.getSession(), repository);
| 238
| 91
| 329
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultModelUrlNormalizer.java
|
DefaultModelUrlNormalizer
|
normalize
|
class DefaultModelUrlNormalizer implements ModelUrlNormalizer {
private final UrlNormalizer urlNormalizer;
@Inject
public DefaultModelUrlNormalizer(UrlNormalizer urlNormalizer) {
this.urlNormalizer = urlNormalizer;
}
@Override
public Model normalize(Model model, ModelBuilderRequest request) {<FILL_FUNCTION_BODY>}
private String normalize(String url) {
return urlNormalizer.normalize(url);
}
}
|
if (model == null) {
return null;
}
Model.Builder builder = Model.newBuilder(model);
builder.url(normalize(model.getUrl()));
Scm scm = model.getScm();
if (scm != null) {
builder.scm(Scm.newBuilder(scm)
.url(normalize(scm.getUrl()))
.connection(normalize(scm.getConnection()))
.developerConnection(normalize(scm.getDeveloperConnection()))
.build());
}
DistributionManagement dist = model.getDistributionManagement();
if (dist != null) {
Site site = dist.getSite();
if (site != null) {
builder.distributionManagement(dist.withSite(site.withUrl(normalize(site.getUrl()))));
}
}
return builder.build();
| 126
| 229
| 355
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultModelVersionParser.java
|
DefaultVersionRange
|
contains
|
class DefaultVersionRange implements VersionRange {
private final VersionScheme versionScheme;
private final org.eclipse.aether.version.VersionRange delegate;
DefaultVersionRange(VersionScheme versionScheme, org.eclipse.aether.version.VersionRange delegate) {
this.versionScheme = versionScheme;
this.delegate = delegate;
}
DefaultVersionRange(VersionScheme versionScheme, String delegateValue) {
this.versionScheme = versionScheme;
try {
this.delegate = versionScheme.parseVersionRange(delegateValue);
} catch (InvalidVersionSpecificationException e) {
throw new VersionParserException("Unable to parse version range: " + delegateValue, e);
}
}
@Override
public boolean contains(Version version) {<FILL_FUNCTION_BODY>}
@Override
public Boundary getUpperBoundary() {
org.eclipse.aether.version.VersionRange.Bound bound = delegate.getUpperBound();
if (bound == null) {
return null;
}
return new Boundary() {
@Override
public Version getVersion() {
return new DefaultVersion(versionScheme, bound.getVersion());
}
@Override
public boolean isInclusive() {
return bound.isInclusive();
}
};
}
@Override
public Boundary getLowerBoundary() {
org.eclipse.aether.version.VersionRange.Bound bound = delegate.getLowerBound();
if (bound == null) {
return null;
}
return new Boundary() {
@Override
public Version getVersion() {
return new DefaultVersion(versionScheme, bound.getVersion());
}
@Override
public boolean isInclusive() {
return bound.isInclusive();
}
};
}
@Override
public String asString() {
return delegate.toString();
}
@Override
public String toString() {
return asString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultVersionRange that = (DefaultVersionRange) o;
return delegate.equals(that.delegate);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
|
if (version instanceof DefaultVersion) {
return delegate.containsVersion(((DefaultVersion) version).delegate);
} else {
return contains(new DefaultVersion(versionScheme, version.asString()));
}
| 635
| 57
| 692
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultModelXmlFactory.java
|
DefaultModelXmlFactory
|
read
|
class DefaultModelXmlFactory implements ModelXmlFactory {
@Override
public Model read(@Nonnull XmlReaderRequest request) throws XmlReaderException {<FILL_FUNCTION_BODY>}
@Override
public void write(XmlWriterRequest<Model> request) throws XmlWriterException {
nonNull(request, "request");
Model content = nonNull(request.getContent(), "content");
Path path = request.getPath();
OutputStream outputStream = request.getOutputStream();
Writer writer = request.getWriter();
if (writer == null && outputStream == null && path == null) {
throw new IllegalArgumentException("writer, outputStream or path must be non null");
}
try {
if (writer != null) {
new MavenStaxWriter().write(writer, content);
} else if (outputStream != null) {
new MavenStaxWriter().write(outputStream, content);
} else {
try (OutputStream os = Files.newOutputStream(path)) {
new MavenStaxWriter().write(outputStream, content);
}
}
} catch (Exception e) {
throw new XmlWriterException("Unable to write model: " + getMessage(e), getLocation(e), e);
}
}
/**
* Simply parse the given xml string.
*
* @param xml the input xml string
* @return the parsed object
* @throws XmlReaderException if an error occurs during the parsing
* @see #toXmlString(Object)
*/
public static Model fromXml(@Nonnull String xml) throws XmlReaderException {
return new DefaultModelXmlFactory().fromXmlString(xml);
}
/**
* Simply converts the given content to an xml string.
*
* @param content the object to convert
* @return the xml string representation
* @throws XmlWriterException if an error occurs during the transformation
* @see #fromXmlString(String)
*/
public static String toXml(@Nonnull Model content) throws XmlWriterException {
return new DefaultModelXmlFactory().toXmlString(content);
}
}
|
nonNull(request, "request");
Path path = request.getPath();
URL url = request.getURL();
Reader reader = request.getReader();
InputStream inputStream = request.getInputStream();
if (path == null && url == null && reader == null && inputStream == null) {
throw new IllegalArgumentException("path, url, reader or inputStream must be non null");
}
try {
InputSource source = null;
if (request.getModelId() != null || request.getLocation() != null) {
source = new InputSource(
request.getModelId(), path != null ? path.toUri().toString() : null);
}
MavenStaxReader xml = new MavenStaxReader();
xml.setAddDefaultEntities(request.isAddDefaultEntities());
if (inputStream != null) {
return xml.read(inputStream, request.isStrict(), source);
} else if (reader != null) {
return xml.read(reader, request.isStrict(), source);
} else if (path != null) {
try (InputStream is = Files.newInputStream(path)) {
return xml.read(is, request.isStrict(), source);
}
} else {
try (InputStream is = url.openStream()) {
return xml.read(is, request.isStrict(), source);
}
}
} catch (Exception e) {
throw new XmlReaderException("Unable to read model: " + getMessage(e), getLocation(e), e);
}
| 528
| 391
| 919
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultNode.java
|
DefaultNode
|
asString
|
class DefaultNode extends AbstractNode {
protected final @Nonnull InternalSession session;
protected final @Nonnull org.eclipse.aether.graph.DependencyNode node;
protected final boolean verbose;
public DefaultNode(
@Nonnull InternalSession session, @Nonnull org.eclipse.aether.graph.DependencyNode node, boolean verbose) {
this.session = session;
this.node = node;
this.verbose = verbose;
}
@Override
DependencyNode getDependencyNode() {
return node;
}
@Override
public Artifact getArtifact() {
return node.getArtifact() != null ? session.getArtifact(node.getArtifact()) : null;
}
@Override
public Dependency getDependency() {
return node.getDependency() != null ? session.getDependency(node.getDependency()) : null;
}
@Override
public List<Node> getChildren() {
return new MappedList<>(node.getChildren(), n -> session.getNode(n, verbose));
}
@Override
public List<RemoteRepository> getRemoteRepositories() {
return new MappedList<>(node.getRepositories(), session::getRemoteRepository);
}
@Override
public Optional<RemoteRepository> getRepository() {
// TODO: v4: implement
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public String asString() {<FILL_FUNCTION_BODY>}
private static void join(StringBuilder buffer, List<String> details, String separator) {
boolean first = true;
for (String detail : details) {
if (first) {
first = false;
} else {
buffer.append(separator);
}
buffer.append(detail);
}
}
}
|
String nodeString = super.asString();
if (!verbose) {
return nodeString;
}
org.eclipse.aether.graph.DependencyNode node = getDependencyNode();
List<String> details = new ArrayList<>();
org.eclipse.aether.graph.DependencyNode winner =
(org.eclipse.aether.graph.DependencyNode) node.getData().get(ConflictResolver.NODE_DATA_WINNER);
String winnerVersion = winner != null ? winner.getArtifact().getBaseVersion() : null;
boolean included = (winnerVersion == null);
String preManagedVersion = DependencyManagerUtils.getPremanagedVersion(node);
if (preManagedVersion != null) {
details.add("version managed from " + preManagedVersion);
}
String preManagedScope = DependencyManagerUtils.getPremanagedScope(node);
if (preManagedScope != null) {
details.add("scope managed from " + preManagedScope);
}
String originalScope = (String) node.getData().get(ConflictResolver.NODE_DATA_ORIGINAL_SCOPE);
if (originalScope != null && !originalScope.equals(node.getDependency().getScope())) {
details.add("scope updated from " + originalScope);
}
if (!included) {
if (Objects.equals(winnerVersion, node.getArtifact().getVersion())) {
details.add("omitted for duplicate");
} else {
details.add("omitted for conflict with " + winnerVersion);
}
}
StringBuilder buffer = new StringBuilder();
if (included) {
buffer.append(nodeString);
if (!details.isEmpty()) {
buffer.append(" (");
join(buffer, details, "; ");
buffer.append(")");
}
} else {
buffer.append("(");
buffer.append(nodeString);
if (!details.isEmpty()) {
buffer.append(" - ");
join(buffer, details, "; ");
}
buffer.append(")");
}
return buffer.toString();
| 473
| 541
| 1,014
|
<methods>public non-sealed void <init>() ,public boolean accept(org.apache.maven.api.NodeVisitor) ,public java.lang.String asString() ,public org.apache.maven.api.Node filter(Predicate<org.apache.maven.api.Node>) ,public java.lang.String toString() <variables>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultPluginConfigurationExpander.java
|
DefaultPluginConfigurationExpander
|
map
|
class DefaultPluginConfigurationExpander implements PluginConfigurationExpander {
@Override
public Model expandPluginConfiguration(Model model, ModelBuilderRequest request, ModelProblemCollector problems) {
Build build = model.getBuild();
if (build != null) {
build = build.withPlugins(expandPlugin(build.getPlugins()));
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
build = build.withPluginManagement(
pluginManagement.withPlugins(expandPlugin(pluginManagement.getPlugins())));
}
model = model.withBuild(build);
}
Reporting reporting = model.getReporting();
if (reporting != null) {
expandReport(reporting.getPlugins());
}
return model.withBuild(build);
}
private List<Plugin> expandPlugin(List<Plugin> oldPlugins) {
return map(oldPlugins, plugin -> {
XmlNode pluginConfiguration = plugin.getConfiguration();
if (pluginConfiguration != null) {
return plugin.withExecutions(map(
plugin.getExecutions(),
execution -> execution.withConfiguration(
XmlNode.merge(execution.getConfiguration(), pluginConfiguration))));
} else {
return plugin;
}
});
}
private List<ReportPlugin> expandReport(List<ReportPlugin> oldPlugins) {
return map(oldPlugins, plugin -> {
XmlNode pluginConfiguration = plugin.getConfiguration();
if (pluginConfiguration != null) {
return plugin.withReportSets(map(
plugin.getReportSets(),
report -> report.withConfiguration(
XmlNode.merge(report.getConfiguration(), pluginConfiguration))));
} else {
return plugin;
}
});
}
static <T> List<T> map(List<T> list, Function<T, T> mapper) {<FILL_FUNCTION_BODY>}
}
|
List<T> newList = list;
for (int i = 0; i < newList.size(); i++) {
T oldT = newList.get(i);
T newT = mapper.apply(oldT);
if (newT != oldT) {
if (newList == list) {
newList = new ArrayList<>(list);
}
newList.set(i, newT);
}
}
return newList;
| 505
| 121
| 626
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultRepositoryFactory.java
|
DefaultRepositoryFactory
|
buildRepositoryPolicy
|
class DefaultRepositoryFactory implements RepositoryFactory {
@Override
public LocalRepository createLocal(Path path) {
return new DefaultLocalRepository(new org.eclipse.aether.repository.LocalRepository(path.toFile()));
}
@Override
public RemoteRepository createRemote(String id, String url) {
return new DefaultRemoteRepository(
new org.eclipse.aether.repository.RemoteRepository.Builder(id, "default", url).build());
}
@Override
public RemoteRepository createRemote(Repository repository) throws IllegalArgumentException {
return new DefaultRemoteRepository(new org.eclipse.aether.repository.RemoteRepository.Builder(
repository.getId(), repository.getLayout(), repository.getUrl())
.setReleasePolicy(buildRepositoryPolicy(repository.getReleases()))
.setSnapshotPolicy(buildRepositoryPolicy(repository.getSnapshots()))
.build());
}
public static org.eclipse.aether.repository.RepositoryPolicy buildRepositoryPolicy(
org.apache.maven.api.model.RepositoryPolicy policy) {<FILL_FUNCTION_BODY>}
}
|
boolean enabled = true;
String updatePolicy = RepositoryPolicy.UPDATE_POLICY_DAILY;
String checksumPolicy = RepositoryPolicy.CHECKSUM_POLICY_FAIL;
if (policy != null) {
enabled = policy.isEnabled();
if (policy.getUpdatePolicy() != null) {
updatePolicy = policy.getUpdatePolicy();
}
if (policy.getChecksumPolicy() != null) {
checksumPolicy = policy.getChecksumPolicy();
}
}
return new org.eclipse.aether.repository.RepositoryPolicy(enabled, updatePolicy, checksumPolicy);
| 266
| 164
| 430
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultSettingsXmlFactory.java
|
DefaultSettingsXmlFactory
|
write
|
class DefaultSettingsXmlFactory implements SettingsXmlFactory {
@Override
public Settings read(@Nonnull XmlReaderRequest request) throws XmlReaderException {
nonNull(request, "request");
Reader reader = request.getReader();
InputStream inputStream = request.getInputStream();
if (reader == null && inputStream == null) {
throw new IllegalArgumentException("reader or inputStream must be non null");
}
try {
InputSource source = null;
if (request.getModelId() != null || request.getLocation() != null) {
source = new InputSource(request.getLocation());
}
SettingsStaxReader xml = new SettingsStaxReader();
xml.setAddDefaultEntities(request.isAddDefaultEntities());
if (reader != null) {
return xml.read(reader, request.isStrict(), source);
} else {
return xml.read(inputStream, request.isStrict(), source);
}
} catch (Exception e) {
throw new XmlReaderException("Unable to read settings: " + getMessage(e), getLocation(e), e);
}
}
@Override
public void write(XmlWriterRequest<Settings> request) throws XmlWriterException {<FILL_FUNCTION_BODY>}
static <T> T nonNull(T t, String name) {
if (t == null) {
throw new IllegalArgumentException(name + " cannot be null");
}
return t;
}
}
|
nonNull(request, "request");
Settings content = nonNull(request.getContent(), "content");
OutputStream outputStream = request.getOutputStream();
Writer writer = request.getWriter();
if (writer == null && outputStream == null) {
throw new IllegalArgumentException("writer or outputStream must be non null");
}
try {
if (writer != null) {
new SettingsStaxWriter().write(writer, content);
} else {
new SettingsStaxWriter().write(outputStream, content);
}
} catch (Exception e) {
throw new XmlWriterException("Unable to write settings: " + getMessage(e), getLocation(e), e);
}
| 372
| 177
| 549
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultSuperPomProvider.java
|
DefaultSuperPomProvider
|
readModel
|
class DefaultSuperPomProvider implements SuperPomProvider {
private final ModelProcessor modelProcessor;
/**
* The cached super POM, lazily created.
*/
private static final Map<String, Model> SUPER_MODELS = new ConcurrentHashMap<>();
@Inject
public DefaultSuperPomProvider(ModelProcessor modelProcessor) {
this.modelProcessor = modelProcessor;
}
@Override
public Model getSuperPom(String version) {
return SUPER_MODELS.computeIfAbsent(Objects.requireNonNull(version), v -> readModel(version, v));
}
private Model readModel(String version, String v) {<FILL_FUNCTION_BODY>}
}
|
String resource = "/org/apache/maven/model/pom-" + v + ".xml";
URL url = getClass().getResource(resource);
if (url == null) {
throw new IllegalStateException("The super POM " + resource + " was not found"
+ ", please verify the integrity of your Maven installation");
}
try (InputStream is = url.openStream()) {
String modelId = "org.apache.maven:maven-model-builder:" + version + "-"
+ this.getClass().getPackage().getImplementationVersion() + ":super-pom";
return modelProcessor.read(XmlReaderRequest.builder()
.modelId(modelId)
.location(url.toExternalForm())
.inputStream(is)
.strict(false)
.build());
} catch (IOException e) {
throw new IllegalStateException(
"The super POM " + resource + " is damaged"
+ ", please verify the integrity of your Maven installation",
e);
}
| 186
| 254
| 440
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsBuilder.java
|
DefaultToolchainsBuilder
|
readToolchains
|
class DefaultToolchainsBuilder implements ToolchainsBuilder {
private final MavenToolchainsMerger toolchainsMerger = new MavenToolchainsMerger();
@Override
public ToolchainsBuilderResult build(ToolchainsBuilderRequest request) throws ToolchainsBuilderException {
List<BuilderProblem> problems = new ArrayList<>();
Source globalSource = request.getGlobalToolchainsSource().orElse(null);
PersistedToolchains global = readToolchains(globalSource, request, problems);
Source userSource = request.getUserToolchainsSource().orElse(null);
PersistedToolchains user = readToolchains(userSource, request, problems);
PersistedToolchains effective = toolchainsMerger.merge(user, global, false, null);
if (hasErrors(problems)) {
throw new ToolchainsBuilderException("Error building toolchains", problems);
}
return new DefaultToolchainsBuilderResult(effective, problems);
}
private boolean hasErrors(List<BuilderProblem> problems) {
if (problems != null) {
for (BuilderProblem problem : problems) {
if (BuilderProblem.Severity.ERROR.compareTo(problem.getSeverity()) >= 0) {
return true;
}
}
}
return false;
}
private PersistedToolchains readToolchains(
Source toolchainsSource, ToolchainsBuilderRequest request, List<BuilderProblem> problems) {<FILL_FUNCTION_BODY>}
private PersistedToolchains interpolate(
PersistedToolchains toolchains, ToolchainsBuilderRequest request, List<BuilderProblem> problems) {
RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
interpolator.addValueSource(new MapBasedValueSource(request.getSession().getUserProperties()));
interpolator.addValueSource(new MapBasedValueSource(request.getSession().getSystemProperties()));
try {
interpolator.addValueSource(new EnvarBasedValueSource());
} catch (IOException e) {
problems.add(new DefaultBuilderProblem(
null,
-1,
-1,
e,
"Failed to use environment variables for interpolation: " + e.getMessage(),
BuilderProblem.Severity.WARNING));
}
return new MavenToolchainsTransformer(value -> {
try {
return value != null ? interpolator.interpolate(value) : null;
} catch (InterpolationException e) {
problems.add(new DefaultBuilderProblem(
null,
-1,
-1,
e,
"Failed to interpolate toolchains: " + e.getMessage(),
BuilderProblem.Severity.WARNING));
return value;
}
})
.visit(toolchains);
}
/**
* Collects the output of the toolchains builder.
*
*/
static class DefaultToolchainsBuilderResult implements ToolchainsBuilderResult {
private final PersistedToolchains effectiveToolchains;
private final List<BuilderProblem> problems;
DefaultToolchainsBuilderResult(PersistedToolchains effectiveToolchains, List<BuilderProblem> problems) {
this.effectiveToolchains = effectiveToolchains;
this.problems = (problems != null) ? problems : new ArrayList<>();
}
@Override
public PersistedToolchains getEffectiveToolchains() {
return effectiveToolchains;
}
@Override
public List<BuilderProblem> getProblems() {
return problems;
}
}
}
|
if (toolchainsSource == null) {
return PersistedToolchains.newInstance();
}
PersistedToolchains toolchains;
try {
try {
InputStream is = toolchainsSource.openStream();
if (is == null) {
return PersistedToolchains.newInstance();
}
toolchains = request.getSession()
.getService(ToolchainsXmlFactory.class)
.read(XmlReaderRequest.builder()
.inputStream(is)
.location(toolchainsSource.getLocation())
.strict(true)
.build());
} catch (XmlReaderException e) {
InputStream is = toolchainsSource.openStream();
if (is == null) {
return PersistedToolchains.newInstance();
}
toolchains = request.getSession()
.getService(ToolchainsXmlFactory.class)
.read(XmlReaderRequest.builder()
.inputStream(is)
.location(toolchainsSource.getLocation())
.strict(false)
.build());
Location loc = e.getCause() instanceof XMLStreamException xe ? xe.getLocation() : null;
problems.add(new DefaultBuilderProblem(
toolchainsSource.getLocation(),
loc != null ? loc.getLineNumber() : -1,
loc != null ? loc.getColumnNumber() : -1,
e,
e.getMessage(),
BuilderProblem.Severity.WARNING));
}
} catch (XmlReaderException e) {
Location loc = e.getCause() instanceof XMLStreamException xe ? xe.getLocation() : null;
problems.add(new DefaultBuilderProblem(
toolchainsSource.getLocation(),
loc != null ? loc.getLineNumber() : -1,
loc != null ? loc.getColumnNumber() : -1,
e,
"Non-parseable toolchains " + toolchainsSource.getLocation() + ": " + e.getMessage(),
BuilderProblem.Severity.FATAL));
return PersistedToolchains.newInstance();
} catch (IOException e) {
problems.add(new DefaultBuilderProblem(
toolchainsSource.getLocation(),
-1,
-1,
e,
"Non-readable toolchains " + toolchainsSource.getLocation() + ": " + e.getMessage(),
BuilderProblem.Severity.FATAL));
return PersistedToolchains.newInstance();
}
toolchains = interpolate(toolchains, request, problems);
return toolchains;
| 930
| 666
| 1,596
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultToolchainsXmlFactory.java
|
DefaultToolchainsXmlFactory
|
read
|
class DefaultToolchainsXmlFactory implements ToolchainsXmlFactory {
@Override
public PersistedToolchains read(@Nonnull XmlReaderRequest request) throws XmlReaderException {<FILL_FUNCTION_BODY>}
@Override
public void write(XmlWriterRequest<PersistedToolchains> request) throws XmlWriterException {
nonNull(request, "request");
PersistedToolchains content = Objects.requireNonNull(request.getContent(), "content");
OutputStream outputStream = request.getOutputStream();
Writer writer = request.getWriter();
if (writer == null && outputStream == null) {
throw new IllegalArgumentException("writer or outputStream must be non null");
}
try {
if (writer != null) {
new MavenToolchainsStaxWriter().write(writer, content);
} else {
new MavenToolchainsStaxWriter().write(outputStream, content);
}
} catch (Exception e) {
throw new XmlWriterException("Unable to write toolchains: " + getMessage(e), getLocation(e), e);
}
}
}
|
Objects.requireNonNull(request, "request");
Reader reader = request.getReader();
InputStream inputStream = request.getInputStream();
if (reader == null && inputStream == null) {
throw new IllegalArgumentException("reader or inputStream must be non null");
}
try {
InputSource source = null;
if (request.getModelId() != null || request.getLocation() != null) {
source = new InputSource(request.getModelId(), request.getLocation());
}
MavenToolchainsStaxReader xml = new MavenToolchainsStaxReader();
xml.setAddDefaultEntities(request.isAddDefaultEntities());
if (reader != null) {
return xml.read(reader, request.isStrict());
} else {
return xml.read(inputStream, request.isStrict());
}
} catch (Exception e) {
throw new XmlReaderException("Unable to read toolchains: " + getMessage(e), getLocation(e), e);
}
| 281
| 262
| 543
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultTransport.java
|
DefaultTransport
|
putBytes
|
class DefaultTransport implements Transport {
private final URI baseURI;
private final Transporter transporter;
public DefaultTransport(URI baseURI, Transporter transporter) {
this.baseURI = requireNonNull(baseURI);
this.transporter = requireNonNull(transporter);
}
@Override
public boolean get(URI relativeSource, Path target) {
requireNonNull(relativeSource, "relativeSource is null");
requireNonNull(target, "target is null");
if (relativeSource.isAbsolute()) {
throw new IllegalArgumentException("Supplied URI is not relative");
}
URI source = baseURI.resolve(relativeSource);
if (!source.toASCIIString().startsWith(baseURI.toASCIIString())) {
throw new IllegalArgumentException("Supplied relative URI escapes baseUrl");
}
GetTask getTask = new GetTask(source);
getTask.setDataFile(target.toFile());
try {
transporter.get(getTask);
return true;
} catch (Exception e) {
if (Transporter.ERROR_NOT_FOUND != transporter.classify(e)) {
throw new RuntimeException(e);
}
return false;
}
}
@Override
public Optional<byte[]> getBytes(URI relativeSource) {
try {
Path tempPath = null;
try {
tempPath = Files.createTempFile("transport-get", "tmp");
if (get(relativeSource, tempPath)) {
// TODO: check file size and prevent OOM?
return Optional.of(Files.readAllBytes(tempPath));
}
return Optional.empty();
} finally {
if (tempPath != null) {
Files.deleteIfExists(tempPath);
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public Optional<String> getString(URI relativeSource, Charset charset) {
requireNonNull(charset, "charset is null");
Optional<byte[]> data = getBytes(relativeSource);
return data.map(bytes -> new String(bytes, charset));
}
@Override
public void put(Path source, URI relativeTarget) {
requireNonNull(source, "source is null");
requireNonNull(relativeTarget, "relativeTarget is null");
if (Files.isRegularFile(source)) {
throw new IllegalArgumentException("source file does not exist or is not a file");
}
if (relativeTarget.isAbsolute()) {
throw new IllegalArgumentException("Supplied URI is not relative");
}
URI target = baseURI.resolve(relativeTarget);
if (!target.toASCIIString().startsWith(baseURI.toASCIIString())) {
throw new IllegalArgumentException("Supplied relative URI escapes baseUrl");
}
PutTask putTask = new PutTask(target);
putTask.setDataFile(source.toFile());
try {
transporter.put(putTask);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void putBytes(byte[] source, URI relativeTarget) {<FILL_FUNCTION_BODY>}
@Override
public void putString(String source, Charset charset, URI relativeTarget) {
requireNonNull(source, "source string is null");
requireNonNull(charset, "charset is null");
putBytes(source.getBytes(charset), relativeTarget);
}
@Override
public void close() {
transporter.close();
}
}
|
requireNonNull(source, "source is null");
try {
Path tempPath = null;
try {
tempPath = Files.createTempFile("transport-get", "tmp");
Files.write(tempPath, source);
put(tempPath, relativeTarget);
} finally {
if (tempPath != null) {
Files.deleteIfExists(tempPath);
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
| 912
| 127
| 1,039
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultTransportProvider.java
|
DefaultTransportProvider
|
transport
|
class DefaultTransportProvider implements TransportProvider {
private final org.eclipse.aether.spi.connector.transport.TransporterProvider transporterProvider;
@Inject
public DefaultTransportProvider(TransporterProvider transporterProvider) {
this.transporterProvider = requireNonNull(transporterProvider);
}
@Override
public Transport transport(Session session, RemoteRepository repository) {<FILL_FUNCTION_BODY>}
}
|
try {
URI baseURI = new URI(repository.getUrl());
return new DefaultTransport(
baseURI,
transporterProvider.newTransporter(
InternalSession.from(session).getSession(),
((DefaultRemoteRepository) repository).getRepository()));
} catch (URISyntaxException e) {
throw new TransportProviderException("Remote repository URL invalid", e);
} catch (NoTransporterException e) {
throw new TransportProviderException("Unsupported remote repository", e);
}
| 108
| 124
| 232
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultUrlNormalizer.java
|
DefaultUrlNormalizer
|
normalize
|
class DefaultUrlNormalizer implements UrlNormalizer {
@Override
public String normalize(String url) {<FILL_FUNCTION_BODY>}
}
|
String result = url;
if (result != null) {
while (true) {
int idx = result.indexOf("/../");
if (idx < 0) {
break;
} else if (idx == 0) {
result = result.substring(3);
continue;
}
int parent = idx - 1;
while (parent >= 0 && result.charAt(parent) == '/') {
parent--;
}
parent = result.lastIndexOf('/', parent);
if (parent < 0) {
result = result.substring(idx + 4);
} else {
result = result.substring(0, parent) + result.substring(idx + 3);
}
}
}
return result;
| 42
| 196
| 238
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultVersionRangeResolver.java
|
DefaultVersionRangeResolver
|
resolve
|
class DefaultVersionRangeResolver implements VersionRangeResolver {
private final RepositorySystem repositorySystem;
@Inject
public DefaultVersionRangeResolver(RepositorySystem repositorySystem) {
this.repositorySystem = repositorySystem;
}
@Override
public VersionRangeResolverResult resolve(VersionRangeResolverRequest request)
throws VersionRangeResolverException {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
try {
VersionRangeResult res = repositorySystem.resolveVersionRange(
session.getSession(),
new VersionRangeRequest(
session.toArtifact(request.getArtifactCoordinate()),
session.toRepositories(session.getRemoteRepositories()),
null));
Map<String, ArtifactRepository> repos = res.getVersions().stream()
.filter(v -> res.getRepository(v) != null)
.collect(Collectors.toMap(v -> v.toString(), res::getRepository));
return new VersionRangeResolverResult() {
@Override
public List<Exception> getExceptions() {
return res.getExceptions();
}
@Override
public List<Version> getVersions() {
return map(res.getVersions(), v -> session.parseVersion(v.toString()));
}
@Override
public Optional<Repository> getRepository(Version version) {
ArtifactRepository repo = repos.get(version.toString());
if (repo instanceof org.eclipse.aether.repository.LocalRepository) {
return Optional.of(
new DefaultLocalRepository((org.eclipse.aether.repository.LocalRepository) repo));
} else if (repo instanceof org.eclipse.aether.repository.RemoteRepository) {
return Optional.of(
new DefaultRemoteRepository((org.eclipse.aether.repository.RemoteRepository) repo));
} else {
return Optional.empty();
}
}
};
} catch (VersionRangeResolutionException e) {
throw new VersionRangeResolverException("Unable to resolve version range", e);
}
| 97
| 433
| 530
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/DefaultVersionResolver.java
|
DefaultVersionResolver
|
resolve
|
class DefaultVersionResolver implements VersionResolver {
private final RepositorySystem repositorySystem;
@Inject
public DefaultVersionResolver(RepositorySystem repositorySystem) {
this.repositorySystem = repositorySystem;
}
@Override
public VersionResolverResult resolve(VersionResolverRequest request) throws VersionResolverException {<FILL_FUNCTION_BODY>}
}
|
nonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
try {
VersionResult res = repositorySystem.resolveVersion(
session.getSession(),
new VersionRequest(
session.toArtifact(request.getArtifactCoordinate()),
session.toRepositories(session.getRemoteRepositories()),
null));
return new VersionResolverResult() {
@Override
public List<Exception> getExceptions() {
return res.getExceptions();
}
@Override
public Version getVersion() {
return session.parseVersion(res.getVersion());
}
@Override
public Optional<Repository> getRepository() {
if (res.getRepository() instanceof org.eclipse.aether.repository.LocalRepository) {
return Optional.of(new DefaultLocalRepository(
(org.eclipse.aether.repository.LocalRepository) res.getRepository()));
} else if (res.getRepository() instanceof org.eclipse.aether.repository.RemoteRepository) {
return Optional.of(new DefaultRemoteRepository(
(org.eclipse.aether.repository.RemoteRepository) res.getRepository()));
} else {
return Optional.empty();
}
}
};
} catch (VersionResolutionException e) {
throw new VersionResolverException("Unable to resolve version", e);
}
| 89
| 345
| 434
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/MappedCollection.java
|
MappedCollection
|
iterator
|
class MappedCollection<U, V> extends AbstractCollection<U> {
private final Collection<V> list;
private final Function<V, U> mapper;
public MappedCollection(Collection<V> list, Function<V, U> mapper) {
this.list = list;
this.mapper = mapper;
}
@Override
public Iterator<U> iterator() {<FILL_FUNCTION_BODY>}
@Override
public int size() {
return list.size();
}
}
|
Iterator<V> it = list.iterator();
return new Iterator<U>() {
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public U next() {
return mapper.apply(it.next());
}
};
| 138
| 80
| 218
|
<methods>public boolean add(U) ,public boolean addAll(Collection<? extends U>) ,public void clear() ,public boolean contains(java.lang.Object) ,public boolean containsAll(Collection<?>) ,public boolean isEmpty() ,public abstract Iterator<U> iterator() ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean retainAll(Collection<?>) ,public abstract int size() ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/PathModularizationCache.java
|
PathModularizationCache
|
selectPathType
|
class PathModularizationCache {
/**
* Module information for each JAR file or output directories.
* Cached when first requested to avoid decoding the module descriptors multiple times.
*
* @see #getModuleInfo(Path)
*/
private final Map<Path, PathModularization> moduleInfo;
/**
* Whether JAR files are modular. This map is redundant with {@link #moduleInfo},
* but cheaper to compute when the module names are not needed.
*
* @see #getPathType(Path)
*/
private final Map<Path, PathType> pathTypes;
/**
* Creates an initially empty cache.
*/
PathModularizationCache() {
moduleInfo = new HashMap<>();
pathTypes = new HashMap<>();
}
/**
* Gets module information for the given JAR file or output directory.
* Module descriptors are read when first requested, then cached.
*/
PathModularization getModuleInfo(Path path) throws IOException {
PathModularization info = moduleInfo.get(path);
if (info == null) {
info = new PathModularization(path, true);
moduleInfo.put(path, info);
pathTypes.put(path, info.getPathType());
}
return info;
}
/**
* Returns {@link JavaPathType#MODULES} if the given JAR file or output directory is modular.
* This is used in heuristic rules for deciding whether to place a dependency on the class-path
* or on the module-path when the {@code "jar"} artifact type is used.
*/
private PathType getPathType(Path path) throws IOException {
PathType type = pathTypes.get(path);
if (type == null) {
type = new PathModularization(path, false).getPathType();
pathTypes.put(path, type);
}
return type;
}
/**
* Selects the type of path where to place the given dependency.
* This method returns one of the values specified in the given collection.
* This method does not handle the patch-module paths, because the patches
* depend on which modules have been previously added on the module-paths.
*
* <p>If the dependency can be a constituent of both the class-path and the module-path,
* then the path type is determined by checking if the dependency is modular.</p>
*
* @param types types of path where a dependency can be placed
* @param filter filter the paths accepted by the tool which will consume the path
* @param path path to the JAR file or output directory of the dependency
* @return where to place the dependency, or an empty value if the placement cannot be determined
* @throws IOException if an error occurred while reading module information
*/
Optional<PathType> selectPathType(Set<PathType> types, Predicate<PathType> filter, Path path) throws IOException {<FILL_FUNCTION_BODY>}
}
|
PathType selected = null;
boolean classes = false;
boolean modules = false;
boolean unknown = false;
for (PathType type : types) {
if (filter.test(type)) {
if (JavaPathType.CLASSES.equals(type)) {
classes = true;
} else if (JavaPathType.MODULES.equals(type)) {
modules = true;
} else {
unknown = true;
}
if (selected == null) {
selected = type;
} else if (unknown) {
// More than one filtered value, and we don't know how to handle at least one of them.
// TODO: add a plugin mechanism for allowing plugin to specify their selection algorithm.
return Optional.empty();
}
}
}
if (classes & modules) {
selected = getPathType(path);
}
return Optional.ofNullable(selected);
| 741
| 231
| 972
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java
|
PropertiesAsMap
|
entrySet
|
class PropertiesAsMap extends AbstractMap<String, String> {
private final Map<Object, Object> properties;
PropertiesAsMap(Map<Object, Object> properties) {
this.properties = properties;
}
@Override
public Set<Entry<String, String>> entrySet() {<FILL_FUNCTION_BODY>}
private static boolean matches(Entry<Object, Object> entry) {
return entry.getKey() instanceof String && entry.getValue() instanceof String;
}
}
|
return new AbstractSet<Entry<String, String>>() {
@Override
public Iterator<Entry<String, String>> iterator() {
Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
return new Iterator<Entry<String, String>>() {
Entry<String, String> next;
{
advance();
}
private void advance() {
next = null;
while (iterator.hasNext()) {
Entry<Object, Object> e = iterator.next();
if (PropertiesAsMap.matches(e)) {
next = new Entry<String, String>() {
@Override
public String getKey() {
return (String) e.getKey();
}
@Override
public String getValue() {
return (String) e.getValue();
}
@Override
public String setValue(String value) {
return (String) e.setValue(value);
}
};
break;
}
}
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Entry<String, String> next() {
Entry<String, String> item = next;
if (item == null) {
throw new NoSuchElementException();
}
advance();
return item;
}
};
}
@Override
public int size() {
return (int) properties.entrySet().stream()
.filter(PropertiesAsMap::matches)
.count();
}
};
| 126
| 401
| 527
|
<methods>public void clear() ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public abstract Set<Entry<java.lang.String,java.lang.String>> entrySet() ,public boolean equals(java.lang.Object) ,public java.lang.String get(java.lang.Object) ,public int hashCode() ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public java.lang.String put(java.lang.String, java.lang.String) ,public void putAll(Map<? extends java.lang.String,? extends java.lang.String>) ,public java.lang.String remove(java.lang.Object) ,public int size() ,public java.lang.String toString() ,public Collection<java.lang.String> values() <variables>transient Set<java.lang.String> keySet,transient Collection<java.lang.String> values
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/StaxLocation.java
|
StaxLocation
|
getMessage
|
class StaxLocation implements Location {
private final javax.xml.stream.Location location;
public static Location getLocation(Exception e) {
return toLocation(e instanceof XMLStreamException xe ? xe.getLocation() : null);
}
public static Location toLocation(javax.xml.stream.Location location) {
return location != null ? new StaxLocation(location) : null;
}
public static String getMessage(Exception e) {<FILL_FUNCTION_BODY>}
public StaxLocation(javax.xml.stream.Location location) {
this.location = location;
}
@Override
public int getLineNumber() {
return location.getLineNumber();
}
@Override
public int getColumnNumber() {
return location.getColumnNumber();
}
@Override
public int getCharacterOffset() {
return location.getCharacterOffset();
}
@Override
public String getPublicId() {
return location.getPublicId();
}
@Override
public String getSystemId() {
return location.getSystemId();
}
}
|
String message = e.getMessage();
if (e instanceof XMLStreamException xe && xe.getLocation() != null) {
int idx = message.indexOf("\nMessage: ");
if (idx >= 0) {
return message.substring(idx + "\nMessage: ".length());
}
}
return message;
| 289
| 85
| 374
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/Utils.java
|
Utils
|
cast
|
class Utils {
static <T> T nonNull(T t) {
if (t == null) {
throw new IllegalArgumentException();
}
return t;
}
static <T> T nonNull(T t, String name) {
if (t == null) {
throw new IllegalArgumentException(name + " cannot be null");
}
return t;
}
static <T> T cast(Class<T> clazz, Object o, String name) {<FILL_FUNCTION_BODY>}
static <U, V> List<V> map(Collection<U> list, Function<U, V> mapper) {
return list.stream().map(mapper).collect(Collectors.toList());
}
}
|
if (!clazz.isInstance(o)) {
if (o == null) {
throw new IllegalArgumentException(name + " is null");
}
throw new IllegalArgumentException(name + " is not an instance of " + clazz.getName());
}
return clazz.cast(o);
| 190
| 76
| 266
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/BuildModelTransformer.java
|
BuildModelTransformer
|
resolveRelativePath
|
class BuildModelTransformer implements ModelTransformer {
public static final String NAMESPACE_PREFIX = "http://maven.apache.org/POM/";
@Override
public Model transform(ModelTransformerContext context, Model model, Path path) {
Model.Builder builder = Model.newBuilder(model);
handleModelVersion(context, model, path, builder);
handleParent(context, model, path, builder);
handleReactorDependencies(context, model, path, builder);
handleCiFriendlyVersion(context, model, path, builder);
return builder.build();
}
//
// Infer modelVersion from namespace URI
//
void handleModelVersion(ModelTransformerContext context, Model model, Path pomFile, Model.Builder builder) {
String namespace = model.getNamespaceUri();
if (model.getModelVersion() == null && namespace != null && namespace.startsWith(NAMESPACE_PREFIX)) {
builder.modelVersion(namespace.substring(NAMESPACE_PREFIX.length()));
}
}
//
// Infer parent information
//
void handleParent(ModelTransformerContext context, Model model, Path pomFile, Model.Builder builder) {
Parent parent = model.getParent();
if (parent != null) {
String version = parent.getVersion();
String path = Optional.ofNullable(parent.getRelativePath()).orElse("..");
if (version == null && !path.isEmpty()) {
Optional<RelativeProject> resolvedParent = resolveRelativePath(
pomFile, context, Paths.get(path), parent.getGroupId(), parent.getArtifactId());
if (resolvedParent.isPresent()) {
version = resolvedParent.get().getVersion();
}
}
// CI Friendly version for parent
String modVersion = replaceCiFriendlyVersion(context, version);
builder.parent(parent.withVersion(modVersion));
}
}
//
// CI friendly versions
//
void handleCiFriendlyVersion(ModelTransformerContext context, Model model, Path pomFile, Model.Builder builder) {
String version = model.getVersion();
String modVersion = replaceCiFriendlyVersion(context, version);
builder.version(modVersion);
}
//
// Infer inner reactor dependencies version
//
void handleReactorDependencies(ModelTransformerContext context, Model model, Path pomFile, Model.Builder builder) {
List<Dependency> newDeps = new ArrayList<>();
boolean modified = false;
for (Dependency dep : model.getDependencies()) {
if (dep.getVersion() == null) {
Model depModel = context.getRawModel(model.getPomFile(), dep.getGroupId(), dep.getArtifactId());
if (depModel != null) {
String v = depModel.getVersion();
if (v == null && depModel.getParent() != null) {
v = depModel.getParent().getVersion();
}
dep = dep.withVersion(v);
modified = true;
}
}
newDeps.add(dep);
}
if (modified) {
builder.dependencies(newDeps);
}
}
protected String replaceCiFriendlyVersion(ModelTransformerContext context, String version) {
if (version != null) {
for (String key : Arrays.asList("changelist", "revision", "sha1")) {
String val = context.getUserProperty(key);
if (val != null) {
version = version.replace("${" + key + "}", val);
}
}
}
return version;
}
protected Optional<RelativeProject> resolveRelativePath(
Path pomFile, ModelTransformerContext context, Path relativePath, String groupId, String artifactId) {<FILL_FUNCTION_BODY>}
private static RelativeProject toRelativeProject(final Model m) {
String groupId = m.getGroupId();
if (groupId == null && m.getParent() != null) {
groupId = m.getParent().getGroupId();
}
String version = m.getVersion();
if (version == null && m.getParent() != null) {
version = m.getParent().getVersion();
}
return new RelativeProject(groupId, m.getArtifactId(), version);
}
protected static class RelativeProject {
private final String groupId;
private final String artifactId;
private final String version;
protected RelativeProject(String groupId, String artifactId, String version) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
}
}
|
Path pomPath = pomFile.resolveSibling(relativePath).normalize();
if (Files.isDirectory(pomPath)) {
pomPath = context.locate(pomPath);
}
if (pomPath == null || !Files.isRegularFile(pomPath)) {
return Optional.empty();
}
Optional<RelativeProject> mappedProject = Optional.ofNullable(context.getRawModel(pomFile, pomPath.normalize()))
.map(BuildModelTransformer::toRelativeProject);
if (mappedProject.isPresent()) {
RelativeProject project = mappedProject.get();
if (Objects.equals(groupId, project.getGroupId()) && Objects.equals(artifactId, project.getArtifactId())) {
return mappedProject;
}
}
return Optional.empty();
| 1,256
| 217
| 1,473
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultDependencyManagementImporter.java
|
DefaultDependencyManagementImporter
|
equals
|
class DefaultDependencyManagementImporter implements DependencyManagementImporter {
@Override
public Model importManagement(
Model target,
List<? extends DependencyManagement> sources,
ModelBuilderRequest request,
ModelProblemCollector problems) {
if (sources != null && !sources.isEmpty()) {
Map<String, Dependency> dependencies = new LinkedHashMap<>();
DependencyManagement depMgmt = target.getDependencyManagement();
if (depMgmt != null) {
for (Dependency dependency : depMgmt.getDependencies()) {
dependencies.put(dependency.getManagementKey(), dependency);
}
} else {
depMgmt = DependencyManagement.newInstance();
}
Set<String> directDependencies = new HashSet<>(dependencies.keySet());
for (DependencyManagement source : sources) {
for (Dependency dependency : source.getDependencies()) {
String key = dependency.getManagementKey();
Dependency present = dependencies.putIfAbsent(key, dependency);
if (present != null && !equals(dependency, present) && !directDependencies.contains(key)) {
// TODO: https://issues.apache.org/jira/browse/MNG-8004
problems.add(
Severity.WARNING,
Version.V40,
"Ignored POM import for: " + toString(dependency) + " as already imported "
+ toString(present) + ". Add a the conflicting managed dependency directly "
+ "to the dependencyManagement section of the POM.");
}
}
}
return target.withDependencyManagement(depMgmt.withDependencies(dependencies.values()));
}
return target;
}
private String toString(Dependency dependency) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(dependency.getGroupId())
.append(":")
.append(dependency.getArtifactId())
.append(":")
.append(dependency.getType());
if (dependency.getClassifier() != null && !dependency.getClassifier().isEmpty()) {
stringBuilder.append(":").append(dependency.getClassifier());
}
stringBuilder
.append(":")
.append(dependency.getVersion())
.append("@")
.append(dependency.getScope() == null ? "compile" : dependency.getScope());
if (dependency.isOptional()) {
stringBuilder.append("[optional]");
}
if (!dependency.getExclusions().isEmpty()) {
stringBuilder.append("[").append(dependency.getExclusions().size()).append(" exclusions]");
}
return stringBuilder.toString();
}
private boolean equals(Dependency d1, Dependency d2) {<FILL_FUNCTION_BODY>}
private boolean equals(Collection<Exclusion> ce1, Collection<Exclusion> ce2) {
if (ce1.size() == ce2.size()) {
Iterator<Exclusion> i1 = ce1.iterator();
Iterator<Exclusion> i2 = ce2.iterator();
while (i1.hasNext() && i2.hasNext()) {
if (!equals(i1.next(), i2.next())) {
return false;
}
}
return !i1.hasNext() && !i2.hasNext();
}
return false;
}
private boolean equals(Exclusion e1, Exclusion e2) {
return Objects.equals(e1.getGroupId(), e2.getGroupId())
&& Objects.equals(e1.getArtifactId(), e2.getArtifactId());
}
}
|
return Objects.equals(d1.getGroupId(), d2.getGroupId())
&& Objects.equals(d1.getArtifactId(), d2.getArtifactId())
&& Objects.equals(d1.getVersion(), d2.getVersion())
&& Objects.equals(d1.getType(), d2.getType())
&& Objects.equals(d1.getClassifier(), d2.getClassifier())
&& Objects.equals(d1.getScope(), d2.getScope())
&& Objects.equals(d1.getSystemPath(), d2.getSystemPath())
&& Objects.equals(d1.getOptional(), d2.getOptional())
&& equals(d1.getExclusions(), d2.getExclusions());
| 927
| 192
| 1,119
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultDependencyManagementInjector.java
|
ManagementModelMerger
|
mergeManagedDependencies
|
class ManagementModelMerger extends MavenModelMerger {
public Model mergeManagedDependencies(Model model) {<FILL_FUNCTION_BODY>}
@Override
protected void mergeDependency_Optional(
Dependency.Builder builder,
Dependency target,
Dependency source,
boolean sourceDominant,
Map<Object, Object> context) {
// optional flag is not managed
}
@Override
protected void mergeDependency_Exclusions(
Dependency.Builder builder,
Dependency target,
Dependency source,
boolean sourceDominant,
Map<Object, Object> context) {
List<Exclusion> tgt = target.getExclusions();
if (tgt.isEmpty()) {
List<Exclusion> src = source.getExclusions();
builder.exclusions(src);
}
}
}
|
DependencyManagement dependencyManagement = model.getDependencyManagement();
if (dependencyManagement != null) {
Map<Object, Dependency> dependencies = new HashMap<>();
Map<Object, Object> context = Collections.emptyMap();
for (Dependency dependency : model.getDependencies()) {
Object key = getDependencyKey().apply(dependency);
dependencies.put(key, dependency);
}
boolean modified = false;
for (Dependency managedDependency : dependencyManagement.getDependencies()) {
Object key = getDependencyKey().apply(managedDependency);
Dependency dependency = dependencies.get(key);
if (dependency != null) {
Dependency merged = mergeDependency(dependency, managedDependency, false, context);
if (merged != dependency) {
dependencies.put(key, merged);
modified = true;
}
}
}
if (modified) {
List<Dependency> newDeps = new ArrayList<>(dependencies.size());
for (Dependency dep : model.getDependencies()) {
Object key = getDependencyKey().apply(dep);
Dependency dependency = dependencies.get(key);
newDeps.add(dependency);
}
return Model.newBuilder(model).dependencies(newDeps).build();
}
}
return model;
| 225
| 331
| 556
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultLifecycleBindingsInjector.java
|
DefaultLifecycleBindingsInjector
|
injectLifecycleBindings
|
class DefaultLifecycleBindingsInjector implements LifecycleBindingsInjector {
private final LifecycleBindingsMerger merger = new LifecycleBindingsMerger();
private final LifecycleRegistry lifecycleRegistry;
private final PackagingRegistry packagingRegistry;
@Inject
public DefaultLifecycleBindingsInjector(LifecycleRegistry lifecycleRegistry, PackagingRegistry packagingRegistry) {
this.lifecycleRegistry = lifecycleRegistry;
this.packagingRegistry = packagingRegistry;
}
public Model injectLifecycleBindings(Model model, ModelBuilderRequest request, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
private void addPlugin(Map<Plugin, Plugin> plugins, Plugin plugin) {
Plugin cur = plugins.putIfAbsent(plugin, plugin);
if (cur != null) {
Map<String, PluginExecution> execs = new LinkedHashMap<>();
cur.getExecutions().forEach(e -> execs.put(e.getId(), e));
plugin.getExecutions().forEach(e -> {
int i = 0;
String id = e.getId();
while (execs.putIfAbsent(id, e.withId(id)) != null) {
id = e.getId() + "-" + (++i);
}
});
Plugin merged = cur.withExecutions(execs.values());
plugins.put(merged, merged);
}
}
private static String getExecutionId(Plugin plugin, String goal) {
Set<String> existingIds = plugin != null
? plugin.getExecutions().stream().map(PluginExecution::getId).collect(Collectors.toSet())
: Set.of();
String base = "default-" + goal;
String id = base;
for (int index = 1; existingIds.contains(id); index++) {
id = base + '-' + index;
}
return id;
}
/**
* The domain-specific model merger for lifecycle bindings
*/
protected static class LifecycleBindingsMerger extends MavenModelMerger {
private static final String PLUGIN_MANAGEMENT = "plugin-management";
public Model merge(Model target, Model source) {
Build targetBuild = target.getBuild();
if (targetBuild == null) {
targetBuild = Build.newInstance();
}
Map<Object, Object> context =
Collections.singletonMap(PLUGIN_MANAGEMENT, targetBuild.getPluginManagement());
Build.Builder builder = Build.newBuilder(targetBuild);
mergePluginContainer_Plugins(builder, targetBuild, source.getBuild(), false, context);
return target.withBuild(builder.build());
}
@SuppressWarnings({"checkstyle:methodname"})
@Override
protected void mergePluginContainer_Plugins(
PluginContainer.Builder builder,
PluginContainer target,
PluginContainer source,
boolean sourceDominant,
Map<Object, Object> context) {
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
List<Plugin> tgt = target.getPlugins();
Map<Object, Plugin> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (Plugin element : tgt) {
Object key = getPluginKey().apply(element);
merged.put(key, element);
}
Map<Object, Plugin> added = new LinkedHashMap<>();
for (Plugin element : src) {
Object key = getPluginKey().apply(element);
Plugin existing = merged.get(key);
if (existing != null) {
element = mergePlugin(existing, element, sourceDominant, context);
} else {
added.put(key, element);
}
merged.put(key, element);
}
if (!added.isEmpty()) {
PluginManagement pluginMgmt = (PluginManagement) context.get(PLUGIN_MANAGEMENT);
if (pluginMgmt != null) {
for (Plugin managedPlugin : pluginMgmt.getPlugins()) {
Object key = getPluginKey().apply(managedPlugin);
Plugin addedPlugin = added.get(key);
if (addedPlugin != null) {
Plugin plugin =
mergePlugin(managedPlugin, addedPlugin, sourceDominant, Collections.emptyMap());
merged.put(key, plugin);
}
}
}
}
List<Plugin> result = new ArrayList<>(merged.values());
builder.plugins(result);
}
}
@Override
protected void mergePluginExecution_Priority(
PluginExecution.Builder builder,
PluginExecution target,
PluginExecution source,
boolean sourceDominant,
Map<Object, Object> context) {
if (target.getPriority() > source.getPriority()) {
builder.priority(source.getPriority());
builder.location("priority", source.getLocation("priority"));
}
}
// mergePluginExecution_Priority( builder, target, source, sourceDominant, context );
}
}
|
String packagingId = model.getPackaging();
Packaging packaging = packagingRegistry.lookup(packagingId).orElse(null);
if (packaging == null) {
problems.add(
Severity.ERROR, Version.BASE, "Unknown packaging: " + packagingId, model.getLocation("packaging"));
return model;
} else {
Map<String, PluginContainer> plugins = new HashMap<>(packaging.plugins());
lifecycleRegistry.stream()
.filter(lf -> !plugins.containsKey(lf.id()))
.forEach(lf -> plugins.put(
lf.id(),
PluginContainer.newBuilder()
.plugins(lf.phases().stream()
.flatMap(phase -> phase.plugins().stream())
.toList())
.build()));
Map<Plugin, Plugin> allPlugins = new LinkedHashMap<>();
plugins.values().stream().flatMap(pc -> pc.getPlugins().stream()).forEach(p -> addPlugin(allPlugins, p));
Model lifecycleModel = Model.newBuilder()
.build(Build.newBuilder().plugins(allPlugins.values()).build())
.build();
return merger.merge(model, lifecycleModel);
}
| 1,345
| 326
| 1,671
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelBuilderResult.java
|
DefaultModelBuilderResult
|
toString
|
class DefaultModelBuilderResult implements ModelBuilderResult {
private Model fileModel;
private Model activatedFileModel;
private Model effectiveModel;
private List<String> modelIds;
private Map<String, Model> rawModels;
private Map<String, List<Profile>> activePomProfiles;
private List<Profile> activeExternalProfiles;
private List<ModelProblem> problems;
DefaultModelBuilderResult() {
modelIds = new ArrayList<>();
rawModels = new HashMap<>();
activePomProfiles = new HashMap<>();
activeExternalProfiles = new ArrayList<>();
problems = new ArrayList<>();
}
DefaultModelBuilderResult(ModelBuilderResult result) {
this();
this.activeExternalProfiles.addAll(result.getActiveExternalProfiles());
this.effectiveModel = result.getEffectiveModel();
this.fileModel = result.getFileModel();
this.problems.addAll(result.getProblems());
for (String modelId : result.getModelIds()) {
this.modelIds.add(modelId);
this.rawModels.put(modelId, result.getRawModel(modelId).orElseThrow());
this.activePomProfiles.put(modelId, result.getActivePomProfiles(modelId));
}
}
@Override
public Model getFileModel() {
return fileModel;
}
public DefaultModelBuilderResult setFileModel(Model fileModel) {
this.fileModel = fileModel;
return this;
}
public Model getActivatedFileModel() {
return activatedFileModel;
}
public DefaultModelBuilderResult setActivatedFileModel(Model activatedFileModel) {
this.activatedFileModel = activatedFileModel;
return this;
}
@Override
public Model getEffectiveModel() {
return effectiveModel;
}
public DefaultModelBuilderResult setEffectiveModel(Model model) {
this.effectiveModel = model;
return this;
}
@Override
public List<String> getModelIds() {
return modelIds;
}
public DefaultModelBuilderResult addModelId(String modelId) {
// Intentionally notNull because Super POM may not contain a modelId
Objects.requireNonNull(modelId, "modelId cannot be null");
modelIds.add(modelId);
return this;
}
@Override
public Model getRawModel() {
return rawModels.get(modelIds.get(0));
}
@Override
public Optional<Model> getRawModel(String modelId) {
return Optional.ofNullable(rawModels.get(modelId));
}
public DefaultModelBuilderResult setRawModel(String modelId, Model rawModel) {
// Intentionally notNull because Super POM may not contain a modelId
Objects.requireNonNull(modelId, "modelId cannot be null");
rawModels.put(modelId, rawModel);
return this;
}
@Override
public List<Profile> getActivePomProfiles(String modelId) {
List<Profile> profiles = activePomProfiles.get(modelId);
return profiles != null ? profiles : List.of();
}
public DefaultModelBuilderResult setActivePomProfiles(String modelId, List<Profile> activeProfiles) {
// Intentionally notNull because Super POM may not contain a modelId
Objects.requireNonNull(modelId, "modelId cannot be null");
if (activeProfiles != null) {
this.activePomProfiles.put(modelId, new ArrayList<>(activeProfiles));
} else {
this.activePomProfiles.remove(modelId);
}
return this;
}
@Override
public List<Profile> getActiveExternalProfiles() {
return activeExternalProfiles;
}
public DefaultModelBuilderResult setActiveExternalProfiles(List<Profile> activeProfiles) {
if (activeProfiles != null) {
this.activeExternalProfiles = new ArrayList<>(activeProfiles);
} else {
this.activeExternalProfiles.clear();
}
return this;
}
@Override
public List<ModelProblem> getProblems() {
return problems;
}
public DefaultModelBuilderResult setProblems(List<ModelProblem> problems) {
if (problems != null) {
this.problems = new ArrayList<>(problems);
} else {
this.problems.clear();
}
return this;
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (!modelIds.isEmpty()) {
String modelId = modelIds.get(0);
StringBuilder sb = new StringBuilder();
sb.append(problems.size())
.append(
(problems.size() == 1)
? " problem was "
: " problems were encountered while building the effective model");
if (modelId != null && !modelId.isEmpty()) {
sb.append(" for ");
sb.append(modelId);
}
for (ModelProblem problem : problems) {
sb.append(System.lineSeparator());
sb.append(" - [");
sb.append(problem.getSeverity());
sb.append("] ");
sb.append(problem.getMessage());
String loc = Stream.of(
problem.getModelId().equals(modelId) ? problem.getModelId() : "",
problem.getModelId().equals(modelId) ? problem.getSource() : "",
problem.getLineNumber() > 0 ? "line " + problem.getLineNumber() : "",
problem.getColumnNumber() > 0 ? "column " + problem.getColumnNumber() : "")
.filter(s -> !s.isEmpty())
.collect(Collectors.joining(", "));
if (!loc.isEmpty()) {
sb.append(" @ ").append(loc);
}
}
return sb.toString();
}
return null;
| 1,189
| 354
| 1,543
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelNormalizer.java
|
DuplicateMerger
|
injectList
|
class DuplicateMerger extends MavenModelMerger {
public Plugin mergePlugin(Plugin target, Plugin source) {
return super.mergePlugin(target, source, false, Collections.emptyMap());
}
}
@Override
public Model injectDefaultValues(Model model, ModelBuilderRequest request, ModelProblemCollector problems) {
Model.Builder builder = Model.newBuilder(model);
builder.dependencies(injectList(model.getDependencies(), this::injectDependency));
Build build = model.getBuild();
if (build != null) {
Build newBuild = Build.newBuilder(build)
.plugins(injectList(build.getPlugins(), this::injectPlugin))
.build();
builder.build(newBuild != build ? newBuild : null);
}
return builder.build();
}
private Plugin injectPlugin(Plugin p) {
return Plugin.newBuilder(p)
.dependencies(injectList(p.getDependencies(), this::injectDependency))
.build();
}
private Dependency injectDependency(Dependency d) {
// we cannot set this directly in the MDO due to the interactions with dependency management
return (d.getScope() == null || d.getScope().isEmpty()) ? d.withScope("compile") : d;
}
/**
* Returns a list suited for the builders, i.e. null if not modified
*/
private <T> List<T> injectList(List<T> list, Function<T, T> modifer) {<FILL_FUNCTION_BODY>
|
List<T> newList = null;
for (int i = 0; i < list.size(); i++) {
T oldT = list.get(i);
T newT = modifer.apply(oldT);
if (newT != oldT) {
if (newList == null) {
newList = new ArrayList<>(list);
}
newList.set(i, newT);
}
}
return newList;
| 403
| 119
| 522
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelPathTranslator.java
|
DefaultModelPathTranslator
|
alignToBaseDirectory
|
class DefaultModelPathTranslator implements ModelPathTranslator {
private final PathTranslator pathTranslator;
@Inject
public DefaultModelPathTranslator(PathTranslator pathTranslator) {
this.pathTranslator = pathTranslator;
}
@Override
public Model alignToBaseDirectory(Model model, Path basedir, ModelBuilderRequest request) {<FILL_FUNCTION_BODY>}
private <T> List<T> map(List<T> resources, Function<T, T> mapper) {
List<T> newResources = null;
if (resources != null) {
for (int i = 0; i < resources.size(); i++) {
T resource = resources.get(i);
T newResource = mapper.apply(resource);
if (newResource != null) {
if (newResources == null) {
newResources = new ArrayList<>(resources);
}
newResources.set(i, newResource);
}
}
}
return newResources;
}
private Resource alignToBaseDirectory(Resource resource, Path basedir) {
if (resource != null) {
String newDir = alignToBaseDirectory(resource.getDirectory(), basedir);
if (newDir != null) {
return resource.withDirectory(newDir);
}
}
return resource;
}
private String alignToBaseDirectory(String path, Path basedir) {
String newPath = pathTranslator.alignToBaseDirectory(path, basedir);
return Objects.equals(path, newPath) ? null : newPath;
}
}
|
if (model == null || basedir == null) {
return model;
}
Build build = model.getBuild();
Build newBuild = null;
if (build != null) {
newBuild = Build.newBuilder(build)
.directory(alignToBaseDirectory(build.getDirectory(), basedir))
.sourceDirectory(alignToBaseDirectory(build.getSourceDirectory(), basedir))
.testSourceDirectory(alignToBaseDirectory(build.getTestSourceDirectory(), basedir))
.scriptSourceDirectory(alignToBaseDirectory(build.getScriptSourceDirectory(), basedir))
.resources(map(build.getResources(), r -> alignToBaseDirectory(r, basedir)))
.testResources(map(build.getTestResources(), r -> alignToBaseDirectory(r, basedir)))
.filters(map(build.getFilters(), s -> alignToBaseDirectory(s, basedir)))
.outputDirectory(alignToBaseDirectory(build.getOutputDirectory(), basedir))
.testOutputDirectory(alignToBaseDirectory(build.getTestOutputDirectory(), basedir))
.build();
}
Reporting reporting = model.getReporting();
Reporting newReporting = null;
if (reporting != null) {
newReporting = Reporting.newBuilder(reporting)
.outputDirectory(alignToBaseDirectory(reporting.getOutputDirectory(), basedir))
.build();
}
if (newBuild != build || newReporting != reporting) {
model = Model.newBuilder(model)
.build(newBuild)
.reporting(newReporting)
.build();
}
return model;
| 415
| 415
| 830
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelProblem.java
|
DefaultModelProblem
|
getMessage
|
class DefaultModelProblem implements ModelProblem {
private final String source;
private final int lineNumber;
private final int columnNumber;
private final String modelId;
private final String message;
private final Exception exception;
private final Severity severity;
private final Version version;
/**
* Creates a new problem with the specified message and exception.
*
* @param message The message describing the problem, may be {@code null}.
* @param severity The severity level of the problem, may be {@code null} to default to
* {@link Severity#ERROR}.
* @param source The source of the problem, may be {@code null}.
* @param lineNumber The one-based index of the line containing the error or {@code -1} if unknown.
* @param columnNumber The one-based index of the column containing the error or {@code -1} if unknown.
* @param exception The exception that caused this problem, may be {@code null}.
*/
// mkleint: does this need to be public?
public DefaultModelProblem(
String message,
Severity severity,
Version version,
Model source,
int lineNumber,
int columnNumber,
Exception exception) {
this(
message,
severity,
version,
ModelProblemUtils.toPath(source),
lineNumber,
columnNumber,
ModelProblemUtils.toId(source),
exception);
}
/**
* Creates a new problem with the specified message and exception.
*
* @param message The message describing the problem, may be {@code null}.
* @param severity The severity level of the problem, may be {@code null} to default to
* {@link Severity#ERROR}.
* @param version The version since the problem is relevant
* @param source A hint about the source of the problem like a file path, may be {@code null}.
* @param lineNumber The one-based index of the line containing the problem or {@code -1} if unknown.
* @param columnNumber The one-based index of the column containing the problem or {@code -1} if unknown.
* @param modelId The identifier of the model that exhibits the problem, may be {@code null}.
* @param exception The exception that caused this problem, may be {@code null}.
*/
// mkleint: does this need to be public?
@SuppressWarnings("checkstyle:parameternumber")
public DefaultModelProblem(
String message,
Severity severity,
Version version,
String source,
int lineNumber,
int columnNumber,
String modelId,
Exception exception) {
this.message = message;
this.severity = (severity != null) ? severity : Severity.ERROR;
this.source = (source != null) ? source : "";
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.modelId = (modelId != null) ? modelId : "";
this.exception = exception;
this.version = version;
}
@Override
public String getSource() {
return source;
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public int getColumnNumber() {
return columnNumber;
}
public String getModelId() {
return modelId;
}
@Override
public Exception getException() {
return exception;
}
@Override
public String getLocation() {
return "";
}
@Override
public String getMessage() {<FILL_FUNCTION_BODY>}
@Override
public Severity getSeverity() {
return severity;
}
public Version getVersion() {
return version;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder(128);
buffer.append('[').append(getSeverity()).append("] ");
buffer.append(getMessage());
String location = ModelProblemUtils.formatLocation(this, null);
if (!location.isEmpty()) {
buffer.append(" @ ");
buffer.append(location);
}
return buffer.toString();
}
}
|
String msg = null;
if (message != null && !message.isEmpty()) {
msg = message;
} else if (exception != null) {
msg = exception.getMessage();
}
if (msg == null) {
msg = "";
}
return msg;
| 1,085
| 79
| 1,164
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelProblemCollector.java
|
DefaultModelProblemCollector
|
newModelBuilderException
|
class DefaultModelProblemCollector implements ModelProblemCollector {
private final ModelBuilderResult result;
private List<ModelProblem> problems;
private String source;
private Model sourceModel;
private Model rootModel;
private Set<ModelProblem.Severity> severities = EnumSet.noneOf(ModelProblem.Severity.class);
DefaultModelProblemCollector(ModelBuilderResult result) {
this.result = result;
this.problems = result.getProblems();
for (ModelProblem problem : this.problems) {
severities.add(problem.getSeverity());
}
}
public boolean hasFatalErrors() {
return severities.contains(ModelProblem.Severity.FATAL);
}
public boolean hasErrors() {
return severities.contains(ModelProblem.Severity.ERROR) || severities.contains(ModelProblem.Severity.FATAL);
}
@Override
public List<ModelProblem> getProblems() {
return problems;
}
public void setSource(String source) {
this.source = source;
this.sourceModel = null;
}
public void setSource(Model source) {
this.sourceModel = source;
this.source = null;
if (rootModel == null) {
rootModel = source;
}
}
private String getSource() {
if (source == null && sourceModel != null) {
source = ModelProblemUtils.toPath(sourceModel);
}
return source;
}
private String getModelId() {
return ModelProblemUtils.toId(sourceModel);
}
public void setRootModel(Model rootModel) {
this.rootModel = rootModel;
}
public Model getRootModel() {
return rootModel;
}
public String getRootModelId() {
return ModelProblemUtils.toId(rootModel);
}
@Override
public void add(ModelProblem problem) {
problems.add(problem);
severities.add(problem.getSeverity());
}
public void addAll(Collection<ModelProblem> problems) {
this.problems.addAll(problems);
for (ModelProblem problem : problems) {
severities.add(problem.getSeverity());
}
}
@Override
public void add(BuilderProblem.Severity severity, ModelProblem.Version version, String message) {
add(severity, version, message, null, null);
}
@Override
public void add(
BuilderProblem.Severity severity, ModelProblem.Version version, String message, InputLocation location) {
add(severity, version, message, location, null);
}
@Override
public void add(
BuilderProblem.Severity severity, ModelProblem.Version version, String message, Exception exception) {
add(severity, version, message, null, exception);
}
public void add(
BuilderProblem.Severity severity,
ModelProblem.Version version,
String message,
InputLocation location,
Exception exception) {
int line = -1;
int column = -1;
String source = null;
String modelId = null;
if (location != null) {
line = location.getLineNumber();
column = location.getColumnNumber();
if (location.getSource() != null) {
modelId = location.getSource().getModelId();
source = location.getSource().getLocation();
}
}
if (modelId == null) {
modelId = getModelId();
source = getSource();
}
if (line <= 0 && column <= 0 && exception instanceof ModelParserException e) {
line = e.getLineNumber();
column = e.getColumnNumber();
}
ModelProblem problem =
new DefaultModelProblem(message, severity, version, source, line, column, modelId, exception);
add(problem);
}
public ModelBuilderException newModelBuilderException() {<FILL_FUNCTION_BODY>}
}
|
ModelBuilderResult result = this.result;
if (result.getModelIds().isEmpty()) {
DefaultModelBuilderResult tmp = new DefaultModelBuilderResult();
tmp.setEffectiveModel(result.getEffectiveModel());
tmp.setProblems(getProblems());
tmp.setActiveExternalProfiles(result.getActiveExternalProfiles());
String id = getRootModelId();
tmp.addModelId(id);
tmp.setRawModel(id, getRootModel());
result = tmp;
}
return new ModelBuilderException(result);
| 1,077
| 140
| 1,217
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelProcessor.java
|
DefaultModelProcessor
|
read
|
class DefaultModelProcessor implements ModelProcessor {
private final ModelXmlFactory modelXmlFactory;
private final List<ModelParser> modelParsers;
@Inject
public DefaultModelProcessor(ModelXmlFactory modelXmlFactory, List<ModelParser> modelParsers) {
this.modelXmlFactory = modelXmlFactory;
this.modelParsers = modelParsers;
}
@Override
public Path locateExistingPom(Path projectDirectory) {
// Note that the ModelProcessor#locatePom never returns null
// while the ModelParser#locatePom needs to return an existing path!
Path pom = modelParsers.stream()
.map(m -> m.locate(projectDirectory)
.map(org.apache.maven.api.services.Source::getPath)
.orElse(null))
.filter(Objects::nonNull)
.findFirst()
.orElseGet(() -> doLocateExistingPom(projectDirectory));
if (pom != null && !pom.equals(projectDirectory) && !pom.getParent().equals(projectDirectory)) {
throw new IllegalArgumentException("The POM found does not belong to the given directory: " + pom);
}
return pom;
}
@Override
public Model read(XmlReaderRequest request) throws IOException {<FILL_FUNCTION_BODY>}
private Path doLocateExistingPom(Path project) {
if (project == null) {
project = Paths.get(System.getProperty("user.dir"));
}
if (Files.isDirectory(project)) {
Path pom = project.resolve("pom.xml");
return Files.isRegularFile(pom) ? pom : null;
} else if (Files.isRegularFile(project)) {
return project;
} else {
return null;
}
}
private Model doRead(XmlReaderRequest request) throws IOException {
return modelXmlFactory.read(request);
}
}
|
Objects.requireNonNull(request, "source cannot be null");
Path pomFile = request.getPath();
if (pomFile != null) {
Path projectDirectory = pomFile.getParent();
List<ModelParserException> exceptions = new ArrayList<>();
for (ModelParser parser : modelParsers) {
try {
Optional<Model> model =
parser.locateAndParse(projectDirectory, Map.of(ModelParser.STRICT, request.isStrict()));
if (model.isPresent()) {
return model.get().withPomFile(pomFile);
}
} catch (ModelParserException e) {
exceptions.add(e);
}
}
try {
return doRead(request);
} catch (IOException e) {
exceptions.forEach(e::addSuppressed);
throw e;
}
} else {
return doRead(request);
}
| 507
| 237
| 744
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelTransformerContext.java
|
GAKey
|
equals
|
class GAKey {
private final String groupId;
private final String artifactId;
private final int hashCode;
GAKey(String groupId, String artifactId) {
this.groupId = groupId;
this.artifactId = artifactId;
this.hashCode = Objects.hash(groupId, artifactId);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof GAKey)) {
return false;
}
GAKey other = (GAKey) obj;
return Objects.equals(artifactId, other.artifactId) && Objects.equals(groupId, other.groupId);
| 134
| 78
| 212
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelTransformerContextBuilder.java
|
DefaultModelTransformerContextBuilder
|
initialize
|
class DefaultModelTransformerContextBuilder implements ModelTransformerContextBuilder {
private final Graph dag = new Graph();
private final DefaultModelBuilder defaultModelBuilder;
private final DefaultModelTransformerContext context;
private final Map<String, Set<ModelSource>> mappedSources = new ConcurrentHashMap<>(64);
private volatile boolean fullReactorLoaded;
DefaultModelTransformerContextBuilder(DefaultModelBuilder defaultModelBuilder) {
this.defaultModelBuilder = defaultModelBuilder;
this.context = new DefaultModelTransformerContext(defaultModelBuilder.getModelProcessor());
}
/**
* If an interface could be extracted, DefaultModelProblemCollector should be ModelProblemCollectorExt
*/
@Override
public ModelTransformerContext initialize(ModelBuilderRequest request, ModelProblemCollector collector) {<FILL_FUNCTION_BODY>}
private boolean addEdge(Path from, Path p, DefaultModelProblemCollector problems) {
try {
dag.addEdge(from.toString(), p.toString());
return true;
} catch (Graph.CycleDetectedException e) {
problems.add(new DefaultModelProblem(
"Cycle detected between models at " + from + " and " + p,
ModelProblem.Severity.FATAL,
null,
null,
0,
0,
null,
e));
return false;
}
}
@Override
public ModelTransformerContext build() {
return context;
}
public ModelSource getSource(String groupId, String artifactId) {
Set<ModelSource> sources = mappedSources.get(groupId + ":" + artifactId);
if (sources == null) {
return null;
}
return sources.stream()
.reduce((a, b) -> {
throw new IllegalStateException(String.format(
"No unique Source for %s:%s: %s and %s",
groupId, artifactId, a.getLocation(), b.getLocation()));
})
.orElse(null);
}
public void putSource(String groupId, String artifactId, ModelSource source) {
mappedSources
.computeIfAbsent(groupId + ":" + artifactId, k -> new HashSet<>())
.add(source);
}
}
|
// We must assume the TransformerContext was created using this.newTransformerContextBuilder()
DefaultModelProblemCollector problems = (DefaultModelProblemCollector) collector;
return new ModelTransformerContext() {
@Override
public Path locate(Path path) {
return context.locate(path);
}
@Override
public String getUserProperty(String key) {
return context.userProperties.computeIfAbsent(
key, k -> request.getUserProperties().get(key));
}
@Override
public Model getRawModel(Path from, String gId, String aId) {
Model model = findRawModel(from, gId, aId);
if (model != null) {
context.modelByGA.put(new GAKey(gId, aId), new Holder(model));
context.modelByPath.put(model.getPomFile(), new Holder(model));
}
return model;
}
@Override
public Model getRawModel(Path from, Path path) {
Model model = findRawModel(from, path);
if (model != null) {
String groupId = DefaultModelBuilder.getGroupId(model);
context.modelByGA.put(
new DefaultModelTransformerContext.GAKey(groupId, model.getArtifactId()),
new Holder(model));
context.modelByPath.put(path, new Holder(model));
}
return model;
}
private Model findRawModel(Path from, String groupId, String artifactId) {
ModelSource source = getSource(groupId, artifactId);
if (source == null) {
// we need to check the whole reactor in case it's a dependency
loadFullReactor();
source = getSource(groupId, artifactId);
}
if (source != null) {
if (!addEdge(from, source.getPath(), problems)) {
return null;
}
try {
ModelBuilderRequest gaBuildingRequest = ModelBuilderRequest.build(request, source);
return defaultModelBuilder.readRawModel(gaBuildingRequest, problems);
} catch (ModelBuilderException e) {
// gathered with problem collector
}
}
return null;
}
private void loadFullReactor() {
if (!fullReactorLoaded) {
synchronized (DefaultModelTransformerContextBuilder.this) {
if (!fullReactorLoaded) {
doLoadFullReactor();
fullReactorLoaded = true;
}
}
}
}
private void doLoadFullReactor() {
Path rootDirectory;
try {
rootDirectory = request.getSession().getRootDirectory();
} catch (IllegalStateException e) {
// if no root directory, bail out
return;
}
List<Path> toLoad = new ArrayList<>();
Path root = defaultModelBuilder.getModelProcessor().locateExistingPom(rootDirectory);
toLoad.add(root);
while (!toLoad.isEmpty()) {
Path pom = toLoad.remove(0);
try {
ModelBuilderRequest gaBuildingRequest =
ModelBuilderRequest.build(request, ModelSource.fromPath(pom));
Model rawModel = defaultModelBuilder.readFileModel(gaBuildingRequest, problems);
for (String module : rawModel.getModules()) {
Path moduleFile = defaultModelBuilder
.getModelProcessor()
.locateExistingPom(pom.getParent().resolve(module));
if (moduleFile != null) {
toLoad.add(moduleFile);
}
}
} catch (ModelBuilderException e) {
// gathered with problem collector
}
}
}
private Model findRawModel(Path from, Path p) {
if (!Files.isRegularFile(p)) {
throw new IllegalArgumentException("Not a regular file: " + p);
}
if (!addEdge(from, p, problems)) {
return null;
}
ModelBuilderRequest req = ModelBuilderRequest.build(request, ModelSource.fromPath(p));
try {
return defaultModelBuilder.readRawModel(req, problems);
} catch (ModelBuilderException e) {
// gathered with problem collector
}
return null;
}
};
| 581
| 1,079
| 1,660
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultModelVersionProcessor.java
|
DefaultModelVersionProcessor
|
overwriteModelProperties
|
class DefaultModelVersionProcessor implements ModelVersionProcessor {
private static final String SHA1_PROPERTY = "sha1";
private static final String CHANGELIST_PROPERTY = "changelist";
private static final String REVISION_PROPERTY = "revision";
@Override
public boolean isValidProperty(String property) {
return REVISION_PROPERTY.equals(property)
|| CHANGELIST_PROPERTY.equals(property)
|| SHA1_PROPERTY.equals(property);
}
@Override
public void overwriteModelProperties(Properties modelProperties, ModelBuilderRequest request) {<FILL_FUNCTION_BODY>}
}
|
Map<String, String> props = request.getUserProperties();
if (props.containsKey(REVISION_PROPERTY)) {
modelProperties.put(REVISION_PROPERTY, props.get(REVISION_PROPERTY));
}
if (props.containsKey(CHANGELIST_PROPERTY)) {
modelProperties.put(CHANGELIST_PROPERTY, props.get(CHANGELIST_PROPERTY));
}
if (props.containsKey(SHA1_PROPERTY)) {
modelProperties.put(SHA1_PROPERTY, props.get(SHA1_PROPERTY));
}
| 176
| 169
| 345
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultPathTranslator.java
|
DefaultPathTranslator
|
alignToBaseDirectory
|
class DefaultPathTranslator implements PathTranslator {
@Override
public String alignToBaseDirectory(String path, Path basedir) {<FILL_FUNCTION_BODY>}
}
|
String result = path;
if (path != null && basedir != null) {
path = path.replace('\\', File.separatorChar).replace('/', File.separatorChar);
File file = new File(path);
if (file.isAbsolute()) {
// path was already absolute, just normalize file separator and we're done
result = file.getPath();
} else if (file.getPath().startsWith(File.separator)) {
// drive-relative Windows path, don't align with project directory but with drive root
result = file.getAbsolutePath();
} else {
// an ordinary relative path, align with project directory
result = basedir.resolve(path).normalize().toString();
}
}
return result;
| 49
| 199
| 248
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultPluginManagementInjector.java
|
ManagementModelMerger
|
mergePluginContainerPlugins
|
class ManagementModelMerger extends MavenModelMerger {
public Model mergeManagedBuildPlugins(Model model) {
Build build = model.getBuild();
if (build != null) {
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
return model.withBuild(mergePluginContainerPlugins(build, pluginManagement));
}
}
return model;
}
private Build mergePluginContainerPlugins(Build target, PluginContainer source) {<FILL_FUNCTION_BODY>}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder,
Plugin target,
Plugin source,
boolean sourceDominant,
Map<Object, Object> context) {
List<PluginExecution> src = source.getExecutions();
if (!src.isEmpty()) {
List<PluginExecution> tgt = target.getExecutions();
Map<Object, PluginExecution> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (PluginExecution element : src) {
Object key = getPluginExecutionKey().apply(element);
merged.put(key, element);
}
for (PluginExecution element : tgt) {
Object key = getPluginExecutionKey().apply(element);
PluginExecution existing = merged.get(key);
if (existing != null) {
element = mergePluginExecution(element, existing, sourceDominant, context);
}
merged.put(key, element);
}
builder.executions(merged.values());
}
}
}
|
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
Map<Object, Plugin> managedPlugins = new LinkedHashMap<>(src.size() * 2);
Map<Object, Object> context = Collections.emptyMap();
for (Plugin element : src) {
Object key = getPluginKey().apply(element);
managedPlugins.put(key, element);
}
List<Plugin> newPlugins = new ArrayList<>();
for (Plugin element : target.getPlugins()) {
Object key = getPluginKey().apply(element);
Plugin managedPlugin = managedPlugins.get(key);
if (managedPlugin != null) {
element = mergePlugin(element, managedPlugin, false, context);
}
newPlugins.add(element);
}
return target.withPlugins(newPlugins);
}
return target;
| 418
| 240
| 658
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultProfileActivationContext.java
|
DefaultProfileActivationContext
|
toMap
|
class DefaultProfileActivationContext implements ProfileActivationContext {
private List<String> activeProfileIds = Collections.emptyList();
private List<String> inactiveProfileIds = Collections.emptyList();
private Map<String, String> systemProperties = Collections.emptyMap();
private Map<String, String> userProperties = Collections.emptyMap();
private Map<String, String> projectProperties = Collections.emptyMap();
private Path projectDirectory;
@Override
public List<String> getActiveProfileIds() {
return activeProfileIds;
}
/**
* Sets the identifiers of those profiles that should be activated by explicit demand.
*
* @param activeProfileIds The identifiers of those profiles to activate, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setActiveProfileIds(List<String> activeProfileIds) {
this.activeProfileIds = unmodifiable(activeProfileIds);
return this;
}
@Override
public List<String> getInactiveProfileIds() {
return inactiveProfileIds;
}
/**
* Sets the identifiers of those profiles that should be deactivated by explicit demand.
*
* @param inactiveProfileIds The identifiers of those profiles to deactivate, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setInactiveProfileIds(List<String> inactiveProfileIds) {
this.inactiveProfileIds = unmodifiable(inactiveProfileIds);
return this;
}
@Override
public Map<String, String> getSystemProperties() {
return systemProperties;
}
/**
* Sets the system properties to use for interpolation and profile activation. The system properties are collected
* from the runtime environment like {@link System#getProperties()} and environment variables.
*
* @param systemProperties The system properties, may be {@code null}.
* @return This context, never {@code null}.
*/
@SuppressWarnings("unchecked")
public DefaultProfileActivationContext setSystemProperties(Properties systemProperties) {
return setSystemProperties(toMap(systemProperties));
}
/**
* Sets the system properties to use for interpolation and profile activation. The system properties are collected
* from the runtime environment like {@link System#getProperties()} and environment variables.
*
* @param systemProperties The system properties, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setSystemProperties(Map<String, String> systemProperties) {
this.systemProperties = unmodifiable(systemProperties);
return this;
}
@Override
public Map<String, String> getUserProperties() {
return userProperties;
}
/**
* Sets the user properties to use for interpolation and profile activation. The user properties have been
* configured directly by the user on his discretion, e.g. via the {@code -Dkey=value} parameter on the command
* line.
*
* @param userProperties The user properties, may be {@code null}.
* @return This context, never {@code null}.
*/
@SuppressWarnings("unchecked")
public DefaultProfileActivationContext setUserProperties(Properties userProperties) {
return setUserProperties(toMap(userProperties));
}
/**
* Sets the user properties to use for interpolation and profile activation. The user properties have been
* configured directly by the user on his discretion, e.g. via the {@code -Dkey=value} parameter on the command
* line.
*
* @param userProperties The user properties, may be {@code null}.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setUserProperties(Map<String, String> userProperties) {
this.userProperties = unmodifiable(userProperties);
return this;
}
@Override
public Path getProjectDirectory() {
return projectDirectory;
}
/**
* Sets the base directory of the current project.
*
* @param projectDirectory The base directory of the current project, may be {@code null} if profile activation
* happens in the context of metadata retrieval rather than project building.
* @return This context, never {@code null}.
*/
public DefaultProfileActivationContext setProjectDirectory(Path projectDirectory) {
this.projectDirectory = projectDirectory;
return this;
}
@Override
public Map<String, String> getProjectProperties() {
return projectProperties;
}
public DefaultProfileActivationContext setProjectProperties(Properties projectProperties) {
return setProjectProperties(toMap(projectProperties));
}
public DefaultProfileActivationContext setProjectProperties(Map<String, String> projectProperties) {
this.projectProperties = unmodifiable(projectProperties);
return this;
}
private static List<String> unmodifiable(List<String> list) {
return list != null ? Collections.unmodifiableList(list) : Collections.emptyList();
}
private static Map<String, String> unmodifiable(Map<String, String> map) {
return map != null ? Collections.unmodifiableMap(map) : Collections.emptyMap();
}
private static Map<String, String> toMap(Properties properties) {<FILL_FUNCTION_BODY>}
}
|
if (properties != null && !properties.isEmpty()) {
return properties.entrySet().stream()
.collect(Collectors.toMap(e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue())));
} else {
return null;
}
| 1,365
| 79
| 1,444
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultProfileInjector.java
|
ProfileModelMerger
|
mergePlugin_Executions
|
class ProfileModelMerger extends MavenModelMerger {
public void mergeModelBase(ModelBase.Builder builder, ModelBase target, ModelBase source) {
mergeModelBase(builder, target, source, true, Collections.emptyMap());
}
public void mergeBuildBase(BuildBase.Builder builder, BuildBase target, BuildBase source) {
mergeBuildBase(builder, target, source, true, Collections.emptyMap());
}
@Override
protected void mergePluginContainer_Plugins(
PluginContainer.Builder builder,
PluginContainer target,
PluginContainer source,
boolean sourceDominant,
Map<Object, Object> context) {
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
List<Plugin> tgt = target.getPlugins();
Map<Object, Plugin> master = new LinkedHashMap<>(tgt.size() * 2);
for (Plugin element : tgt) {
Object key = getPluginKey().apply(element);
master.put(key, element);
}
Map<Object, List<Plugin>> predecessors = new LinkedHashMap<>();
List<Plugin> pending = new ArrayList<>();
for (Plugin element : src) {
Object key = getPluginKey().apply(element);
Plugin existing = master.get(key);
if (existing != null) {
existing = mergePlugin(existing, element, sourceDominant, context);
master.put(key, existing);
if (!pending.isEmpty()) {
predecessors.put(key, pending);
pending = new ArrayList<>();
}
} else {
pending.add(element);
}
}
List<Plugin> result = new ArrayList<>(src.size() + tgt.size());
for (Map.Entry<Object, Plugin> entry : master.entrySet()) {
List<Plugin> pre = predecessors.get(entry.getKey());
if (pre != null) {
result.addAll(pre);
}
result.add(entry.getValue());
}
result.addAll(pending);
builder.plugins(result);
}
}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder,
Plugin target,
Plugin source,
boolean sourceDominant,
Map<Object, Object> context) {<FILL_FUNCTION_BODY>}
@Override
protected void mergeReporting_Plugins(
Reporting.Builder builder,
Reporting target,
Reporting source,
boolean sourceDominant,
Map<Object, Object> context) {
List<ReportPlugin> src = source.getPlugins();
if (!src.isEmpty()) {
List<ReportPlugin> tgt = target.getPlugins();
Map<Object, ReportPlugin> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (ReportPlugin element : tgt) {
Object key = getReportPluginKey().apply(element);
merged.put(key, element);
}
for (ReportPlugin element : src) {
Object key = getReportPluginKey().apply(element);
ReportPlugin existing = merged.get(key);
if (existing != null) {
element = mergeReportPlugin(existing, element, sourceDominant, context);
}
merged.put(key, element);
}
builder.plugins(merged.values());
}
}
@Override
protected void mergeReportPlugin_ReportSets(
ReportPlugin.Builder builder,
ReportPlugin target,
ReportPlugin source,
boolean sourceDominant,
Map<Object, Object> context) {
List<ReportSet> src = source.getReportSets();
if (!src.isEmpty()) {
List<ReportSet> tgt = target.getReportSets();
Map<Object, ReportSet> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (ReportSet element : tgt) {
Object key = getReportSetKey().apply(element);
merged.put(key, element);
}
for (ReportSet element : src) {
Object key = getReportSetKey().apply(element);
ReportSet existing = merged.get(key);
if (existing != null) {
element = mergeReportSet(existing, element, sourceDominant, context);
}
merged.put(key, element);
}
builder.reportSets(merged.values());
}
}
}
|
List<PluginExecution> src = source.getExecutions();
if (!src.isEmpty()) {
List<PluginExecution> tgt = target.getExecutions();
Map<Object, PluginExecution> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (PluginExecution element : tgt) {
Object key = getPluginExecutionKey().apply(element);
merged.put(key, element);
}
for (PluginExecution element : src) {
Object key = getPluginExecutionKey().apply(element);
PluginExecution existing = merged.get(key);
if (existing != null) {
element = mergePluginExecution(existing, element, sourceDominant, context);
}
merged.put(key, element);
}
builder.executions(merged.values());
}
| 1,165
| 217
| 1,382
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultProfileSelector.java
|
DefaultProfileSelector
|
getActiveProfiles
|
class DefaultProfileSelector implements ProfileSelector {
private final List<ProfileActivator> activators;
public DefaultProfileSelector() {
this.activators = new ArrayList<>();
}
@Inject
public DefaultProfileSelector(List<ProfileActivator> activators) {
this.activators = new ArrayList<>(activators);
}
public DefaultProfileSelector addProfileActivator(ProfileActivator profileActivator) {
if (profileActivator != null) {
activators.add(profileActivator);
}
return this;
}
@Override
public List<Profile> getActiveProfiles(
Collection<Profile> profiles, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
private boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
boolean isActive = false;
for (ProfileActivator activator : activators) {
if (activator.presentInConfig(profile, context, problems)) {
isActive = true;
try {
if (!activator.isActive(profile, context, problems)) {
return false;
}
} catch (RuntimeException e) {
problems.add(
Severity.ERROR,
Version.BASE,
"Failed to determine activation for profile " + profile.getId(),
profile.getLocation(""),
e);
return false;
}
}
}
return isActive;
}
private boolean isActiveByDefault(Profile profile) {
Activation activation = profile.getActivation();
return activation != null && activation.isActiveByDefault();
}
}
|
Collection<String> activatedIds = new HashSet<>(context.getActiveProfileIds());
Collection<String> deactivatedIds = new HashSet<>(context.getInactiveProfileIds());
List<Profile> activeProfiles = new ArrayList<>(profiles.size());
List<Profile> activePomProfilesByDefault = new ArrayList<>();
boolean activatedPomProfileNotByDefault = false;
for (Profile profile : profiles) {
if (!deactivatedIds.contains(profile.getId())) {
if (activatedIds.contains(profile.getId()) || isActive(profile, context, problems)) {
activeProfiles.add(profile);
if (Profile.SOURCE_POM.equals(profile.getSource())) {
activatedPomProfileNotByDefault = true;
}
} else if (isActiveByDefault(profile)) {
if (Profile.SOURCE_POM.equals(profile.getSource())) {
activePomProfilesByDefault.add(profile);
} else {
activeProfiles.add(profile);
}
}
}
}
if (!activatedPomProfileNotByDefault) {
activeProfiles.addAll(activePomProfilesByDefault);
}
return activeProfiles;
| 418
| 314
| 732
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/DefaultRootLocator.java
|
DefaultRootLocator
|
isRootDirectory
|
class DefaultRootLocator implements RootLocator {
public boolean isRootDirectory(Path dir) {<FILL_FUNCTION_BODY>}
}
|
if (Files.isDirectory(dir.resolve(".mvn"))) {
return true;
}
// we're too early to use the modelProcessor ...
Path pom = dir.resolve("pom.xml");
try (InputStream is = Files.newInputStream(pom)) {
XMLStreamReader parser = new WstxInputFactory().createXMLStreamReader(is);
if (parser.nextTag() == XMLStreamReader.START_ELEMENT
&& parser.getLocalName().equals("project")) {
for (int i = 0; i < parser.getAttributeCount(); i++) {
if ("root".equals(parser.getAttributeLocalName(i))) {
return Boolean.parseBoolean(parser.getAttributeValue(i));
}
}
}
} catch (IOException | XMLStreamException e) {
// The root locator can be used very early during the setup of Maven,
// even before the arguments from the command line are parsed. Any exception
// that would happen here should cause the build to fail at a later stage
// (when actually parsing the POM) and will lead to a better exception being
// displayed to the user, so just bail out and return false.
}
return false;
| 38
| 302
| 340
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/FileToRawModelMerger.java
|
FileToRawModelMerger
|
mergeDependencyManagement_Dependencies
|
class FileToRawModelMerger extends MavenMerger {
@Override
protected void mergeBuild_Extensions(
Build.Builder builder, Build target, Build source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeBuildBase_Resources(
BuildBase.Builder builder,
BuildBase target,
BuildBase source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeBuildBase_TestResources(
BuildBase.Builder builder,
BuildBase target,
BuildBase source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeCiManagement_Notifiers(
CiManagement.Builder builder,
CiManagement target,
CiManagement source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeDependencyManagement_Dependencies(
DependencyManagement.Builder builder,
DependencyManagement target,
DependencyManagement source,
boolean sourceDominant,
Map<Object, Object> context) {<FILL_FUNCTION_BODY>}
@Override
protected void mergeDependency_Exclusions(
Dependency.Builder builder,
Dependency target,
Dependency source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Contributors(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Developers(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Licenses(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_MailingLists(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeModel_Profiles(
Model.Builder builder, Model target, Model source, boolean sourceDominant, Map<Object, Object> context) {
Iterator<Profile> sourceIterator = source.getProfiles().iterator();
builder.profiles(target.getProfiles().stream()
.map(d -> mergeProfile(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
}
@Override
protected void mergeModelBase_Dependencies(
ModelBase.Builder builder,
ModelBase target,
ModelBase source,
boolean sourceDominant,
Map<Object, Object> context) {
Iterator<Dependency> sourceIterator = source.getDependencies().iterator();
builder.dependencies(target.getDependencies().stream()
.map(d -> mergeDependency(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
}
@Override
protected void mergeModelBase_PluginRepositories(
ModelBase.Builder builder,
ModelBase target,
ModelBase source,
boolean sourceDominant,
Map<Object, Object> context) {
builder.pluginRepositories(source.getPluginRepositories());
}
@Override
protected void mergeModelBase_Repositories(
ModelBase.Builder builder,
ModelBase target,
ModelBase source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergePlugin_Dependencies(
Plugin.Builder builder, Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context) {
Iterator<Dependency> sourceIterator = source.getDependencies().iterator();
builder.dependencies(target.getDependencies().stream()
.map(d -> mergeDependency(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
}
@Override
protected void mergePlugin_Executions(
Plugin.Builder builder, Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeReporting_Plugins(
Reporting.Builder builder,
Reporting target,
Reporting source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergeReportPlugin_ReportSets(
ReportPlugin.Builder builder,
ReportPlugin target,
ReportPlugin source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
@Override
protected void mergePluginContainer_Plugins(
PluginContainer.Builder builder,
PluginContainer target,
PluginContainer source,
boolean sourceDominant,
Map<Object, Object> context) {
// don't merge
}
}
|
Iterator<Dependency> sourceIterator = source.getDependencies().iterator();
builder.dependencies(target.getDependencies().stream()
.map(d -> mergeDependency(d, sourceIterator.next(), sourceDominant, context))
.collect(Collectors.toList()));
| 1,385
| 72
| 1,457
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/Graph.java
|
Graph
|
addEdge
|
class Graph {
final Map<String, Set<String>> graph = new LinkedHashMap<>();
synchronized void addEdge(String from, String to) throws CycleDetectedException {<FILL_FUNCTION_BODY>}
private enum DfsState {
VISITING,
VISITED
}
private static List<String> visitCycle(
Map<String, Set<String>> graph,
Collection<String> children,
Map<String, DfsState> stateMap,
LinkedList<String> cycle) {
if (children != null) {
for (String v : children) {
DfsState state = stateMap.putIfAbsent(v, DfsState.VISITING);
if (state == null) {
cycle.addLast(v);
List<String> ret = visitCycle(graph, graph.get(v), stateMap, cycle);
if (ret != null) {
return ret;
}
cycle.removeLast();
stateMap.put(v, DfsState.VISITED);
} else if (state == DfsState.VISITING) {
// we are already visiting this vertex, this mean we have a cycle
int pos = cycle.lastIndexOf(v);
List<String> ret = cycle.subList(pos, cycle.size());
ret.add(v);
return ret;
}
}
}
return null;
}
public static class CycleDetectedException extends Exception {
private final List<String> cycle;
CycleDetectedException(String message, List<String> cycle) {
super(message);
this.cycle = cycle;
}
public List<String> getCycle() {
return cycle;
}
@Override
public String getMessage() {
return super.getMessage() + " " + String.join(" --> ", cycle);
}
}
}
|
if (graph.computeIfAbsent(from, l -> new HashSet<>()).add(to)) {
List<String> cycle = visitCycle(graph, Collections.singleton(to), new HashMap<>(), new LinkedList<>());
if (cycle != null) {
// remove edge which introduced cycle
throw new CycleDetectedException(
"Edge between '" + from + "' and '" + to + "' introduces to cycle in the graph", cycle);
}
}
| 489
| 120
| 609
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/ModelProblemUtils.java
|
ModelProblemUtils
|
toPath
|
class ModelProblemUtils {
/**
* Creates a user-friendly source hint for the specified model.
*
* @param model The model to create a source hint for, may be {@code null}.
* @return The user-friendly source hint, never {@code null}.
*/
static String toSourceHint(Model model) {
if (model == null) {
return "";
}
StringBuilder buffer = new StringBuilder(128);
buffer.append(toId(model));
Path pomPath = model.getPomFile();
if (pomPath != null) {
buffer.append(" (").append(pomPath).append(')');
}
return buffer.toString();
}
static String toPath(Model model) {<FILL_FUNCTION_BODY>}
static String toId(Model model) {
if (model == null) {
return "";
}
String groupId = model.getGroupId();
if (groupId == null && model.getParent() != null) {
groupId = model.getParent().getGroupId();
}
String artifactId = model.getArtifactId();
String version = model.getVersion();
if (version == null && model.getParent() != null) {
version = model.getParent().getVersion();
}
return toId(groupId, artifactId, version);
}
/**
* Creates a user-friendly artifact id from the specified coordinates.
*
* @param groupId The group id, may be {@code null}.
* @param artifactId The artifact id, may be {@code null}.
* @param version The version, may be {@code null}.
* @return The user-friendly artifact id, never {@code null}.
*/
static String toId(String groupId, String artifactId, String version) {
return ((groupId != null && !groupId.isEmpty()) ? groupId : "[unknown-group-id]")
+ ':'
+ ((artifactId != null && !artifactId.isEmpty()) ? artifactId : "[unknown-artifact-id]")
+ ':'
+ ((version != null && !version.isEmpty()) ? version : "[unknown-version]");
}
/**
* Creates a string with all location details for the specified model problem. If the project identifier is
* provided, the generated location will omit the model id and source information and only give line/column
* information for problems originating directly from this POM.
*
* @param problem The problem whose location should be formatted, must not be {@code null}.
* @param projectId The {@code <groupId>:<artifactId>:<version>} of the corresponding project, may be {@code null}
* to force output of model id and source.
* @return The formatted problem location or an empty string if unknown, never {@code null}.
*/
public static String formatLocation(ModelProblem problem, String projectId) {
StringBuilder buffer = new StringBuilder(256);
if (!problem.getModelId().equals(projectId)) {
buffer.append(problem.getModelId());
if (!problem.getSource().isEmpty()) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append(problem.getSource());
}
}
if (problem.getLineNumber() > 0) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append("line ").append(problem.getLineNumber());
}
if (problem.getColumnNumber() > 0) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append("column ").append(problem.getColumnNumber());
}
return buffer.toString();
}
}
|
String path = "";
if (model != null) {
Path pomPath = model.getPomFile();
if (pomPath != null) {
path = pomPath.toAbsolutePath().toString();
}
}
return path;
| 941
| 71
| 1,012
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/ProfileActivationFilePathInterpolator.java
|
ProfileActivationFilePathInterpolator
|
interpolate
|
class ProfileActivationFilePathInterpolator {
private final PathTranslator pathTranslator;
private final RootLocator rootLocator;
@Inject
public ProfileActivationFilePathInterpolator(PathTranslator pathTranslator, RootLocator rootLocator) {
this.pathTranslator = pathTranslator;
this.rootLocator = rootLocator;
}
/**
* Interpolates given {@code path}.
*
* @return absolute path or {@code null} if the input was {@code null}
*/
public String interpolate(String path, ProfileActivationContext context) throws InterpolationException {<FILL_FUNCTION_BODY>}
}
|
if (path == null) {
return null;
}
RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
Path basedir = context.getProjectDirectory();
if (basedir != null) {
interpolator.addValueSource(new AbstractValueSource(false) {
@Override
public Object getValue(String expression) {
if ("basedir".equals(expression) || "project.basedir".equals(expression)) {
return basedir.toAbsolutePath().toString();
}
return null;
}
});
} else if (path.contains("${basedir}")) {
return null;
}
interpolator.addValueSource(new AbstractValueSource(false) {
@Override
public Object getValue(String expression) {
if ("rootDirectory".equals(expression)) {
Path root = rootLocator.findMandatoryRoot(basedir);
return root.toFile().getAbsolutePath();
}
return null;
}
});
interpolator.addValueSource(new MapBasedValueSource(context.getProjectProperties()));
interpolator.addValueSource(new MapBasedValueSource(context.getUserProperties()));
interpolator.addValueSource(new MapBasedValueSource(context.getSystemProperties()));
String absolutePath = interpolator.interpolate(path, "");
return pathTranslator.alignToBaseDirectory(absolutePath, basedir);
| 178
| 365
| 543
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/Result.java
|
Result
|
addProblems
|
class Result<T> {
/**
* Success without warnings
*
* @param model
*/
public static <T> Result<T> success(T model) {
return success(model, Collections.emptyList());
}
/**
* Success with warnings
*
* @param model
* @param problems
*/
public static <T> Result<T> success(T model, Iterable<? extends ModelProblem> problems) {
assert !hasErrors(problems);
return new Result<>(false, model, problems);
}
/**
* Success with warnings
*
* @param model
* @param results
*/
public static <T> Result<T> success(T model, Result<?>... results) {
final List<ModelProblem> problemsList = new ArrayList<>();
for (Result<?> result1 : results) {
for (ModelProblem modelProblem : result1.getProblems()) {
problemsList.add(modelProblem);
}
}
return success(model, problemsList);
}
/**
* Error with problems describing the cause
*
* @param problems
*/
public static <T> Result<T> error(Iterable<? extends ModelProblem> problems) {
return error(null, problems);
}
public static <T> Result<T> error(T model) {
return error(model, Collections.emptyList());
}
public static <T> Result<T> error(Result<?> result) {
return error(result.getProblems());
}
public static <T> Result<T> error(Result<?>... results) {
final List<ModelProblem> problemsList = new ArrayList<>();
for (Result<?> result1 : results) {
for (ModelProblem modelProblem : result1.getProblems()) {
problemsList.add(modelProblem);
}
}
return error(problemsList);
}
/**
* Error with partial result and problems describing the cause
*
* @param model
* @param problems
*/
public static <T> Result<T> error(T model, Iterable<? extends ModelProblem> problems) {
return new Result<>(true, model, problems);
}
/**
* New result - determine whether error or success by checking problems for errors
*
* @param model
* @param problems
*/
public static <T> Result<T> newResult(T model, Iterable<? extends ModelProblem> problems) {
return new Result<>(hasErrors(problems), model, problems);
}
/**
* New result consisting of given result and new problem. Convenience for newResult(result.get(),
* concat(result.getProblems(),problems)).
*
* @param result
* @param problem
*/
public static <T> Result<T> addProblem(Result<T> result, ModelProblem problem) {
return addProblems(result, Collections.singleton(problem));
}
/**
* New result that includes the given
*
* @param result
* @param problems
*/
public static <T> Result<T> addProblems(Result<T> result, Iterable<? extends ModelProblem> problems) {
Collection<ModelProblem> list = new ArrayList<>();
for (ModelProblem item : problems) {
list.add(item);
}
for (ModelProblem item : result.getProblems()) {
list.add(item);
}
return new Result<>(result.hasErrors() || hasErrors(problems), result.get(), list);
}
public static <T> Result<T> addProblems(Result<T> result, Result<?>... results) {<FILL_FUNCTION_BODY>}
/**
* Turns the given results into a single result by combining problems and models into single collection.
*
* @param results
*/
public static <T> Result<Iterable<T>> newResultSet(Iterable<? extends Result<? extends T>> results) {
boolean hasErrors = false;
List<T> modelsList = new ArrayList<>();
List<ModelProblem> problemsList = new ArrayList<>();
for (Result<? extends T> result : results) {
modelsList.add(result.get());
for (ModelProblem modelProblem : result.getProblems()) {
problemsList.add(modelProblem);
}
if (result.hasErrors()) {
hasErrors = true;
}
}
return new Result<>(hasErrors, (Iterable<T>) modelsList, problemsList);
}
// helper to determine if problems contain error
private static boolean hasErrors(Iterable<? extends ModelProblem> problems) {
for (ModelProblem input : problems) {
if (input.getSeverity().equals(Severity.ERROR)
|| input.getSeverity().equals(Severity.FATAL)) {
return true;
}
}
return false;
}
/**
* Class definition
*/
private final boolean errors;
private final T value;
private final Iterable<? extends ModelProblem> problems;
private Result(boolean errors, T model, Iterable<? extends ModelProblem> problems) {
this.errors = errors;
this.value = model;
this.problems = problems;
}
public Iterable<? extends ModelProblem> getProblems() {
return problems;
}
public T get() {
return value;
}
public boolean hasErrors() {
return errors;
}
}
|
final List<ModelProblem> problemsList = new ArrayList<>();
for (Result<?> result1 : results) {
for (ModelProblem modelProblem : result1.getProblems()) {
problemsList.add(modelProblem);
}
}
return addProblems(result, problemsList);
| 1,454
| 82
| 1,536
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/profile/FileProfileActivator.java
|
FileProfileActivator
|
isActive
|
class FileProfileActivator implements ProfileActivator {
private final ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator;
@Inject
public FileProfileActivator(ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator) {
this.profileActivationFilePathInterpolator = profileActivationFilePathInterpolator;
}
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationFile file = activation.getFile();
return file != null;
}
}
|
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationFile file = activation.getFile();
if (file == null) {
return false;
}
String path;
boolean missing;
if (file.getExists() != null && !file.getExists().isEmpty()) {
path = file.getExists();
missing = false;
} else if (file.getMissing() != null && !file.getMissing().isEmpty()) {
path = file.getMissing();
missing = true;
} else {
return false;
}
try {
path = profileActivationFilePathInterpolator.interpolate(path, context);
} catch (InterpolationException e) {
problems.add(
BuilderProblem.Severity.ERROR,
ModelProblem.Version.BASE,
"Failed to interpolate file location " + path + " for profile " + profile.getId() + ": "
+ e.getMessage(),
file.getLocation(missing ? "missing" : "exists"),
e);
return false;
}
if (path == null) {
return false;
}
File f = new File(path);
if (!f.isAbsolute()) {
return false;
}
boolean fileExists = f.exists();
return missing != fileExists;
| 219
| 365
| 584
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/profile/JdkVersionProfileActivator.java
|
JdkVersionProfileActivator
|
getRange
|
class JdkVersionProfileActivator implements ProfileActivator {
private static final Pattern FILTER_1 = Pattern.compile("[^\\d._-]");
private static final Pattern FILTER_2 = Pattern.compile("[._-]");
private static final Pattern FILTER_3 = Pattern.compile("\\."); // used for split now
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
String jdk = activation.getJdk();
if (jdk == null) {
return false;
}
String version = context.getSystemProperties().get("java.version");
if (version == null || version.isEmpty()) {
problems.add(
BuilderProblem.Severity.ERROR,
ModelProblem.Version.BASE,
"Failed to determine Java version for profile " + profile.getId(),
activation.getLocation("jdk"));
return false;
}
return isJavaVersionCompatible(jdk, version);
}
public static boolean isJavaVersionCompatible(String requiredJdkRange, String currentJavaVersion) {
if (requiredJdkRange.startsWith("!")) {
return !currentJavaVersion.startsWith(requiredJdkRange.substring(1));
} else if (isRange(requiredJdkRange)) {
return isInRange(currentJavaVersion, getRange(requiredJdkRange));
} else {
return currentJavaVersion.startsWith(requiredJdkRange);
}
}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
String jdk = activation.getJdk();
return jdk != null;
}
private static boolean isInRange(String value, List<RangeValue> range) {
int leftRelation = getRelationOrder(value, range.get(0), true);
if (leftRelation == 0) {
return true;
}
if (leftRelation < 0) {
return false;
}
return getRelationOrder(value, range.get(1), false) <= 0;
}
private static int getRelationOrder(String value, RangeValue rangeValue, boolean isLeft) {
if (rangeValue.value.isEmpty()) {
return isLeft ? 1 : -1;
}
value = FILTER_1.matcher(value).replaceAll("");
List<String> valueTokens = new ArrayList<>(Arrays.asList(FILTER_2.split(value)));
List<String> rangeValueTokens = new ArrayList<>(Arrays.asList(FILTER_3.split(rangeValue.value)));
addZeroTokens(valueTokens, 3);
addZeroTokens(rangeValueTokens, 3);
for (int i = 0; i < 3; i++) {
int x = Integer.parseInt(valueTokens.get(i));
int y = Integer.parseInt(rangeValueTokens.get(i));
if (x < y) {
return -1;
} else if (x > y) {
return 1;
}
}
if (!rangeValue.closed) {
return isLeft ? -1 : 1;
}
return 0;
}
private static void addZeroTokens(List<String> tokens, int max) {
while (tokens.size() < max) {
tokens.add("0");
}
}
private static boolean isRange(String value) {
return value.startsWith("[") || value.startsWith("(");
}
private static List<RangeValue> getRange(String range) {<FILL_FUNCTION_BODY>}
private static class RangeValue {
private String value;
private boolean closed;
RangeValue(String value, boolean closed) {
this.value = value.trim();
this.closed = closed;
}
@Override
public String toString() {
return value;
}
}
}
|
List<RangeValue> ranges = new ArrayList<>();
for (String token : range.split(",")) {
if (token.startsWith("[")) {
ranges.add(new RangeValue(token.replace("[", ""), true));
} else if (token.startsWith("(")) {
ranges.add(new RangeValue(token.replace("(", ""), false));
} else if (token.endsWith("]")) {
ranges.add(new RangeValue(token.replace("]", ""), true));
} else if (token.endsWith(")")) {
ranges.add(new RangeValue(token.replace(")", ""), false));
} else if (token.isEmpty()) {
ranges.add(new RangeValue("", false));
}
}
if (ranges.size() < 2) {
ranges.add(new RangeValue("99999999", false));
}
return ranges;
| 1,094
| 238
| 1,332
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/profile/OperatingSystemProfileActivator.java
|
OperatingSystemProfileActivator
|
isActive
|
class OperatingSystemProfileActivator implements ProfileActivator {
private static final String REGEX_PREFIX = "regex:";
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationOS os = activation.getOs();
return os != null;
}
private boolean ensureAtLeastOneNonNull(ActivationOS os) {
return os.getArch() != null || os.getFamily() != null || os.getName() != null || os.getVersion() != null;
}
private boolean determineVersionMatch(String expectedVersion, String actualVersion) {
String test = expectedVersion;
boolean reverse = false;
final boolean result;
if (test.startsWith(REGEX_PREFIX)) {
result = actualVersion.matches(test.substring(REGEX_PREFIX.length()));
} else {
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
result = actualVersion.equals(test);
}
return reverse != result;
}
private boolean determineArchMatch(String expectedArch, String actualArch) {
String test = expectedArch;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = actualArch.equals(test);
return reverse != result;
}
private boolean determineNameMatch(String expectedName, String actualName) {
String test = expectedName;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = actualName.equals(test);
return reverse != result;
}
private boolean determineFamilyMatch(String family, String actualName) {
String test = family;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = Os.isFamily(test, actualName);
return reverse != result;
}
}
|
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationOS os = activation.getOs();
if (os == null) {
return false;
}
boolean active = ensureAtLeastOneNonNull(os);
String actualOsName = context.getSystemProperties().get("os.name").toLowerCase(Locale.ENGLISH);
String actualOsArch = context.getSystemProperties().get("os.arch").toLowerCase(Locale.ENGLISH);
String actualOsVersion = context.getSystemProperties().get("os.version").toLowerCase(Locale.ENGLISH);
if (active && os.getFamily() != null) {
active = determineFamilyMatch(os.getFamily(), actualOsName);
}
if (active && os.getName() != null) {
active = determineNameMatch(os.getName(), actualOsName);
}
if (active && os.getArch() != null) {
active = determineArchMatch(os.getArch(), actualOsArch);
}
if (active && os.getVersion() != null) {
active = determineVersionMatch(os.getVersion(), actualOsVersion);
}
return active;
| 640
| 321
| 961
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/profile/Os.java
|
Os
|
isFamily
|
class Os {
/**
* The OS Name.
*/
public static final String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
/**
* The OA architecture.
*/
public static final String OS_ARCH = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH);
/**
* The OS version.
*/
public static final String OS_VERSION = System.getProperty("os.version").toLowerCase(Locale.ENGLISH);
/**
* OS Family
*/
public static final String OS_FAMILY;
/**
* Boolean indicating if the running OS is a Windows system.
*/
public static final boolean IS_WINDOWS;
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_WINDOWS = "windows";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_WIN9X = "win9x";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_NT = "winnt";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OS2 = "os/2";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_NETWARE = "netware";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_DOS = "dos";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_MAC = "mac";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_TANDEM = "tandem";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_UNIX = "unix";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OPENVMS = "openvms";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_ZOS = "z/os";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OS390 = "os/390";
/**
* OS family that can be tested for. {@value}
*/
private static final String FAMILY_OS400 = "os/400";
/**
* OpenJDK is reported to call MacOS X "Darwin"
*
* @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=44889">bugzilla issue</a>
* @see <a href="https://issues.apache.org/jira/browse/HADOOP-3318">HADOOP-3318</a>
*/
private static final String DARWIN = "darwin";
/**
* The path separator.
*/
private static final String PATH_SEP = System.getProperty("path.separator");
static {
// Those two public constants are initialized here, as they need all the private constants
// above to be initialized first, but the code style imposes the public constants to be
// defined above the private ones...
OS_FAMILY = getOsFamily();
IS_WINDOWS = isFamily(FAMILY_WINDOWS);
}
private Os() {}
/**
* Determines if the OS on which Maven is executing matches the
* given OS family.
*
* @param family the family to check for
* @return true if the OS matches
*
*/
public static boolean isFamily(String family) {
return isFamily(family, OS_NAME);
}
/**
* Determines if the OS on which Maven is executing matches the
* given OS family derived from the given OS name
*
* @param family the family to check for
* @param actualOsName the OS name to check against
* @return true if the OS matches
*
*/
public static boolean isFamily(String family, String actualOsName) {<FILL_FUNCTION_BODY>}
/**
* Helper method to determine the current OS family.
*
* @return name of current OS family.
*/
private static String getOsFamily() {
return Stream.of(
FAMILY_DOS,
FAMILY_MAC,
FAMILY_NETWARE,
FAMILY_NT,
FAMILY_OPENVMS,
FAMILY_OS2,
FAMILY_OS400,
FAMILY_TANDEM,
FAMILY_UNIX,
FAMILY_WIN9X,
FAMILY_WINDOWS,
FAMILY_ZOS)
.filter(Os::isFamily)
.findFirst()
.orElse(null);
}
}
|
// windows probing logic relies on the word 'windows' in the OS
boolean isWindows = actualOsName.contains(FAMILY_WINDOWS);
boolean is9x = false;
boolean isNT = false;
if (isWindows) {
// there are only four 9x platforms that we look for
is9x = (actualOsName.contains("95")
|| actualOsName.contains("98")
|| actualOsName.contains("me")
// wince isn't really 9x, but crippled enough to
// be a muchness. Maven doesnt run on CE, anyway.
|| actualOsName.contains("ce"));
isNT = !is9x;
}
switch (family) {
case FAMILY_WINDOWS:
return isWindows;
case FAMILY_WIN9X:
return isWindows && is9x;
case FAMILY_NT:
return isWindows && isNT;
case FAMILY_OS2:
return actualOsName.contains(FAMILY_OS2);
case FAMILY_NETWARE:
return actualOsName.contains(FAMILY_NETWARE);
case FAMILY_DOS:
return PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE, actualOsName) && !isWindows;
case FAMILY_MAC:
return actualOsName.contains(FAMILY_MAC) || actualOsName.contains(DARWIN);
case FAMILY_TANDEM:
return actualOsName.contains("nonstop_kernel");
case FAMILY_UNIX:
return PATH_SEP.equals(":")
&& !isFamily(FAMILY_OPENVMS, actualOsName)
&& (!isFamily(FAMILY_MAC, actualOsName) || actualOsName.endsWith("x"));
case FAMILY_ZOS:
return actualOsName.contains(FAMILY_ZOS) || actualOsName.contains(FAMILY_OS390);
case FAMILY_OS400:
return actualOsName.contains(FAMILY_OS400);
case FAMILY_OPENVMS:
return actualOsName.contains(FAMILY_OPENVMS);
default:
return actualOsName.contains(family.toLowerCase(Locale.US));
}
| 1,384
| 622
| 2,006
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/model/profile/PropertyProfileActivator.java
|
PropertyProfileActivator
|
isActive
|
class PropertyProfileActivator implements ProfileActivator {
@Override
public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {<FILL_FUNCTION_BODY>}
@Override
public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) {
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationProperty property = activation.getProperty();
return property != null;
}
}
|
Activation activation = profile.getActivation();
if (activation == null) {
return false;
}
ActivationProperty property = activation.getProperty();
if (property == null) {
return false;
}
String name = property.getName();
boolean reverseName = false;
if (name != null && name.startsWith("!")) {
reverseName = true;
name = name.substring(1);
}
if (name == null || name.isEmpty()) {
problems.add(
BuilderProblem.Severity.ERROR,
ModelProblem.Version.BASE,
"The property name is required to activate the profile " + profile.getId(),
property.getLocation(""));
return false;
}
String sysValue = context.getUserProperties().get(name);
if (sysValue == null) {
sysValue = context.getSystemProperties().get(name);
}
String propValue = property.getValue();
if (propValue != null && !propValue.isEmpty()) {
boolean reverseValue = false;
if (propValue.startsWith("!")) {
reverseValue = true;
propValue = propValue.substring(1);
}
// we have a value, so it has to match the system value...
return reverseValue != propValue.equals(sysValue);
} else {
return reverseName != (sysValue != null && !sysValue.isEmpty());
}
| 140
| 378
| 518
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/ArtifactDescriptorReaderDelegate.java
|
ArtifactDescriptorReaderDelegate
|
populateResult
|
class ArtifactDescriptorReaderDelegate {
public void populateResult(InternalSession session, ArtifactDescriptorResult result, Model model) {<FILL_FUNCTION_BODY>}
private Dependency convert(org.apache.maven.api.model.Dependency dependency, ArtifactTypeRegistry stereotypes) {
ArtifactType stereotype = stereotypes.get(dependency.getType());
if (stereotype == null) {
// TODO: this here is fishy
stereotype = new DefaultType(dependency.getType(), Language.NONE, "", null, false);
}
boolean system = dependency.getSystemPath() != null
&& !dependency.getSystemPath().isEmpty();
Map<String, String> props = null;
if (system) {
props = Collections.singletonMap(MavenArtifactProperties.LOCAL_PATH, dependency.getSystemPath());
}
Artifact artifact = new DefaultArtifact(
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getClassifier(),
null,
dependency.getVersion(),
props,
stereotype);
List<Exclusion> exclusions = new ArrayList<>(dependency.getExclusions().size());
for (org.apache.maven.api.model.Exclusion exclusion : dependency.getExclusions()) {
exclusions.add(convert(exclusion));
}
return new Dependency(
artifact,
dependency.getScope(),
dependency.getOptional() != null ? dependency.isOptional() : null,
exclusions);
}
private Exclusion convert(org.apache.maven.api.model.Exclusion exclusion) {
return new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*");
}
private void setArtifactProperties(ArtifactDescriptorResult result, Model model) {
String downloadUrl = null;
DistributionManagement distMgmt = model.getDistributionManagement();
if (distMgmt != null) {
downloadUrl = distMgmt.getDownloadUrl();
}
if (downloadUrl != null && !downloadUrl.isEmpty()) {
Artifact artifact = result.getArtifact();
Map<String, String> props = new HashMap<>(artifact.getProperties());
props.put(ArtifactProperties.DOWNLOAD_URL, downloadUrl);
result.setArtifact(artifact.setProperties(props));
}
}
}
|
ArtifactTypeRegistry stereotypes = session.getSession().getArtifactTypeRegistry();
for (Repository r : model.getRepositories()) {
result.addRepository(session.toRepository(
session.getService(RepositoryFactory.class).createRemote(r)));
}
for (org.apache.maven.api.model.Dependency dependency : model.getDependencies()) {
result.addDependency(convert(dependency, stereotypes));
}
DependencyManagement mgmt = model.getDependencyManagement();
if (mgmt != null) {
for (org.apache.maven.api.model.Dependency dependency : mgmt.getDependencies()) {
result.addManagedDependency(convert(dependency, stereotypes));
}
}
Map<String, Object> properties = new LinkedHashMap<>();
Prerequisites prerequisites = model.getPrerequisites();
if (prerequisites != null) {
properties.put("prerequisites.maven", prerequisites.getMaven());
}
List<License> licenses = model.getLicenses();
properties.put("license.count", licenses.size());
for (int i = 0; i < licenses.size(); i++) {
License license = licenses.get(i);
properties.put("license." + i + ".name", license.getName());
properties.put("license." + i + ".url", license.getUrl());
properties.put("license." + i + ".comments", license.getComments());
properties.put("license." + i + ".distribution", license.getDistribution());
}
result.setProperties(properties);
setArtifactProperties(result, model);
| 611
| 432
| 1,043
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/ArtifactDescriptorUtils.java
|
ArtifactDescriptorUtils
|
toRepositoryPolicy
|
class ArtifactDescriptorUtils {
public static Artifact toPomArtifact(Artifact artifact) {
Artifact pomArtifact = artifact;
if (!pomArtifact.getClassifier().isEmpty() || !"pom".equals(pomArtifact.getExtension())) {
pomArtifact =
new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom", artifact.getVersion());
}
return pomArtifact;
}
/**
* Creates POM artifact out of passed in artifact by dropping classifier (if exists) and rewriting extension to
* "pom". Unconditionally, unlike {@link #toPomArtifact(Artifact)} that does this only for artifacts without
* classifiers.
*
* @since 4.0.0
*/
public static Artifact toPomArtifactUnconditionally(Artifact artifact) {
return new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom", artifact.getVersion());
}
public static RemoteRepository toRemoteRepository(Repository repository) {
RemoteRepository.Builder builder =
new RemoteRepository.Builder(repository.getId(), repository.getLayout(), repository.getUrl());
builder.setSnapshotPolicy(toRepositoryPolicy(repository.getSnapshots()));
builder.setReleasePolicy(toRepositoryPolicy(repository.getReleases()));
return builder.build();
}
public static RepositoryPolicy toRepositoryPolicy(org.apache.maven.api.model.RepositoryPolicy policy) {<FILL_FUNCTION_BODY>}
public static String toRepositoryChecksumPolicy(final String artifactRepositoryPolicy) {
switch (artifactRepositoryPolicy) {
case RepositoryPolicy.CHECKSUM_POLICY_FAIL:
return RepositoryPolicy.CHECKSUM_POLICY_FAIL;
case RepositoryPolicy.CHECKSUM_POLICY_IGNORE:
return RepositoryPolicy.CHECKSUM_POLICY_IGNORE;
case RepositoryPolicy.CHECKSUM_POLICY_WARN:
return RepositoryPolicy.CHECKSUM_POLICY_WARN;
default:
throw new IllegalArgumentException("unknown repository checksum policy: " + artifactRepositoryPolicy);
}
}
}
|
boolean enabled = true;
String checksums = toRepositoryChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN); // the default
String updates = RepositoryPolicy.UPDATE_POLICY_DAILY;
if (policy != null) {
enabled = policy.isEnabled();
if (policy.getUpdatePolicy() != null) {
updates = policy.getUpdatePolicy();
}
if (policy.getChecksumPolicy() != null) {
checksums = policy.getChecksumPolicy();
}
}
return new RepositoryPolicy(enabled, updates, checksums);
| 565
| 161
| 726
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/DefaultModelCache.java
|
GavCacheKey
|
gav
|
class GavCacheKey {
private final String gav;
private final String tag;
private final int hash;
GavCacheKey(String groupId, String artifactId, String version, String tag) {
this(gav(groupId, artifactId, version), tag);
}
GavCacheKey(String gav, String tag) {
this.gav = gav;
this.tag = tag;
this.hash = Objects.hash(gav, tag);
}
private static String gav(String groupId, String artifactId, String version) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (null == obj || !getClass().equals(obj.getClass())) {
return false;
}
GavCacheKey that = (GavCacheKey) obj;
return Objects.equals(this.gav, that.gav) && Objects.equals(this.tag, that.tag);
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return "GavCacheKey{" + "gav='" + gav + '\'' + ", tag='" + tag + '\'' + '}';
}
}
|
StringBuilder sb = new StringBuilder();
if (groupId != null) {
sb.append(groupId);
}
sb.append(":");
if (artifactId != null) {
sb.append(artifactId);
}
sb.append(":");
if (version != null) {
sb.append(version);
}
return sb.toString();
| 346
| 99
| 445
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.