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
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/user/AuthenticateUserApi.java
AuthenticateUserApi
authenticate
class AuthenticateUserApi { private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticateUserApi.class); @Value("${authToken.header}") private String tokenHeader; @Inject private AuthenticationManager jwtAdminAuthenticationManager; @Inject private UserDetailsService jwtAdminDetailsService; @Inject private JWTTokenUtil jwtTokenUtil; /** * Authenticate a user using username & password * @param authenticationRequest * @param device * @return * @throws AuthenticationException */ @RequestMapping(value = "/private/login", method = RequestMethod.POST) public ResponseEntity<?> authenticate(@RequestBody @Valid AuthenticationRequest authenticationRequest) throws AuthenticationException {<FILL_FUNCTION_BODY>} @RequestMapping(value = "/auth/refresh", method = RequestMethod.GET) public ResponseEntity<AuthenticationResponse> refreshAndGetAuthenticationToken(HttpServletRequest request) { String token = request.getHeader(tokenHeader); if(token != null && token.contains("Bearer")) { token = token.substring("Bearer ".length(),token.length()); } String username = jwtTokenUtil.getUsernameFromToken(token); JWTUser user = (JWTUser) jwtAdminDetailsService.loadUserByUsername(username); if (jwtTokenUtil.canTokenBeRefreshedWithGrace(token, user.getLastPasswordResetDate())) { String refreshedToken = jwtTokenUtil.refreshToken(token); return ResponseEntity.ok(new AuthenticationResponse(user.getId(),refreshedToken)); } else { return ResponseEntity.badRequest().body(null); } } }
//TODO SET STORE in flow // Perform the security Authentication authentication = null; try { //to be used when username and password are set authentication = jwtAdminAuthenticationManager.authenticate( new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword() ) ); } catch(Exception e) { if(e instanceof BadCredentialsException) { return new ResponseEntity<>("{\"message\":\"Bad credentials\"}",HttpStatus.UNAUTHORIZED); } LOGGER.error("Error during authentication " + e.getMessage()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if(authentication == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final JWTUser userDetails = (JWTUser)jwtAdminDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); // Return the token return ResponseEntity.ok(new AuthenticationResponse(userDetails.getId(),token));
457
344
801
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/user/ResetUserPasswordApi.java
ResetUserPasswordApi
passwordResetVerify
class ResetUserPasswordApi { private static final Logger LOGGER = LoggerFactory.getLogger(ResetUserPasswordApi.class); @Inject private UserFacade userFacade; /** * Request a reset password token * @param merchantStore * @param language * @param user * @param request */ @ResponseStatus(HttpStatus.OK) @PostMapping(value = { "/user/password/reset/request" }, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(httpMethod = "POST", value = "Launch user password reset flow", notes = "", response = ReadableUser.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void passwordResetRequest( @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, @Valid @RequestBody ResetPasswordRequest user, HttpServletRequest request) { userFacade.requestPasswordReset(user.getUsername(), user.getReturnUrl(), merchantStore, language); } /** * Verify a password token * @param store * @param token * @param merchantStore * @param language * @param request */ @ResponseStatus(HttpStatus.OK) @GetMapping(value = { "/user/{store}/reset/{token}" }, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(httpMethod = "GET", value = "Validate user password reset token", notes = "", response = Void.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void passwordResetVerify(@PathVariable String store, @PathVariable String token, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request) {<FILL_FUNCTION_BODY>} /** * Change password * @param passwordRequest * @param store * @param token * @param merchantStore * @param language * @param request */ @PostMapping(value = "/user/{store}/password/{token}", produces = { "application/json" }) @ApiOperation(httpMethod = "POST", value = "Change user password", response = Void.class) public void changePassword( @RequestBody @Valid PasswordRequest passwordRequest, @PathVariable String store, @PathVariable String token, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request) { // validate password if (StringUtils.isBlank(passwordRequest.getPassword()) || StringUtils.isBlank(passwordRequest.getRepeatPassword())) { throw new RestApiException("400", "Password don't match"); } if (!passwordRequest.getPassword().equals(passwordRequest.getRepeatPassword())) { throw new RestApiException("400", "Password don't match"); } userFacade.resetPassword(passwordRequest.getPassword(), token, store); } }
/** * Receives reset token Needs to validate if user found from token Needs * to validate if token has expired * * If no problem void is returned otherwise throw OperationNotAllowed * All of this in UserFacade */ userFacade.verifyPasswordRequestToken(token, store);
826
87
913
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/api/v2/product/ProductVariantApi.java
ProductVariantApi
update
class ProductVariantApi { private static final Logger LOGGER = LoggerFactory.getLogger(ProductVariantApi.class); @Autowired private ProductVariantFacade productVariantFacade; @Inject private UserFacade userFacade; @ResponseStatus(HttpStatus.CREATED) @PostMapping(value = { "/private/product/{productId}/variant" }) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") }) public @ResponseBody Entity create( @Valid @RequestBody PersistableProductVariant variant, @PathVariable Long productId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); Long id = productVariantFacade.create(variant, productId, merchantStore, language); return new Entity(id); } @ResponseStatus(HttpStatus.OK) @PutMapping(value = { "/private/product/{id}/variant/{variantId}" }) @ApiOperation(httpMethod = "PUT", value = "Update product variant", notes = "", produces = "application/json", response = Void.class) public @ResponseBody void update(@PathVariable Long id, @PathVariable Long variantId, @Valid @RequestBody PersistableProductVariant variant, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) {<FILL_FUNCTION_BODY>} @ResponseStatus(HttpStatus.OK) @GetMapping(value = { "/private/product/{id}/variant/{sku}/unique" }, produces = "application/json") @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") }) @ApiOperation(httpMethod = "GET", value = "Check if option set code already exists", notes = "", response = EntityExists.class) public @ResponseBody ResponseEntity<EntityExists> exists( @PathVariable Long id, @PathVariable String sku, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); boolean exist = productVariantFacade.exists(sku, merchantStore, id, language); return new ResponseEntity<EntityExists>(new EntityExists(exist), HttpStatus.OK); } @GetMapping(value = "/private/product/{id}/variant/{variantId}", produces = "application/json") @ApiOperation(httpMethod = "GET", value = "Get a productVariant by id", notes = "For administration and shop purpose. Specifying ?merchant is required otherwise it falls back to DEFAULT") @ApiResponses(value = { @ApiResponse(code = 200, message = "Single product found", response = ReadableProductVariant.class) }) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableProductVariant get( @PathVariable final Long id, @PathVariable Long variantId, @RequestParam(value = "lang", required = false) String lang, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) throws Exception { return productVariantFacade.get(variantId, id, merchantStore, language); } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { "/private/product/{id}/variants" }, method = RequestMethod.GET) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableEntityList<ReadableProductVariant> list(@PathVariable final Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, @RequestParam(value = "page", required = false, defaultValue = "0") Integer page, @RequestParam(value = "count", required = false, defaultValue = "10") Integer count) { return productVariantFacade.list(id, merchantStore, language, page, count); } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { "/private/product/{id}/variant/{variantId}" }, method = RequestMethod.DELETE) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void delete( @PathVariable Long id, @PathVariable Long variantId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { productVariantFacade.delete(variantId, id, merchantStore); } /** @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { "/private/product/{id}/{variantId}/image" }, method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void addvariantImage( @PathVariable Long id, @RequestParam(name = "file", required = true) MultipartFile file, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) { //productOptionFacade.addOptionValueImage(file, id, merchantStore, language); } **/ }
String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); productVariantFacade.update(variantId, variant, id, merchantStore, language);
1,704
144
1,848
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/api/v2/product/ProductVariantGroupApi.java
ProductVariantGroupApi
delete
class ProductVariantGroupApi { @Autowired private ProductVariantGroupFacade productVariantGroupFacade; @Autowired private UserFacade userFacade; @ResponseStatus(HttpStatus.CREATED) @PostMapping(value = { "/private/product/productVariantGroup" }) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") }) public @ResponseBody Entity create( @Valid @RequestBody PersistableProductVariantGroup instanceGroup, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); Long id = productVariantGroupFacade.create(instanceGroup, merchantStore, language); return new Entity(id); } @ResponseStatus(HttpStatus.OK) @PutMapping(value = { "/private/product/productVariantGroup/{id}" }) @ApiOperation(httpMethod = "PUT", value = "Update product instance group", notes = "", produces = "application/json", response = Void.class) public @ResponseBody void update(@PathVariable Long id, @Valid @RequestBody PersistableProductVariantGroup instance, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); productVariantGroupFacade.update(id, instance, merchantStore, language); } @ResponseStatus(HttpStatus.OK) @GetMapping(value = { "/private/product/productVariantGroup/{id}" }) @ApiOperation(httpMethod = "GET", value = "Get product instance group", notes = "", produces = "application/json", response = Void.class) public @ResponseBody ReadableProductVariantGroup get( @PathVariable Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); return productVariantGroupFacade.get(id, merchantStore, language); } // delete @ResponseStatus(HttpStatus.OK) @DeleteMapping(value = { "/private/product/productVariantGroup/{id}" }) @ApiOperation(httpMethod = "DELETE", value = "Delete product instance group", notes = "", produces = "application/json", response = Void.class) public @ResponseBody void delete(@PathVariable Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) {<FILL_FUNCTION_BODY>} // list @ResponseStatus(HttpStatus.OK) @GetMapping(value = { "/private/product/{id}/productVariantGroup" }) @ApiOperation(httpMethod = "GET", value = "Delete product instance group", notes = "", produces = "application/json", response = Void.class) public @ResponseBody ReadableEntityList<ReadableProductVariantGroup> list( @PathVariable final Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, @RequestParam(value = "page", required = false, defaultValue = "0") Integer page, @RequestParam(value = "count", required = false, defaultValue = "10") Integer count) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); return productVariantGroupFacade.list(id, merchantStore, language, page, count); } // add image @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { "/private/product/productVariantGroup/{id}/image" }, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }, method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void addImage( @PathVariable Long id, @RequestParam(value = "file", required = true) MultipartFile file, @RequestParam(value = "order", required = false, defaultValue = "0") Integer position, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); productVariantGroupFacade.addImage(file, id, merchantStore, language); } // remove image @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { "/private/product/productVariantGroup/{id}/image/{imageId}" }, method = RequestMethod.DELETE) public void removeImage(@PathVariable Long id, @PathVariable Long imageId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); productVariantGroupFacade.removeImage(imageId, id, merchantStore); } }
String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_CATALOGUE, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); productVariantGroupFacade.delete(id, id, merchantStore);
1,839
140
1,979
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/AbstractController.java
AbstractController
calculatePaginaionData
class AbstractController { /** * Method which will help to retrieving values from Session * based on the key being passed to the method. * @param key * @return value stored in session corresponding to the key */ @SuppressWarnings( "unchecked" ) protected <T> T getSessionAttribute(final String key, HttpServletRequest request) { return (T) com.salesmanager.shop.utils.SessionUtil.getSessionAttribute(key, request); } protected void setSessionAttribute(final String key, final Object value, HttpServletRequest request) { com.salesmanager.shop.utils.SessionUtil.setSessionAttribute(key, value, request); } protected void removeAttribute(final String key, HttpServletRequest request) { com.salesmanager.shop.utils.SessionUtil.removeSessionAttribute(key, request); } protected Language getLanguage(HttpServletRequest request) { return (Language)request.getAttribute(Constants.LANGUAGE); } protected PaginationData createPaginaionData( final int pageNumber, final int pageSize ) { final PaginationData paginaionData = new PaginationData(pageSize,pageNumber); return paginaionData; } protected PaginationData calculatePaginaionData( final PaginationData paginationData, final int pageSize, final int resultCount){<FILL_FUNCTION_BODY>} }
int currentPage = paginationData.getCurrentPage(); int count = Math.min((currentPage * pageSize), resultCount); paginationData.setCountByPage(count); paginationData.setTotalCount( resultCount ); return paginationData;
373
76
449
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/country/facade/CountryFacadeImpl.java
CountryFacadeImpl
getListOfCountryZones
class CountryFacadeImpl implements CountryFacade { @Inject private CountryService countryService; @Override public List<ReadableCountry> getListCountryZones(Language language, MerchantStore merchantStore) { return getListOfCountryZones(language) .stream() .map(country -> convertToReadableCountry(country, language, merchantStore)) .collect(Collectors.toList()); } private ReadableCountry convertToReadableCountry(Country country, Language language, MerchantStore merchantStore) { try{ ReadableCountryPopulator populator = new ReadableCountryPopulator(); return populator.populate(country, new ReadableCountry(), merchantStore, language); } catch (ConversionException e) { throw new ConversionRuntimeException(e); } } private List<Country> getListOfCountryZones(Language language) {<FILL_FUNCTION_BODY>} }
try{ return countryService.listCountryZones(language); } catch (ServiceException e) { throw new ServiceRuntimeException(e); }
259
49
308
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/currency/facade/CurrencyFacadeImpl.java
CurrencyFacadeImpl
getList
class CurrencyFacadeImpl implements CurrencyFacade { @Inject private CurrencyService currencyService; @Override public List<Currency> getList() {<FILL_FUNCTION_BODY>} }
List<Currency> currencyList = currencyService.list(); if (currencyList.isEmpty()){ throw new ResourceNotFoundException("No languages found"); } Collections.sort(currencyList, new Comparator<Currency>(){ public int compare(Currency o1, Currency o2) { return o1.getCode().compareTo(o2.getCode()); } }); return currencyList;
66
130
196
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/error/ShopErrorController.java
ShopErrorController
handleException
class ShopErrorController { private static final Logger LOGGER = LoggerFactory.getLogger(ShopErrorController.class); @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @Produces({MediaType.APPLICATION_JSON}) public ModelAndView handleException(Exception ex) {<FILL_FUNCTION_BODY>} @ExceptionHandler(RuntimeException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @Produces({MediaType.APPLICATION_JSON}) public ModelAndView handleRuntimeException(Exception ex) { LOGGER.error("Error page controller",ex); ModelAndView model = null; model = new ModelAndView("error/generic_error"); model.addObject("stackError", ExceptionUtils.getStackTrace(ex)); model.addObject("errMsg", ex.getMessage()); return model; } /** * Generic exception catch allpage * @param ex * @return */ @RequestMapping(value="/error", method=RequestMethod.GET) public ModelAndView handleCatchAllException(Model model) { ModelAndView modelAndView = null; modelAndView = new ModelAndView("error/generic_error"); return modelAndView; } }
LOGGER.error("Error page controller",ex); ModelAndView model = null; if(ex instanceof AccessDeniedException) { model = new ModelAndView("error/access_denied"); } else { model = new ModelAndView("error/generic_error"); model.addObject("stackError", ExceptionUtils.getStackTrace(ex)); model.addObject("errMsg", ex.getMessage()); } return model;
371
134
505
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/language/facade/LanguageFacadeImpl.java
LanguageFacadeImpl
getLanguages
class LanguageFacadeImpl implements LanguageFacade { @Inject private LanguageService languageService; @Override public List<Language> getLanguages() {<FILL_FUNCTION_BODY>} }
try{ List<Language> languages = languageService.getLanguages(); if (languages.isEmpty()) { throw new ResourceNotFoundException("No languages found"); } return languages; } catch (ServiceException e){ throw new ServiceRuntimeException(e); }
63
86
149
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/marketplace/facade/MarketPlaceFacadeImpl.java
MarketPlaceFacadeImpl
createReadableMarketPlace
class MarketPlaceFacadeImpl implements MarketPlaceFacade { @Inject private StoreFacade storeFacade; @Inject private OptinService optinService; @Override public ReadableMarketPlace get(String store, Language lang) { ReadableMerchantStore readableStore = storeFacade.getByCode(store, lang); return createReadableMarketPlace(readableStore); } private ReadableMarketPlace createReadableMarketPlace(ReadableMerchantStore readableStore) {<FILL_FUNCTION_BODY>} @Override public ReadableOptin findByMerchantAndType(MerchantStore store, OptinType type) { Optin optin = getOptinByMerchantAndType(store, type); return convertOptinToReadableOptin(store, optin); } private Optin getOptinByMerchantAndType(MerchantStore store, OptinType type) { try{ return Optional.ofNullable(optinService.getOptinByMerchantAndType(store, type)) .orElseThrow(() -> new ResourceNotFoundException("Option not found")); } catch (ServiceException e) { throw new ServiceRuntimeException(e); } } private ReadableOptin convertOptinToReadableOptin(MerchantStore store, Optin optin) { try{ ReadableOptinPopulator populator = new ReadableOptinPopulator(); return populator.populate(optin, null, store, null); } catch (ConversionException e) { throw new ConversionRuntimeException(e); } } }
//TODO add info from Entity ReadableMarketPlace marketPlace = new ReadableMarketPlace(); marketPlace.setStore(readableStore); return marketPlace;
410
48
458
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/optin/OptinFacadeImpl.java
OptinFacadeImpl
createOptin
class OptinFacadeImpl implements OptinFacade { @Inject private OptinService optinService; @Inject private ReadableOptinMapper readableOptinConverter; @Inject private PersistableOptinMapper persistableOptinConverter; @Override public ReadableOptin create( PersistableOptin persistableOptin, MerchantStore merchantStore, Language language) { Optin optinEntity = persistableOptinConverter.convert(persistableOptin, merchantStore, language); Optin savedOptinEntity = createOptin(optinEntity); return readableOptinConverter.convert(savedOptinEntity, merchantStore, language); } private Optin createOptin(Optin optinEntity) {<FILL_FUNCTION_BODY>} }
try{ optinService.create(optinEntity); return optinEntity; } catch (ServiceException e){ throw new ServiceRuntimeException(e); }
224
57
281
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/search/facade/SearchFacadeImpl.java
SearchFacadeImpl
convertProductToReadableProduct
class SearchFacadeImpl implements SearchFacade { private static final Logger LOGGER = LoggerFactory.getLogger(SearchFacadeImpl.class); @Inject private SearchService searchService; @Inject private ProductService productService; @Inject private CategoryService categoryService; @Inject private PricingService pricingService; @Inject @Qualifier("img") private ImageFilePath imageUtils; private final static String CATEGORY_FACET_NAME = "categories"; private final static String MANUFACTURER_FACET_NAME = "manufacturer"; private final static int AUTOCOMPLETE_ENTRIES_COUNT = 15; /** * Index all products from the catalogue Better stop the system, remove ES * indexex manually restart ES and run this query */ @Override @Async public void indexAllData(MerchantStore store) throws Exception { List<Product> products = productService.listByStore(store); products.stream().forEach(p -> { try { searchService.index(store, p); } catch (ServiceException e) { throw new RuntimeException("Exception while indexing products", e); } }); } @Override public List<SearchItem> search(MerchantStore store, Language language, SearchProductRequest searchRequest) { SearchResponse response = search(store, language.getCode(), searchRequest.getQuery(), searchRequest.getCount(), searchRequest.getStart()); return response.getItems(); } private SearchResponse search(MerchantStore store, String languageCode, String query, Integer count, Integer start) { Validate.notNull(query,"Search Keyword must not be null"); Validate.notNull(languageCode, "Language cannot be null"); Validate.notNull(store,"MerchantStore cannot be null"); try { LOGGER.debug("Search " + query); SearchRequest searchRequest = new SearchRequest(); searchRequest.setLanguage(languageCode); searchRequest.setSearchString(query); searchRequest.setStore(store.getCode().toLowerCase()); //aggregations //TODO add scroll return searchService.search(store, languageCode, searchRequest, count, start); } catch (ServiceException e) { throw new ServiceRuntimeException(e); } } private List<ReadableCategory> getCategoryFacets(MerchantStore merchantStore, Language language, List<Aggregation> facets) { /** List<SearchFacet> categoriesFacets = facets.entrySet().stream() .filter(e -> CATEGORY_FACET_NAME.equals(e.getKey())).findFirst().map(Entry::getValue) .orElse(Collections.emptyList()); if (CollectionUtils.isNotEmpty(categoriesFacets)) { List<String> categoryCodes = categoriesFacets.stream().map(SearchFacet::getName) .collect(Collectors.toList()); Map<String, Long> productCategoryCount = categoriesFacets.stream() .collect(Collectors.toMap(SearchFacet::getKey, SearchFacet::getCount)); List<Category> categories = categoryService.listByCodes(merchantStore, categoryCodes, language); return categories.stream().map(category -> convertCategoryToReadableCategory(merchantStore, language, productCategoryCount, category)).collect(Collectors.toList()); } else { return Collections.emptyList(); } **/ return null; } private ReadableCategory convertCategoryToReadableCategory(MerchantStore merchantStore, Language language, Map<String, Long> productCategoryCount, Category category) { ReadableCategoryPopulator populator = new ReadableCategoryPopulator(); try { ReadableCategory categoryProxy = populator.populate(category, new ReadableCategory(), merchantStore, language); Long total = productCategoryCount.get(categoryProxy.getCode()); if (total != null) { categoryProxy.setProductCount(total.intValue()); } return categoryProxy; } catch (ConversionException e) { throw new ConversionRuntimeException(e); } } private ReadableProduct convertProductToReadableProduct(Product product, MerchantStore merchantStore, Language language) {<FILL_FUNCTION_BODY>} @Override public ValueList autocompleteRequest(String word, MerchantStore store, Language language) { Validate.notNull(word,"Search Keyword must not be null"); Validate.notNull(language, "Language cannot be null"); Validate.notNull(store,"MerchantStore cannot be null"); SearchRequest req = new SearchRequest(); req.setLanguage(language.getCode()); req.setStore(store.getCode().toLowerCase()); req.setSearchString(word); req.setLanguage(language.getCode()); SearchResponse response; try { response = searchService.searchKeywords(store, language.getCode(), req, AUTOCOMPLETE_ENTRIES_COUNT); } catch (ServiceException e) { throw new RuntimeException(e); } List<String> keywords = response.getItems().stream().map(i -> i.getSuggestions()).collect(Collectors.toList()); ValueList valueList = new ValueList(); valueList.setValues(keywords); return valueList; } }
ReadableProductPopulator populator = new ReadableProductPopulator(); populator.setPricingService(pricingService); populator.setimageUtils(imageUtils); try { return populator.populate(product, new ReadableProduct(), merchantStore, language); } catch (ConversionException e) { throw new ConversionRuntimeException(e); }
1,433
104
1,537
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/security/facade/SecurityFacadeImpl.java
SecurityFacadeImpl
getPermissions
class SecurityFacadeImpl implements SecurityFacade { private static final String USER_PASSWORD_PATTERN = "((?=.*[a-z])(?=.*\\d)(?=.*[A-Z]).{6,12})"; private Pattern userPasswordPattern = Pattern.compile(USER_PASSWORD_PATTERN); @Inject private PermissionService permissionService; @Inject private GroupService groupService; @Inject private PasswordEncoder passwordEncoder; @SuppressWarnings({"rawtypes", "unchecked"}) @Override public List<ReadablePermission> getPermissions(List<String> groups) {<FILL_FUNCTION_BODY>} @Override public boolean validateUserPassword(String password) { Matcher matcher = userPasswordPattern.matcher(password); return matcher.matches(); } @Override public String encodePassword(String password) { return passwordEncoder.encode(password); } /** * Match non encoded to encoded * Don't use this as a simple raw password check */ @Override public boolean matchPassword(String modelPassword, String newPassword) { return passwordEncoder.matches(newPassword, modelPassword); } @Override public boolean matchRawPasswords(String password, String repeatPassword) { Validate.notNull(password,"password is null"); Validate.notNull(repeatPassword,"repeat password is null"); return password.equals(repeatPassword); } }
List<Group> userGroups = null; try { userGroups = groupService.listGroupByNames(groups); List<Integer> ids = new ArrayList<Integer>(); for (Group g : userGroups) { ids.add(g.getId()); } PermissionCriteria criteria = new PermissionCriteria(); criteria.setGroupIds(new HashSet(ids)); PermissionList permissions = permissionService.listByCriteria(criteria); throw new ServiceRuntimeException("Not implemented"); } catch (ServiceException e) { e.printStackTrace(); } return null;
401
161
562
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/system/MerchantConfigurationFacadeImpl.java
MerchantConfigurationFacadeImpl
getMerchantConfig
class MerchantConfigurationFacadeImpl implements MerchantConfigurationFacade { private static final Logger LOGGER = LoggerFactory .getLogger(MerchantConfigurationFacadeImpl.class); @Inject private MerchantConfigurationService merchantConfigurationService; @Value("${config.displayShipping}") private String displayShipping; @Override public Configs getMerchantConfig(MerchantStore merchantStore, Language language) {<FILL_FUNCTION_BODY>} private MerchantConfig getMerchantConfig(MerchantStore merchantStore) { try{ return merchantConfigurationService.getMerchantConfig(merchantStore); } catch (ServiceException e){ throw new ServiceRuntimeException(e); } } private Optional<String> getConfigValue(String keyContant, MerchantStore merchantStore) { return getMerchantConfiguration(keyContant, merchantStore) .map(MerchantConfiguration::getValue); } private Optional<MerchantConfiguration> getMerchantConfiguration(String key, MerchantStore merchantStore) { try{ return Optional.ofNullable(merchantConfigurationService.getMerchantConfiguration(key, merchantStore)); } catch (ServiceException e) { throw new ServiceRuntimeException(e); } } }
MerchantConfig configs = getMerchantConfig(merchantStore); Configs readableConfig = new Configs(); readableConfig.setAllowOnlinePurchase(configs.isAllowPurchaseItems()); readableConfig.setDisplaySearchBox(configs.isDisplaySearchBox()); readableConfig.setDisplayContactUs(configs.isDisplayContactUs()); readableConfig.setDisplayCustomerSection(configs.isDisplayCustomerSection()); readableConfig.setDisplayAddToCartOnFeaturedItems(configs.isDisplayAddToCartOnFeaturedItems()); readableConfig.setDisplayCustomerAgreement(configs.isDisplayCustomerAgreement()); readableConfig.setDisplayPagesMenu(configs.isDisplayPagesMenu()); Optional<String> facebookConfigValue = getConfigValue(KEY_FACEBOOK_PAGE_URL, merchantStore); facebookConfigValue.ifPresent(readableConfig::setFacebook); Optional<String> googleConfigValue = getConfigValue(KEY_GOOGLE_ANALYTICS_URL, merchantStore); googleConfigValue.ifPresent(readableConfig::setGa); Optional<String> instagramConfigValue = getConfigValue(KEY_INSTAGRAM_URL, merchantStore); instagramConfigValue.ifPresent(readableConfig::setInstagram); Optional<String> pinterestConfigValue = getConfigValue(KEY_PINTEREST_PAGE_URL, merchantStore); pinterestConfigValue.ifPresent(readableConfig::setPinterest); readableConfig.setDisplayShipping(false); try { if(!StringUtils.isBlank(displayShipping)) { readableConfig.setDisplayShipping(Boolean.valueOf(displayShipping)); } } catch(Exception e) { LOGGER.error("Cannot parse value of " + displayShipping); } return readableConfig;
356
512
868
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/controller/zone/facade/ZoneFacadeImpl.java
ZoneFacadeImpl
getZones
class ZoneFacadeImpl implements ZoneFacade { @Inject private ZoneService zoneService; @Override public List<ReadableZone> getZones(String countryCode, Language language, MerchantStore merchantStore) {<FILL_FUNCTION_BODY>} private ReadableZone convertToReadableZone(Zone zone, Language language, MerchantStore merchantStore) { try{ ReadableZonePopulator populator = new ReadableZonePopulator(); return populator.populate(zone, new ReadableZone(), merchantStore, language); } catch (ConversionException e){ throw new ConversionRuntimeException(e); } } private List<Zone> getListZones(String countryCode, Language language) { try{ return zoneService.getZones(countryCode, language); } catch (ServiceException e){ throw new ServiceRuntimeException(e); } } }
List<Zone> listZones = getListZones(countryCode, language); if (listZones.isEmpty()){ return Collections.emptyList(); //throw new ResourceNotFoundException("No zones found"); } return listZones.stream() .map(zone -> convertToReadableZone(zone, language, merchantStore)) .collect(Collectors.toList());
255
110
365
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/customer/CustomerFacadeImpl.java
CustomerFacadeImpl
requestPasswordReset
class CustomerFacadeImpl implements CustomerFacade { @Autowired private com.salesmanager.shop.store.controller.customer.facade.CustomerFacade customerFacade; @Autowired private CustomerService customerService; @Autowired private FilePathUtils filePathUtils; @Autowired private LanguageService lamguageService; @Autowired private EmailUtils emailUtils; @Autowired private EmailService emailService; @Autowired @Qualifier("img") private ImageFilePath imageUtils; @Inject private LabelUtils messages; @Inject private PasswordEncoder passwordEncoder; private static final String resetCustomerLink = "customer/%s/reset/%s"; // front // url private static final String ACCOUNT_PASSWORD_RESET_TPL = "email_template_password_reset_request_customer.ftl"; private static final String RESET_PASSWORD_LINK = "RESET_PASSWORD_LINK"; private static final String RESET_PASSWORD_TEXT = "RESET_PASSWORD_TEXT"; @Override public void authorize(Customer customer, Principal principal) { Validate.notNull(customer, "Customer cannot be null"); Validate.notNull(principal, "Principal cannot be null"); if (!principal.getName().equals(customer.getNick())) { throw new UnauthorizedException( "User [" + principal.getName() + "] unauthorized for customer [" + customer.getId() + "]"); } } @Override public void requestPasswordReset(String customerName, String customerContextPath, MerchantStore store, Language language) {<FILL_FUNCTION_BODY>} @Async private void resetPasswordRequest(Customer customer, String resetLink, MerchantStore store, Locale locale) throws Exception { try { // creation of a user, send an email String[] storeEmail = { store.getStoreEmailAddress() }; Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(imageUtils.getContextPath(), store, messages, locale); templateTokens.put(EmailConstants.LABEL_HI, messages.getMessage("label.generic.hi", locale)); templateTokens.put(EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, customer.getBilling().getFirstName()); templateTokens.put(RESET_PASSWORD_LINK, resetLink); templateTokens.put(RESET_PASSWORD_TEXT, messages.getMessage("email.reset.password.text", new String[] { store.getStorename() }, locale)); templateTokens.put(EmailConstants.LABEL_LINK_TITLE, messages.getMessage("email.link.reset.password.title", locale)); templateTokens.put(EmailConstants.LABEL_LINK, messages.getMessage("email.link", locale)); templateTokens.put(EmailConstants.EMAIL_CONTACT_OWNER, messages.getMessage("email.contactowner", storeEmail, locale)); Email email = new Email(); email.setFrom(store.getStorename()); email.setFromEmail(store.getStoreEmailAddress()); email.setSubject(messages.getMessage("email.link.reset.password.title", locale)); email.setTo(customer.getEmailAddress()); email.setTemplateName(ACCOUNT_PASSWORD_RESET_TPL); email.setTemplateTokens(templateTokens); emailService.sendHtmlEmail(store, email); } catch (Exception e) { throw new Exception("Cannot send email to customer", e); } } @Override public void verifyPasswordRequestToken(String token, String store) { Validate.notNull(token, "ResetPassword token cannot be null"); Validate.notNull(store, "Store code cannot be null"); verifyCustomerLink(token, store); return; } @Override public void resetPassword(String password, String token, String store) { Validate.notNull(token, "ResetPassword token cannot be null"); Validate.notNull(store, "Store code cannot be null"); Validate.notNull(password, "New password cannot be null"); Customer customer = verifyCustomerLink(token, store);// reverify customer.setPassword(passwordEncoder.encode(password)); try { customerService.save(customer); } catch (ServiceException e) { throw new ServiceRuntimeException("Error while saving customer",e); } } private Customer verifyCustomerLink(String token, String store) { Customer customer = null; try { customer = customerService.getByPasswordResetToken(store, token); if (customer == null) { throw new ResourceNotFoundException( "Customer not fount for store [" + store + "] and token [" + token + "]"); } } catch (Exception e) { throw new ServiceRuntimeException("Cannot verify customer token", e); } Date tokenExpiry = customer.getCredentialsResetRequest().getCredentialsRequestExpiry(); if (tokenExpiry == null) { throw new GenericRuntimeException("No expiry date configured for token [" + token + "]"); } if (!DateUtil.dateBeforeEqualsDate(new Date(), tokenExpiry)) { throw new GenericRuntimeException("Ttoken [" + token + "] has expired"); } return customer; } @Override public boolean customerExists(String userName, MerchantStore store) { return Optional.ofNullable(customerService.getByNick(userName, store.getId())) .isPresent(); } }
try { // get customer by user name Customer customer = customerService.getByNick(customerName, store.getId()); if (customer == null) { throw new ResourceNotFoundException( "Customer [" + customerName + "] not found for store [" + store.getCode() + "]"); } // generates unique token String token = UUID.randomUUID().toString(); Date expiry = DateUtil.addDaysToCurrentDate(2); CredentialsReset credsRequest = new CredentialsReset(); credsRequest.setCredentialsRequest(token); credsRequest.setCredentialsRequestExpiry(expiry); customer.setCredentialsResetRequest(credsRequest); customerService.saveOrUpdate(customer); // reset password link // this will build http | https ://domain/contextPath String baseUrl = filePathUtils.buildBaseUrl(customerContextPath, store); // need to add link to controller receiving user reset password // request String customerResetLink = new StringBuilder().append(baseUrl) .append(String.format(resetCustomerLink, store.getCode(), token)).toString(); resetPasswordRequest(customer, customerResetLink, store, lamguageService.toLocale(language, store)); } catch (Exception e) { throw new ServiceRuntimeException("Error while executing resetPassword request", e); } /** * User sends username (unique in the system) * * UserNameEntity will be the following { userName: "test@test.com" } * * The system retrieves user using userName (username is unique) if user * exists, system sends an email with reset password link * * How to retrieve a User from userName * * userFacade.findByUserName * * How to send an email * * * How to generate a token * * Generate random token * * Calculate token expiration date * * Now + 48 hours * * Update User in the database with token * * Send reset token email */
1,465
560
2,025
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/order/OrderFacadeImpl.java
OrderFacadeImpl
orderConfirmation
class OrderFacadeImpl implements OrderFacade { private static final Logger LOGGER = LoggerFactory.getLogger(OrderFacadeImpl.class); @Autowired private ReadableCustomerMapper readableCustomerMapper; @Autowired private ReadableOrderTotalMapper readableOrderTotalMapper; @Autowired private ReadableOrderProductMapper readableOrderProductMapper; @Autowired private LabelUtils messages; @Autowired private LanguageService languageService; @Override public ReadableOrderConfirmation orderConfirmation(Order order, Customer customer, MerchantStore store, Language language) {<FILL_FUNCTION_BODY>} private ReadableOrderTotal convertOrderTotal(OrderTotal total, MerchantStore store, Language language) { return readableOrderTotalMapper.convert(total, store, language); } private ReadableOrderProduct convertOrderProduct(OrderProduct product, MerchantStore store, Language language) { return readableOrderProductMapper.convert(product, store, language); } }
Validate.notNull(order, "Order cannot be null"); Validate.notNull(customer, "Customer cannot be null"); Validate.notNull(store, "MerchantStore cannot be null"); ReadableOrderConfirmation orderConfirmation = new ReadableOrderConfirmation(); ReadableCustomer readableCustomer = readableCustomerMapper.convert(customer, store, language); orderConfirmation.setBilling(readableCustomer.getBilling()); orderConfirmation.setDelivery(readableCustomer.getDelivery()); ReadableTotal readableTotal = new ReadableTotal(); Set<OrderTotal> totals = order.getOrderTotal(); List<ReadableOrderTotal> readableTotals = totals.stream() .sorted(Comparator.comparingInt(OrderTotal::getSortOrder)) .map(tot -> convertOrderTotal(tot, store, language)) .collect(Collectors.toList()); readableTotal.setTotals(readableTotals); Optional<ReadableOrderTotal> grandTotal = readableTotals.stream().filter(tot -> tot.getCode().equals("order.total.total")).findFirst(); if(grandTotal.isPresent()) { readableTotal.setGrandTotal(grandTotal.get().getText()); } orderConfirmation.setTotal(readableTotal); List<ReadableOrderProduct> products = order.getOrderProducts().stream().map(pr -> convertOrderProduct(pr, store, language)).collect(Collectors.toList()); orderConfirmation.setProducts(products); if(!StringUtils.isBlank(order.getShippingModuleCode())) { StringBuilder optionCodeBuilder = new StringBuilder(); try { optionCodeBuilder .append("module.shipping.") .append(order.getShippingModuleCode()); String shippingName = messages.getMessage(optionCodeBuilder.toString(), new String[]{store.getStorename()},languageService.toLocale(language, store)); orderConfirmation.setShipping(shippingName); } catch (Exception e) { // label not found LOGGER.warn("No shipping code found for " + optionCodeBuilder.toString()); } } if(order.getPaymentType() != null) { orderConfirmation.setPayment(order.getPaymentType().name()); } /** * Confirmation may be formatted */ orderConfirmation.setId(order.getId()); return orderConfirmation;
267
684
951
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/payment/PaymentConfigurationFacadeImpl.java
PaymentConfigurationFacadeImpl
configuration
class PaymentConfigurationFacadeImpl implements ConfigurationsFacade { @Autowired private PaymentService paymentService; @Override public List<ReadableConfiguration> configurations(MerchantStore store) { try { List<PaymentMethod> methods = paymentService.getAcceptedPaymentMethods(store); List<ReadableConfiguration> configurations = methods.stream() .map(m -> configuration(m.getInformations(), store)).collect(Collectors.toList()); return configurations; } catch (ServiceException e) { throw new ServiceRuntimeException("Error while getting payment configurations",e); } } @Override public ReadableConfiguration configuration(String module, MerchantStore store) {<FILL_FUNCTION_BODY>} @Override public void saveConfiguration(PersistableConfiguration configuration, MerchantStore store) { // TODO Auto-generated method stub } @Override public void deleteConfiguration(String module, MerchantStore store) { // TODO Auto-generated method stub } private ReadableConfiguration configuration(IntegrationConfiguration source, MerchantStore store) { ReadableConfiguration config = new ReadableConfiguration(); config.setActive(source.isActive()); config.setCode(source.getModuleCode()); config.setKeys(source.getIntegrationKeys()); config.setIntegrationOptions(source.getIntegrationOptions()); return config; } }
try { ReadableConfiguration config = null; List<PaymentMethod> methods = paymentService.getAcceptedPaymentMethods(store); Optional<ReadableConfiguration> configuration = methods.stream() .filter(m -> module.equals(m.getModule().getCode())) .map(m -> this.configuration(m.getInformations(), store)) .findFirst(); if(configuration.isPresent()) { config = configuration.get(); } return config; } catch (ServiceException e) { throw new ServiceRuntimeException("Error while getting payment configuration [" + module + "]",e); }
374
180
554
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductDefinitionFacadeImpl.java
ProductDefinitionFacadeImpl
saveProductDefinition
class ProductDefinitionFacadeImpl implements ProductDefinitionFacade { @Inject private ProductService productService; @Autowired private PersistableProductDefinitionMapper persistableProductDefinitionMapper; @Autowired private ReadableProductDefinitionMapper readableProductDefinitionMapper; @Autowired private ProductVariantFacade productVariantFacade; @Inject @Qualifier("img") private ImageFilePath imageUtils; @Override public Long saveProductDefinition(MerchantStore store, PersistableProductDefinition product, Language language) {<FILL_FUNCTION_BODY>} @Override public void update(Long id, PersistableProductDefinition product, MerchantStore merchant, Language language) { product.setId(id); this.saveProductDefinition(merchant, product, language); } @Override public ReadableProductDefinition getProduct(MerchantStore store, Long id, Language language) { Product product = productService.findOne(id, store); return readableProductDefinitionMapper.convert(product, store, language); } @Override public ReadableProductDefinition getProductBySku(MerchantStore store, String uniqueCode, Language language) { Product product = null; try { product = productService.getBySku(uniqueCode, store, language); } catch (ServiceException e) { throw new ServiceRuntimeException(e); } return readableProductDefinitionMapper.convert(product, store, language); } }
Product target = null; if (product.getId() != null && product.getId().longValue() > 0) { Optional<Product> p = productService.retrieveById(product.getId(), store); if(p.isEmpty()) { throw new ResourceNotFoundException("Product with id [" + product.getId() + "] not found for store [" + store.getCode() + "]"); } target = p.get(); } else { target = new Product(); } try { target = persistableProductDefinitionMapper.merge(product, target, store, language); productService.saveProduct(target); product.setId(target.getId()); return target.getId(); } catch (Exception e) { throw new ServiceRuntimeException(e); }
378
218
596
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionSetFacadeImpl.java
ProductOptionSetFacadeImpl
update
class ProductOptionSetFacadeImpl implements ProductOptionSetFacade { @Autowired private PersistableProductOptionSetMapper persistableProductOptionSetMapper; @Autowired private ReadableProductOptionSetMapper readableProductOptionSetMapper; @Autowired private ProductOptionSetService productOptionSetService; @Autowired private ProductTypeFacade productTypeFacade;; @Override public ReadableProductOptionSet get(Long id, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); ProductOptionSet optionSet = productOptionSetService.getById(store, id, language); if (optionSet == null) { throw new ResourceNotFoundException( "ProductOptionSet not found for id [" + id + "] and store [" + store.getCode() + "]"); } return readableProductOptionSetMapper.convert(optionSet, store, language); } @Override public List<ReadableProductOptionSet> list(MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); try { List<ProductOptionSet> optionSets = productOptionSetService.listByStore(store, language); return optionSets.stream().map(opt -> this.convert(opt, store, language)).collect(Collectors.toList()); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while listing ProductOptionSet", e); } } private ReadableProductOptionSet convert(ProductOptionSet optionSet, MerchantStore store, Language language) { return readableProductOptionSetMapper.convert(optionSet, store, language); } @Override public void create(PersistableProductOptionSet optionSet, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Validate.notNull(optionSet, "PersistableProductOptionSet cannot be null"); if (this.exists(optionSet.getCode(), store)) { throw new OperationNotAllowedException("Option set with code [" + optionSet.getCode() + "] already exist"); } ProductOptionSet opt = persistableProductOptionSetMapper.convert(optionSet, store, language); try { opt.setStore(store); productOptionSetService.create(opt); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while creating ProductOptionSet", e); } } @Override public void update(Long id, PersistableProductOptionSet optionSet, MerchantStore store, Language language) {<FILL_FUNCTION_BODY>} @Override public void delete(Long id, MerchantStore store) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(id, "id cannot be null"); ProductOptionSet opt = productOptionSetService.getById(id); if (opt == null) { throw new ResourceNotFoundException( "ProductOptionSet not found for id [" + id + "] and store [" + store.getCode() + "]"); } if (!opt.getStore().getCode().equals(store.getCode())) { throw new ResourceNotFoundException( "ProductOptionSet not found for id [" + id + "] and store [" + store.getCode() + "]"); } try { productOptionSetService.delete(opt); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while deleting ProductOptionSet", e); } } @Override public boolean exists(String code, MerchantStore store) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(code, "code cannot be null"); ProductOptionSet optionSet = productOptionSetService.getCode(store, code); if (optionSet != null) { return true; } return false; } @Override public List<ReadableProductOptionSet> list(MerchantStore store, Language language, String type) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Validate.notNull(type, "Product type cannot be null"); // find product type by id ReadableProductType readable = productTypeFacade.get(store, type, language); if(readable == null) { throw new ResourceNotFoundException("Can't fing product type [" + type + "] fpr merchand [" + store.getCode() +"]"); } List<ProductOptionSet> optionSets = productOptionSetService.getByProductType(readable.getId(), store, language); return optionSets.stream().map(opt -> this.convert(opt, store, language)).collect(Collectors.toList()); } }
Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Validate.notNull(optionSet, "PersistableProductOptionSet cannot be null"); ProductOptionSet opt = productOptionSetService.getById(store, id, language); if (opt == null) { throw new ResourceNotFoundException( "ProductOptionSet not found for id [" + id + "] and store [" + store.getCode() + "]"); } optionSet.setId(id); optionSet.setCode(opt.getCode()); ProductOptionSet model = persistableProductOptionSetMapper.convert(optionSet, store, language); try { model.setStore(store); productOptionSetService.save(model); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while creating ProductOptionSet", e); }
1,290
244
1,534
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductPriceFacadeImpl.java
ProductPriceFacadeImpl
delete
class ProductPriceFacadeImpl implements ProductPriceFacade { @Autowired private ProductPriceService productPriceService; @Autowired private PricingService pricingService; @Autowired private ProductAvailabilityService productAvailabilityService; @Autowired private PersistableProductPriceMapper persistableProductPriceMapper; @Override public Long save(PersistableProductPrice price, MerchantStore store) { ProductPrice productPrice = persistableProductPriceMapper.convert(price, store, store.getDefaultLanguage()); try { if(!isPositive(productPrice.getId())) { //avoid detached entity failed to persist productPrice.getProductAvailability().setPrices(null); productPrice = productPriceService .saveOrUpdate(productPrice); } else { productPrice = productPriceService .saveOrUpdate(productPrice); } } catch (ServiceException e) { throw new ServiceRuntimeException("An exception occured while creating a ProductPrice"); } return productPrice.getId(); } @Override public List<ReadableProductPrice> list(String sku, Long inventoryId, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(sku, "Product sku cannot be null"); Validate.notNull(inventoryId, "Product inventory cannot be null"); List<ProductPrice> prices = productPriceService.findByInventoryId(inventoryId, sku, store); List<ReadableProductPrice> returnPrices = prices.stream().map(p -> { try { return this.readablePrice(p, store, language); } catch (ConversionException e) { throw new ServiceRuntimeException("An exception occured while getting product price for sku [" + sku + "] and Store [" + store.getCode() + "]", e); } }).collect(Collectors.toList()); return returnPrices; } @Override public List<ReadableProductPrice> list(String sku, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(sku, "Product sku cannot be null"); List<ProductPrice> prices = productPriceService.findByProductSku(sku, store); List<ReadableProductPrice> returnPrices = prices.stream().map(p -> { try { return this.readablePrice(p, store, language); } catch (ConversionException e) { throw new ServiceRuntimeException("An exception occured while getting product price for sku [" + sku + "] and Store [" + store.getCode() + "]", e); } }).collect(Collectors.toList()); return returnPrices; } @Override public void delete(Long priceId, String sku, MerchantStore store) {<FILL_FUNCTION_BODY>} private ReadableProductPrice readablePrice (ProductPrice price, MerchantStore store, Language language) throws ConversionException { ReadableProductPricePopulator populator = new ReadableProductPricePopulator(); populator.setPricingService(pricingService); return populator.populate(price, store, language); } @Override public ReadableProductPrice get(String sku, Long productPriceId, MerchantStore store, Language language) { Validate.notNull(productPriceId, "Product Price id cannot be null"); Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(sku, "Product sku cannot be null"); ProductPrice price = productPriceService.findById(productPriceId, sku, store); if(price == null) { throw new ResourceNotFoundException("ProductPrice with id [" + productPriceId + " not found for product sku [" + sku + "] and Store [" + store.getCode() + "]"); } try { return readablePrice(price, store, language); } catch (ConversionException e) { throw new ServiceRuntimeException("An exception occured while deleting product price [" + productPriceId + "] for product sku [" + sku + "] and Store [" + store.getCode() + "]", e); } } }
Validate.notNull(priceId, "Product Price id cannot be null"); Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(sku, "Product sku cannot be null"); ProductPrice productPrice = productPriceService.findById(priceId, sku, store); if(productPrice == null) { throw new ServiceRuntimeException("An exception occured while getting product price [" + priceId + "] for product sku [" + sku + "] and Store [" + store.getCode() + "]"); } try { productPriceService.delete(productPrice); } catch (ServiceException e) { throw new ServiceRuntimeException("An exception occured while deleting product price [" + priceId + "] for product sku [" + sku + "] and Store [" + store.getCode() + "]", e); }
1,127
230
1,357
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductTypeFacadeImpl.java
ProductTypeFacadeImpl
get
class ProductTypeFacadeImpl implements ProductTypeFacade { @Autowired private ProductTypeService productTypeService; @Autowired private ReadableProductTypeMapper readableProductTypeMapper; @Autowired private PersistableProductTypeMapper persistableProductTypeMapper; @Override public ReadableProductTypeList getByMerchant(MerchantStore store, Language language, int count, int page) { Validate.notNull(store, "MerchantStore cannot be null"); ReadableProductTypeList returnList = new ReadableProductTypeList(); try { Page<ProductType> types = productTypeService.getByMerchant(store, language, page, count); if(types != null) { returnList.setList(types.getContent().stream().map(t -> readableProductTypeMapper.convert(t, store, language)).collect(Collectors.toList())); returnList.setTotalPages(types.getTotalPages()); returnList.setRecordsTotal(types.getTotalElements()); returnList.setRecordsFiltered(types.getSize()); } return returnList; } catch (Exception e) { throw new ServiceRuntimeException( "An exception occured while getting product types for merchant[ " + store.getCode() + "]", e); } } @Override public ReadableProductType get(MerchantStore store, Long id, Language language) {<FILL_FUNCTION_BODY>} @Override public Long save(PersistableProductType type, MerchantStore store, Language language) { Validate.notNull(type,"ProductType cannot be null"); Validate.notNull(store,"MerchantStore cannot be null"); Validate.notNull(type.getCode(),"ProductType code cannot be empty"); try { if(this.exists(type.getCode(), store, language)) { throw new OperationNotAllowedException( "Product type [" + type.getCode() + "] already exist for store [" + store.getCode() + "]"); } ProductType model = persistableProductTypeMapper.convert(type, store, language); model.setMerchantStore(store); ProductType saved = productTypeService.saveOrUpdate(model); return saved.getId(); } catch(Exception e) { throw new ServiceRuntimeException( "An exception occured while saving product type",e); } } @Override public void update(PersistableProductType type, Long id, MerchantStore store, Language language) { Validate.notNull(type,"ProductType cannot be null"); Validate.notNull(store,"MerchantStore cannot be null"); Validate.notNull(id,"id cannot be empty"); try { ProductType t = productTypeService.getById(id, store, language); if(t == null) { throw new ResourceNotFoundException( "Product type [" + type.getCode() + "] does not exist for store [" + store.getCode() + "]"); } type.setId(t.getId()); type.setCode(t.getCode()); ProductType model = persistableProductTypeMapper.merge(type, t, store, language); model.setMerchantStore(store); productTypeService.saveOrUpdate(model); } catch(Exception e) { throw new ServiceRuntimeException( "An exception occured while saving product type",e); } } @Override public void delete(Long id, MerchantStore store, Language language) { Validate.notNull(store,"MerchantStore cannot be null"); Validate.notNull(id,"id cannot be empty"); try { ProductType t = productTypeService.getById(id, store, language); if(t == null) { throw new ResourceNotFoundException( "Product type [" + id + "] does not exist for store [" + store.getCode() + "]"); } productTypeService.delete(t); } catch(Exception e) { throw new ServiceRuntimeException( "An exception occured while saving product type",e); } } @Override public boolean exists(String code, MerchantStore store, Language language) { ProductType t; try { t = productTypeService.getByCode(code, store, language); } catch (ServiceException e) { throw new RuntimeException("An exception occured while getting product type [" + code + "] for merchant store [" + store.getCode() +"]",e); } if(t != null) { return true; } return false; } @Override public ReadableProductType get(MerchantStore store, String code, Language language) { ProductType t; try { t = productTypeService.getByCode(code, store, language); } catch (ServiceException e) { throw new RuntimeException("An exception occured while getting product type [" + code + "] for merchant store [" + store.getCode() +"]",e); } if(t == null) { throw new ResourceNotFoundException("Product type [" + code + "] not found for merchant [" + store.getCode() + "]"); } ReadableProductType readableType = readableProductTypeMapper.convert(t, store, language); return readableType; } }
Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(id, "ProductType code cannot be empty"); try { ProductType type = null; if(language == null) { type = productTypeService.getById(id, store); } else { type = productTypeService.getById(id, store, language); } if(type == null) { throw new ResourceNotFoundException("Product type [" + id + "] not found for store [" + store.getCode() + "]"); } ReadableProductType readableType = readableProductTypeMapper.convert(type, store, language); return readableType; } catch(Exception e) { throw new ServiceRuntimeException( "An exception occured while getting product type [" + id + "] not found for store [" + store.getCode() + "]", e); }
1,387
247
1,634
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductVariantFacadeImpl.java
ProductVariantFacadeImpl
update
class ProductVariantFacadeImpl implements ProductVariantFacade { @Autowired private ReadableProductVariantMapper readableProductVariantMapper; @Autowired private PersistableProductVariantMapper persistableProductVariantMapper; @Autowired private ProductVariantService productVariantService; @Autowired private ProductVariationService productVariationService; @Autowired private ProductFacade productFacade; @Autowired private ProductCommonFacade productCommonFacade; @Override public ReadableProductVariant get(Long instanceId, Long productId, MerchantStore store, Language language) { Optional<ProductVariant> productVariant = this.getproductVariant(instanceId, productId, store); if(productVariant.isEmpty()) { throw new ResourceNotFoundException("Product instance + [" + instanceId + "] not found for store [" + store.getCode() + "]"); } ProductVariant model = productVariant.get(); return readableProductVariantMapper.convert(model, store, language); } @Override public boolean exists(String sku, MerchantStore store, Long productId, Language language) { ReadableProduct product = null; try { product = productCommonFacade.getProduct(store, productId, language); } catch (Exception e) { throw new ServiceRuntimeException("Error while getting product [" + productId + "]",e); } return productVariantService.exist(sku,product.getId()); } @Override public Long create(PersistableProductVariant productVariant, Long productId, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(productVariant, "productVariant cannot be null"); Validate.notNull(productId, "Product id cannot be null"); //variation and variation value should not be of same product option code if( productVariant.getVariation() != null && productVariant.getVariation().longValue() > 0 && productVariant.getVariationValue() != null && productVariant.getVariationValue().longValue() > 0) { List<ProductVariation> variations = productVariationService.getByIds(Arrays.asList(productVariant.getVariation(),productVariant.getVariationValue()), store); boolean differentOption = variations.stream().map(i -> i.getProductOption().getCode()).distinct().count() > 1; if(!differentOption) { throw new ConstraintException("Product option of instance.variant and instance.variantValue must be different"); } } productVariant.setProductId(productId); productVariant.setId(null); ProductVariant variant = persistableProductVariantMapper.convert(productVariant, store, language); try { productVariantService.saveProductVariant(variant); } catch (ServiceException e) { throw new ServiceRuntimeException("Cannot save product instance for store [" + store.getCode() + "] and productId [" + productId + "]", e); } return variant.getId(); } @Override public void update(Long instanceId, PersistableProductVariant productVariant, Long productId, MerchantStore store, Language language) {<FILL_FUNCTION_BODY>} private Optional<ProductVariant> getproductVariant(Long id, Long productId, MerchantStore store) { return productVariantService.getById(id, productId, store); } @Override public void delete(Long productVariant, Long productId, MerchantStore store) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(productVariant, "productVariant id cannot be null"); Validate.notNull(productId, "Product id cannot be null"); Optional<ProductVariant> instanceModel = this.getproductVariant(productVariant, productId, store); if(instanceModel.isEmpty()) { throw new ResourceNotFoundException("productVariant with id [" + productVariant + "] not found for store [" + store.getCode() + "] and productId [" + productId + "]"); } try { productVariantService.delete(instanceModel.get()); } catch (ServiceException e) { throw new ServiceRuntimeException("Cannot delete product instance [" + productVariant + "] for store [" + store.getCode() + "] and productId [" + productId + "]", e); } } @Override public ReadableEntityList<ReadableProductVariant> list(Long productId, MerchantStore store, Language language, int page, int count) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(productId, "Product id cannot be null"); Product product = productFacade.getProduct(productId, store); if(product == null) { throw new ResourceNotFoundException("Product with id [" + productId + "] not found for store [" + store.getCode() + "]"); } Page<ProductVariant> instances = productVariantService.getByProductId(store, product, language, page, count); List<ReadableProductVariant> readableInstances = instances.stream() .map(rp -> this.readableProductVariantMapper.convert(rp, store, language)).collect(Collectors.toList()); return createReadableList(instances, readableInstances); } }
Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(productVariant, "productVariant cannot be null"); Validate.notNull(productId, "Product id cannot be null"); Validate.notNull(instanceId, "Product instance id cannot be null"); Optional<ProductVariant> instanceModel = this.getproductVariant(instanceId, productId, store); if(instanceModel.isEmpty()) { throw new ResourceNotFoundException("productVariant with id [" + instanceId + "] not found for store [" + store.getCode() + "] and productId [" + productId + "]"); } productVariant.setProductId(productId); ProductVariant mergedModel = persistableProductVariantMapper.merge(productVariant, instanceModel.get(), store, language); try { productVariantService.saveProductVariant(mergedModel); } catch (ServiceException e) { throw new ServiceRuntimeException("Cannot save product instance for store [" + store.getCode() + "] and productId [" + productId + "]", e); }
1,463
294
1,757
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductVariantGroupFacadeImpl.java
ProductVariantGroupFacadeImpl
addImage
class ProductVariantGroupFacadeImpl implements ProductVariantGroupFacade { @Autowired private ProductVariantGroupService productVariantGroupService; @Autowired private ProductVariantService productVariantService; @Autowired private ProductVariantImageService productVariantImageService; @Autowired private PersistableProductVariantGroupMapper persistableProductIntanceGroupMapper; @Autowired private ReadableProductVariantGroupMapper readableProductVariantGroupMapper; @Autowired private ContentService contentService; //file management @Override public ReadableProductVariantGroup get(Long instanceGroupId, MerchantStore store, Language language) { ProductVariantGroup group = this.group(instanceGroupId, store); return readableProductVariantGroupMapper.convert(group, store, language); } @Override public Long create(PersistableProductVariantGroup productVariantGroup, MerchantStore store, Language language) { ProductVariantGroup group = persistableProductIntanceGroupMapper.convert(productVariantGroup, store, language); try { group = productVariantGroupService.saveOrUpdate(group); } catch (ServiceException e) { throw new ServiceRuntimeException("Cannot save product instance group [" + productVariantGroup + "] for store [" + store.getCode() + "]"); } return group.getId(); } @Override public void update(Long productVariantGroup, PersistableProductVariantGroup instance, MerchantStore store, Language language) { ProductVariantGroup group = this.group(productVariantGroup, store); instance.setId(productVariantGroup); group = persistableProductIntanceGroupMapper.merge(instance, group, store, language); try { productVariantGroupService.saveOrUpdate(group); } catch (ServiceException e) { throw new ServiceRuntimeException("Cannot save product instance group [" + productVariantGroup + "] for store [" + store.getCode() + "]"); } } @Override public void delete(Long productVariantGroup, Long productId, MerchantStore store) { ProductVariantGroup group = this.group(productVariantGroup, store); if(group == null) { throw new ResourceNotFoundException("Product instance group [" + group.getId() + " not found for store [" + store.getCode() + "]"); } try { //null all group from instances for(ProductVariant instance : group.getProductVariants()) { Optional<ProductVariant> p = productVariantService.getById(instance.getId(), store); if(p.isEmpty()) { throw new ResourceNotFoundException("Product instance [" + instance.getId() + " not found for store [" + store.getCode() + "]"); } instance.setProductVariantGroup(null); productVariantService.save(instance); } //now delete productVariantGroupService.delete(group); } catch (ServiceException e) { throw new ServiceRuntimeException("Cannot remove product instance group [" + productVariantGroup + "] for store [" + store.getCode() + "]"); } } @Override public ReadableEntityList<ReadableProductVariantGroup> list(Long productId, MerchantStore store, Language language, int page, int count) { Page<ProductVariantGroup> groups = productVariantGroupService.getByProductId(store, productId, language, page, count); List<ReadableProductVariantGroup> readableInstances = groups.stream() .map(rp -> this.readableProductVariantGroupMapper.convert(rp, store, language)).collect(Collectors.toList()); return createReadableList(groups, readableInstances); } private ProductVariantGroup group(Long productOptionGroupId,MerchantStore store) { Optional<ProductVariantGroup> group = productVariantGroupService.getById(productOptionGroupId, store); if(group.isEmpty()) { throw new ResourceNotFoundException("Product instance group [" + productOptionGroupId + "] not found"); } return group.get(); } @Override public void addImage(MultipartFile image, Long instanceGroupId, MerchantStore store, Language language) {<FILL_FUNCTION_BODY>} @Override public void removeImage(Long imageId, Long productVariantGroupId, MerchantStore store) { Validate.notNull(productVariantGroupId,"productVariantGroupId must not be null"); Validate.notNull(store,"MerchantStore must not be null"); ProductVariantImage image = productVariantImageService.getById(imageId); if(image == null) { throw new ResourceNotFoundException("productVariantImage [" + imageId + "] was not found"); } ProductVariantGroup group = this.group(productVariantGroupId, store); try { contentService.removeFile(Constants.SLASH + store.getCode() + Constants.SLASH + productVariantGroupId, FileContentType.VARIANT, image.getProductImage()); group.getImages().removeIf(i -> (i.getId() == image.getId())); //update productVariantroup productVariantGroupService.update(group); } catch (ServiceException e) { throw new ServiceRuntimeException("An exception occured while removing instance image [" + imageId + "]",e); } } }
Validate.notNull(instanceGroupId,"productVariantGroupId must not be null"); Validate.notNull(image,"Image must not be null"); Validate.notNull(store,"MerchantStore must not be null"); //get option group ProductVariantGroup group = this.group(instanceGroupId, store); ProductVariantImage instanceImage = new ProductVariantImage(); try { String path = new StringBuilder().append("group").append(Constants.SLASH).append(instanceGroupId).toString(); instanceImage.setProductImage(image.getOriginalFilename()); instanceImage.setProductVariantGroup(group); String imageName = image.getOriginalFilename(); InputStream inputStream = image.getInputStream(); InputContentFile cmsContentImage = new InputContentFile(); cmsContentImage.setFileName(imageName); cmsContentImage.setMimeType(image.getContentType()); cmsContentImage.setFile(inputStream); cmsContentImage.setPath(path); cmsContentImage.setFileContentType(FileContentType.VARIANT); contentService.addContentFile(store.getCode(), cmsContentImage); group.getImages().add(instanceImage); productVariantGroupService.saveOrUpdate(group); } catch (Exception e) { throw new ServiceRuntimeException("Exception while adding instance group image", e); } return;
1,425
388
1,813
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductVariationFacadeImpl.java
ProductVariationFacadeImpl
delete
class ProductVariationFacadeImpl implements ProductVariationFacade { @Autowired private PersistableProductVariationMapper persistableProductVariationMapper; @Autowired private ReadableProductVariationMapper readableProductVariationMapper; @Autowired private ProductVariationService productVariationService; @Override public ReadableProductVariation get(Long variationId, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Optional<ProductVariation> variation = productVariationService.getById(store, variationId, language); if(variation.isEmpty()) { throw new ResourceNotFoundException("ProductVariation not found for id [" + variationId +"] and store [" + store.getCode() + "]"); } return readableProductVariationMapper.convert(variation.get(), store, language); } @Override public ReadableEntityList<ReadableProductVariation> list(MerchantStore store, Language language, int page, int count) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Page<ProductVariation> vars = productVariationService.getByMerchant(store, language, null, page, count); List<ReadableProductVariation> variations = vars.stream().map(opt -> this.convert(opt, store, language)).collect(Collectors.toList()); ReadableEntityList<ReadableProductVariation> returnList = new ReadableEntityList<ReadableProductVariation>(); returnList.setItems(variations); returnList.setNumber(variations.size()); returnList.setRecordsTotal(vars.getTotalElements()); returnList.setTotalPages(vars.getTotalPages()); return returnList; } private ReadableProductVariation convert(ProductVariation var, MerchantStore store, Language language) { return readableProductVariationMapper.convert(var, store, language); } @Override public Long create(PersistableProductVariation var, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Validate.notNull(var, "PersistableProductVariation cannot be null"); if(this.exists(var.getCode(), store)) { throw new OperationNotAllowedException("Option set with code [" + var.getCode() + "] already exist"); } ProductVariation p = persistableProductVariationMapper.convert(var, store, language); p.setMerchantStore(store); try { productVariationService.saveOrUpdate(p); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while creating ProductOptionSet", e); } return p.getId(); } @Override public void update(Long variationId, PersistableProductVariation var, MerchantStore store, Language language) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(language, "Language cannot be null"); Validate.notNull(var, "PersistableProductVariation cannot be null"); Optional<ProductVariation> p = productVariationService.getById(store, variationId, language); if(p.isEmpty()) { throw new ResourceNotFoundException("ProductVariation not found for id [" + variationId +"] and store [" + store.getCode() + "]"); } ProductVariation productVariant = p.get(); productVariant.setId(variationId); productVariant.setCode(var.getCode()); ProductVariation model = persistableProductVariationMapper.merge(var, productVariant, store, language); try { model.setMerchantStore(store); productVariationService.save(model); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while creating ProductVariation", e); } } @Override public void delete(Long variationId, MerchantStore store) {<FILL_FUNCTION_BODY>} @Override public boolean exists(String code, MerchantStore store) { Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(code, "code cannot be null"); Optional<ProductVariation> var = productVariationService.getByCode(store, code); if(var.isPresent()) { return true; } return false; } }
Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(variationId, "variationId cannot be null"); ProductVariation opt = productVariationService.getById(variationId); if(opt == null) { throw new ResourceNotFoundException("ProductVariation not found for id [" + variationId +"] and store [" + store.getCode() + "]"); } if(!opt.getMerchantStore().getCode().equals(store.getCode())) { throw new ResourceNotFoundException("ProductVariation not found for id [" + variationId +"] and store [" + store.getCode() + "]"); } try { productVariationService.delete(opt); } catch (ServiceException e) { throw new ServiceRuntimeException("Exception while deleting ProductVariation", e); }
1,200
219
1,419
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/facade/shoppingCart/ShoppingCartFacadeImpl.java
ShoppingCartFacadeImpl
get
class ShoppingCartFacadeImpl implements ShoppingCartFacade { @Autowired private CustomerService customerService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private com.salesmanager.shop.store.controller.customer.facade.CustomerFacade customerFacade; @Autowired private com.salesmanager.shop.store.controller.shoppingCart.facade.ShoppingCartFacade shoppingCartFacade; // legacy // facade @Override public ReadableShoppingCart get(Optional<String> cart, Long customerId, MerchantStore store, Language language) {<FILL_FUNCTION_BODY>} }
Validate.notNull(customerId, "Customer id cannot be null"); Validate.notNull(store, "MerchantStore cannot be null"); try { // lookup customer Customer customer = customerService.getById(customerId); if (customer == null) { throw new ResourceNotFoundException("No Customer found for id [" + customerId + "]"); } ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer, store); if(cart.isPresent()) { cartModel = customerFacade.mergeCart(customer, cart.get(), store, language); } if(cartModel == null) { return null; } ReadableShoppingCart readableCart = shoppingCartFacade.readableCart(cartModel, store, language); return readableCart; } catch (Exception e) { throw new ServiceRuntimeException(e); }
171
256
427
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/model/paging/PaginationData.java
PaginationData
getPageNumber
class PaginationData implements Serializable { private static final long serialVersionUID = 1L; /** The number of results per page.*/ private int pageSize; private int currentPage; private int offset ; private int totalCount; private int totalPages; private int countByPage; public PaginationData(int pageSize,int currentPage) { if (pageSize == 0) throw new IllegalArgumentException("limit cannot be 0 for pagination."); this.pageSize = pageSize; this.currentPage=currentPage; } public int getPageSize() { return pageSize; } /** * The current page number this pagination object represents * * @return the page number */ public int getPageNumber() {<FILL_FUNCTION_BODY>} /** * The offset for this pagination object. The offset determines what index (0 index) to start retrieving results from. * * @return the offset */ public int getOffset() { return (currentPage - 1) * pageSize + 1; } /** * Creates a new pagination object representing the next page * * @return new pagination object with offset shifted by offset+limit */ public PaginationData getNext() { return new PaginationData( offset + pageSize, pageSize ); } /** * Creates a new pagination object representing the previous page * * @return new pagination object with offset shifted by offset-limit */ public PaginationData getPrevious() { if (pageSize >= offset) { return new PaginationData(0, pageSize); } else { return new PaginationData(offset - pageSize, pageSize); } } public int getCurrentPage() { return currentPage; } public void setCurrentPage( int currentPage ) { this.currentPage = currentPage; } public int getTotalCount() { return totalCount; } public void setTotalCount( int totalCount ) { this.totalCount = totalCount; } public int getTotalPages() { Integer totalPages= Integer.valueOf((int) (Math.ceil(Integer.valueOf(totalCount).doubleValue() / pageSize))); return totalPages; } public int getCountByPage() { return countByPage; } public void setCountByPage(int countByPage) { this.countByPage = countByPage; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } }
if (offset < pageSize || pageSize == 0) return 1; return (offset / pageSize) + 1;
737
36
773
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/model/search/AutoCompleteRequest.java
AutoCompleteRequest
toJSONString
class AutoCompleteRequest { private String merchantCode; private String languageCode; private final static String WILDCARD_QUERY = "wildcard"; private final static String KEYWORD = "keyword"; private final static String UNDERSCORE = "_"; private final static String ALL = "*"; private final static String TYPE = "type"; private final static String ANALYZER = "analyzer"; private final static String STD_ANALYZER = "standard"; private final static String TYPE_PHRASE = "phrase_prefix"; private final static String QUERY = "query"; private final static String MATCH = "match"; public AutoCompleteRequest(String merchantCode, String languageCode) { this.merchantCode = merchantCode; this.languageCode = languageCode; } @SuppressWarnings("unchecked") @Deprecated public String toJSONString(String query) {<FILL_FUNCTION_BODY>} /** keyword_en_default **/ public String getCollectionName() { StringBuilder qBuilder = new StringBuilder(); qBuilder.append(KEYWORD).append(UNDERSCORE).append(getLanguageCode()).append(UNDERSCORE) .append(getMerchantCode()); return qBuilder.toString().toLowerCase(); } public String getMerchantCode() { return merchantCode; } public void setMerchantCode(String merchantCode) { this.merchantCode = merchantCode; } public String getLanguageCode() { return languageCode; } public void setLanguageCode(String languageCode) { this.languageCode = languageCode; } }
//{"size": 10,"query": {"match": {"keyword": {"query": "wat","operator":"and"}}}}"; JSONObject keyword = new JSONObject(); JSONObject q = new JSONObject(); JSONObject mq = new JSONObject(); JSONObject match = new JSONObject(); q.put(QUERY, query); q.put(ANALYZER, STD_ANALYZER); keyword.put(KEYWORD, q); match.put(MATCH, keyword); mq.put(QUERY, match); return mq.toJSONString();
415
173
588
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/AbstractCustomerServices.java
AbstractCustomerServices
loadUserByUsername
class AbstractCustomerServices implements UserDetailsService{ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCustomerServices.class); protected CustomerService customerService; protected PermissionService permissionService; protected GroupService groupService; public final static String ROLE_PREFIX = "ROLE_";//Spring Security 4 public AbstractCustomerServices( CustomerService customerService, PermissionService permissionService, GroupService groupService) { this.customerService = customerService; this.permissionService = permissionService; this.groupService = groupService; } protected abstract UserDetails userDetails(String userName, Customer customer, Collection<GrantedAuthority> authorities); public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {<FILL_FUNCTION_BODY>} }
Customer user = null; Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); try { LOGGER.debug("Loading user by user id: {}", userName); user = customerService.getByNick(userName); if(user==null) { //return null; throw new UsernameNotFoundException("User " + userName + " not found"); } GrantedAuthority role = new SimpleGrantedAuthority(ROLE_PREFIX + Constants.PERMISSION_CUSTOMER_AUTHENTICATED);//required to login authorities.add(role); List<Integer> groupsId = new ArrayList<Integer>(); List<Group> groups = user.getGroups(); for(Group group : groups) { groupsId.add(group.getId()); } if(CollectionUtils.isNotEmpty(groupsId)) { List<Permission> permissions = permissionService.getPermissions(groupsId); for(Permission permission : permissions) { GrantedAuthority auth = new SimpleGrantedAuthority(permission.getPermissionName()); authorities.add(auth); } } } catch (ServiceException e) { LOGGER.error("Exception while querrying customer",e); throw new SecurityDataAccessException("Cannot authenticate customer",e); } return userDetails(userName, user, authorities);
228
392
620
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/AuthenticationTokenFilter.java
AuthenticationTokenFilter
doFilterInternal
class AuthenticationTokenFilter extends OncePerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationTokenFilter.class); @Value("${authToken.header}") private String tokenHeader; private final static String BEARER_TOKEN ="Bearer "; private final static String FACEBOOK_TOKEN ="FB "; //private final static String privateApiPatternString = "/api/v*/private"; //private final static Pattern pattern = Pattern.compile(privateApiPatternString); @Inject private CustomAuthenticationManager jwtCustomCustomerAuthenticationManager; @Inject private CustomAuthenticationManager jwtCustomAdminAuthenticationManager; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<FILL_FUNCTION_BODY>} private void postFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { UserContext userContext = UserContext.getCurrentInstance(); if(userContext!=null) { userContext.close(); } } catch(Exception s) { LOGGER.error("Error while getting ip address ", s); } } }
String origin = "*"; if(!StringUtils.isBlank(request.getHeader("origin"))) { origin = request.getHeader("origin"); } //in flight response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH"); response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Headers", "X-Auth-Token, Content-Type, Authorization, Cache-Control, X-Requested-With"); response.setHeader("Access-Control-Allow-Credentials", "true"); try { String ipAddress = GeoLocationUtils.getClientIpAddress(request); UserContext userContext = UserContext.create(); userContext.setIpAddress(ipAddress); } catch(Exception s) { LOGGER.error("Error while getting ip address ", s); } String requestUrl = request.getRequestURL().toString(); if(requestUrl.contains("/api/v1/auth")) { //setHeader(request,response); final String requestHeader = request.getHeader(this.tokenHeader);//token try { if (requestHeader != null && requestHeader.startsWith(BEARER_TOKEN)) {//Bearer jwtCustomCustomerAuthenticationManager.authenticateRequest(request, response); } else if(requestHeader != null && requestHeader.startsWith(FACEBOOK_TOKEN)) { //Facebook //facebookCustomerAuthenticationManager.authenticateRequest(request, response); } else { LOGGER.warn("couldn't find any authorization token, will ignore the header"); } } catch(Exception e) { throw new ServletException(e); } } if(requestUrl.contains("/api/v1/private") || requestUrl.contains("/api/v2/private")) { //setHeader(request,response); Enumeration<String> headers = request.getHeaderNames(); //while(headers.hasMoreElements()) { //LOGGER.debug(headers.nextElement()); //} final String requestHeader = request.getHeader(this.tokenHeader);//token try { if (requestHeader != null && requestHeader.startsWith(BEARER_TOKEN)) {//Bearer jwtCustomAdminAuthenticationManager.authenticateRequest(request, response); } else { LOGGER.warn("couldn't find any authorization token, will ignore the header, might be a preflight check"); } } catch(Exception e) { throw new ServletException(e); } } chain.doFilter(request, response); postFilter(request, response, chain);
358
805
1,163
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/CustomerServicesImpl.java
CustomerServicesImpl
userDetails
class CustomerServicesImpl extends AbstractCustomerServices{ private static final Logger LOGGER = LoggerFactory.getLogger(CustomerServicesImpl.class); private CustomerService customerService; private PermissionService permissionService; private GroupService groupService; @Inject public CustomerServicesImpl(CustomerService customerService, PermissionService permissionService, GroupService groupService) { super(customerService, permissionService, groupService); this.customerService = customerService; this.permissionService = permissionService; this.groupService = groupService; } @Override protected UserDetails userDetails(String userName, Customer customer, Collection<GrantedAuthority> authorities) {<FILL_FUNCTION_BODY>} }
CustomerDetails authUser = new CustomerDetails(userName, customer.getPassword(), true, true, true, true, authorities); authUser.setEmail(customer.getEmailAddress()); authUser.setId(customer.getId()); return authUser;
185
75
260
<methods>public void <init>(com.salesmanager.core.business.services.customer.CustomerService, com.salesmanager.core.business.services.user.PermissionService, com.salesmanager.core.business.services.user.GroupService) ,public UserDetails loadUserByUsername(java.lang.String) throws UsernameNotFoundException, org.springframework.dao.DataAccessException<variables>private static final org.slf4j.Logger LOGGER,public static final java.lang.String ROLE_PREFIX,protected com.salesmanager.core.business.services.customer.CustomerService customerService,protected com.salesmanager.core.business.services.user.GroupService groupService,protected com.salesmanager.core.business.services.user.PermissionService permissionService
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/JWTTokenUtil.java
JWTTokenUtil
canTokenBeRefreshedWithGrace
class JWTTokenUtil implements Serializable { /** * */ private static final long serialVersionUID = 1L; static final int GRACE_PERIOD = 200; static final String CLAIM_KEY_USERNAME = "sub"; static final String CLAIM_KEY_AUDIENCE = "aud"; static final String CLAIM_KEY_CREATED = "iat"; static final String AUDIENCE_UNKNOWN = "unknown"; static final String AUDIENCE_API = "api"; static final String AUDIENCE_WEB = "web"; static final String AUDIENCE_MOBILE = "mobile"; static final String AUDIENCE_TABLET = "tablet"; @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String getUsernameFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } public Date getIssuedAtDateFromToken(String token) { return getClaimFromToken(token, Claims::getIssuedAt); } public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token, Claims::getExpiration); } public String getAudienceFromToken(String token) { return getClaimFromToken(token, Claims::getAudience); } public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { final Claims claims = getAllClaimsFromToken(token); return claimsResolver.apply(claims); } private Claims getAllClaimsFromToken(String token) { return Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(DateUtil.getDate()); } private Boolean isTokenExpiredWithGrace(String token) { Date expiration = getExpirationDateFromToken(token); expiration = addSeconds(expiration,GRACE_PERIOD); return expiration.before(DateUtil.getDate()); } private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) { return (lastPasswordReset != null && created.before(lastPasswordReset)); } private Boolean isCreatedBeforeLastPasswordResetWithGrace(Date created, Date lastPasswordReset) { return (lastPasswordReset != null && created.before(addSeconds(lastPasswordReset,GRACE_PERIOD))); } private Date addSeconds(Date date, Integer seconds) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.SECOND, seconds); return cal.getTime(); } private String generateAudience() { return AUDIENCE_API; } private Boolean ignoreTokenExpiration(String token) { String audience = getAudienceFromToken(token); return (AUDIENCE_TABLET.equals(audience) || AUDIENCE_MOBILE.equals(audience)); } public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername(), generateAudience()); } private String doGenerateToken(Map<String, Object> claims, String subject, String audience) { final Date createdDate = DateUtil.getDate(); final Date expirationDate = calculateExpirationDate(createdDate); System.out.println("doGenerateToken " + createdDate); return Jwts.builder() .setClaims(claims) .setSubject(subject) .setAudience(audience) .setIssuedAt(createdDate) .setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public Boolean canTokenBeRefreshedWithGrace(String token, Date lastPasswordReset) {<FILL_FUNCTION_BODY>} public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) { final Date created = getIssuedAtDateFromToken(token); return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset) && (!isTokenExpired(token) || ignoreTokenExpiration(token)); } public String refreshToken(String token) { final Date createdDate = DateUtil.getDate(); final Date expirationDate = calculateExpirationDate(createdDate); final Claims claims = getAllClaimsFromToken(token); claims.setIssuedAt(createdDate); claims.setExpiration(expirationDate); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public Boolean validateToken(String token, UserDetails userDetails) { JWTUser user = (JWTUser) userDetails; final String username = getUsernameFromToken(token); final Date created = getIssuedAtDateFromToken(token); //final Date expiration = getExpirationDateFromToken(token); boolean usernameEquals = username.equals(user.getUsername()); boolean isTokenExpired = isTokenExpired(token); boolean isTokenCreatedBeforeLastPasswordReset = isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate()); return ( usernameEquals && !isTokenExpired && !isTokenCreatedBeforeLastPasswordReset ); } private Date calculateExpirationDate(Date createdDate) { return new Date(createdDate.getTime() + expiration * 1000); } }
final Date created = getIssuedAtDateFromToken(token); boolean t = isCreatedBeforeLastPasswordResetWithGrace(created, lastPasswordReset); boolean u = isTokenExpiredWithGrace(token); boolean v = ignoreTokenExpiration(token); System.out.println(t + " " + u + " " + v); System.out.println(!isCreatedBeforeLastPasswordResetWithGrace(created, lastPasswordReset) && (!isTokenExpiredWithGrace(token) || ignoreTokenExpiration(token))); //return !isCreatedBeforeLastPasswordResetWithGrace(created, lastPasswordReset) // && (!isTokenExpired(token) || ignoreTokenExpiration(token)); return true;
1,565
180
1,745
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/RestAuthenticationEntryPoint.java
RestAuthenticationEntryPoint
afterPropertiesSet
class RestAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean, Ordered { private String realmName = "rest-realm"; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); } @Override public int getOrder() { return 1; } @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} }
if ((realmName == null) || "".equals(realmName)) { throw new IllegalArgumentException("realmName must be specified"); }
149
41
190
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/ServicesAuthenticationEntryPoint.java
ServicesAuthenticationEntryPoint
afterPropertiesSet
class ServicesAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean, Ordered { private String realmName = "services-realm"; @Override public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException{ response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); } @Override public int getOrder() { return 0; } @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} }
if ((realmName == null) || "".equals(realmName)) { throw new IllegalArgumentException("realmName must be specified"); }
143
43
186
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/ServicesAuthenticationSuccessHandler.java
ServicesAuthenticationSuccessHandler
onAuthenticationSuccess
class ServicesAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private RequestCache requestCache = new HttpSessionRequestCache(); @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {<FILL_FUNCTION_BODY>} public void setRequestCache(RequestCache requestCache) { this.requestCache = requestCache; } }
SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest == null) { clearAuthenticationAttributes(request); return; } String targetUrlParam = getTargetUrlParameter(); if (isAlwaysUseDefaultTargetUrl() || (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) { requestCache.removeRequest(request, response); clearAuthenticationAttributes(request); return; } clearAuthenticationAttributes(request);
106
134
240
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/SocialCustomerServicesImpl.java
SocialCustomerServicesImpl
loadUserByUsername
class SocialCustomerServicesImpl implements UserDetailsService{ @Inject UserDetailsService customerDetailsService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<FILL_FUNCTION_BODY>} }
//delegates to Customer fetch service UserDetails userDetails = customerDetailsService.loadUserByUsername(username); if (userDetails == null) { return null; } return userDetails;
64
59
123
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/admin/JWTAdminAuthenticationManager.java
JWTAdminAuthenticationManager
attemptAuthentication
class JWTAdminAuthenticationManager extends CustomAuthenticationManager { protected final Log logger = LogFactory.getLog(getClass()); private static final String BEARER = "Bearer"; @Inject private JWTTokenUtil jwtTokenUtil; @Inject private UserDetailsService jwtAdminDetailsService; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {<FILL_FUNCTION_BODY>} @Override public void successfullAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws AuthenticationException { // TODO Auto-generated method stub } @Override public void unSuccessfullAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // TODO Auto-generated method stub } }
final String requestHeader = request.getHeader(super.getTokenHeader());// token String username = null; final String authToken; authToken = ofNullable(requestHeader).map(value -> removeStart(value, BEARER)).map(String::trim) .orElseThrow(() -> new CustomAuthenticationException("Missing Authentication Token")); try { username = jwtTokenUtil.getUsernameFromToken(authToken); } catch (IllegalArgumentException e) { logger.error("an error occured during getting username from token", e); } catch (ExpiredJwtException e) { logger.warn("the token is expired and not valid anymore", e); } UsernamePasswordAuthenticationToken authentication = null; logger.info("checking authentication for user " + username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { // It is not compelling necessary to load the use details from the database. You could also // store the information // in the token and read it from it. It's up to you ;) UserDetails userDetails = this.jwtAdminDetailsService.loadUserByUsername(username); // For simple validation it is completely sufficient to just check the token integrity. You // don't have to call // the database compellingly. Again it's up to you ;) if (userDetails != null && jwtTokenUtil.validateToken(authToken, userDetails)) { authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); logger.info("authenticated user " + username + ", setting security context"); // SecurityContextHolder.getContext().setAuthentication(authentication); } } return authentication;
217
458
675
<methods>public non-sealed void <init>() ,public abstract Authentication attemptAuthentication(HttpServletRequest, HttpServletResponse) throws AuthenticationException, java.lang.Exception,public void authenticateRequest(HttpServletRequest, HttpServletResponse) throws java.lang.Exception,public java.lang.String getTokenHeader() ,public void setTokenHeader(java.lang.String) ,public abstract void successfullAuthentication(HttpServletRequest, HttpServletResponse, Authentication) throws AuthenticationException,public abstract void unSuccessfullAuthentication(HttpServletRequest, HttpServletResponse) throws AuthenticationException<variables>protected final org.apache.commons.logging.Log logger,private java.lang.String tokenHeader
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/admin/JWTAdminAuthenticationProvider.java
JWTAdminAuthenticationProvider
authenticate
class JWTAdminAuthenticationProvider extends DaoAuthenticationProvider { @Autowired private UserDetailsService jwtAdminDetailsService; @Inject private PasswordEncoder passwordEncoder; public UserDetailsService getJwtAdminDetailsService() { return jwtAdminDetailsService; } public void setJwtAdminDetailsService(UserDetailsService jwtAdminDetailsService) { this.jwtAdminDetailsService = jwtAdminDetailsService; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException {<FILL_FUNCTION_BODY>} private boolean passwordMatch(String rawPassword, String user) { return passwordEncoder.matches(rawPassword, user); } @Override public boolean supports(Class<?> authentication) { return true; } }
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String name = auth.getName(); Object credentials = auth.getCredentials(); UserDetails user = jwtAdminDetailsService.loadUserByUsername(name); if (user == null) { throw new BadCredentialsException("Username/Password does not match for " + auth.getPrincipal()); } String pass = credentials.toString(); String usr = name; if(!passwordMatch(pass, usr)) { throw new BadCredentialsException("Username/Password does not match for " + auth.getPrincipal()); } /** * username password auth */ return new UsernamePasswordAuthenticationToken(user, credentials, user.getAuthorities());
240
223
463
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/admin/JWTAdminServicesImpl.java
JWTAdminServicesImpl
loadUserByUsername
class JWTAdminServicesImpl implements UserDetailsService{ private static final Logger LOGGER = LoggerFactory.getLogger(JWTAdminServicesImpl.class); @Inject private UserService userService; @Inject private PermissionService permissionService; @Inject private GroupService groupService; public final static String ROLE_PREFIX = "ROLE_";//Spring Security 4 private UserDetails userDetails(String userName, User user, Collection<GrantedAuthority> authorities) { AuditSection section = null; section = user.getAuditSection(); Date lastModified = null; //if(section != null) {//does not represent password change // lastModified = section.getDateModified(); //} return new JWTUser( user.getId(), userName, user.getFirstName(), user.getLastName(), user.getAdminEmail(), user.getAdminPassword(), authorities, true, lastModified ); } @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {<FILL_FUNCTION_BODY>} }
User user = null; Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); try { LOGGER.debug("Loading user by user id: {}", userName); user = userService.getByUserName(userName); if(user==null) { //return null; throw new UsernameNotFoundException("User " + userName + " not found"); } GrantedAuthority role = new SimpleGrantedAuthority(ROLE_PREFIX + Constants.PERMISSION_AUTHENTICATED);//required to login authorities.add(role); List<Integer> groupsId = new ArrayList<Integer>(); List<Group> groups = user.getGroups(); for(Group group : groups) { groupsId.add(group.getId()); } if(CollectionUtils.isNotEmpty(groupsId)) { List<Permission> permissions = permissionService.getPermissions(groupsId); for(Permission permission : permissions) { GrantedAuthority auth = new SimpleGrantedAuthority(permission.getPermissionName()); authorities.add(auth); } } } catch (ServiceException e) { LOGGER.error("Exception while querrying customer",e); throw new SecurityDataAccessException("Cannot authenticate customer",e); } return userDetails(userName, user, authorities);
321
381
702
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/common/CustomAuthenticationManager.java
CustomAuthenticationManager
success
class CustomAuthenticationManager { protected final Log logger = LogFactory.getLog(getClass()); @Value("${authToken.header}") private String tokenHeader; public String getTokenHeader() { return tokenHeader; } public void setTokenHeader(String tokenHeader) { this.tokenHeader = tokenHeader; } public void authenticateRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Processing authentication"); } Authentication authResult = null; try { authResult = this.attemptAuthentication(request, response); if (authResult == null) { // return immediately as subclass has indicated that it hasn't completed // authentication return; } } catch (AuthenticationException failed) { // Authentication failed unsuccess(request, response); return; } this.success(request, response, authResult); } private void success(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws AuthenticationException {<FILL_FUNCTION_BODY>} private void unsuccess(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { SecurityContextHolder.clearContext(); if (logger.isDebugEnabled()) { logger.debug("Authentication request failed"); logger.debug("Updated SecurityContextHolder to contain null Authentication"); } unSuccessfullAuthentication(request, response); } public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, Exception; public abstract void successfullAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws AuthenticationException; public abstract void unSuccessfullAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException; }
SecurityContextHolder.getContext().setAuthentication(authentication); if (logger.isDebugEnabled()) { logger.debug("Authentication success"); logger.debug("Updated SecurityContextHolder to containAuthentication"); } successfullAuthentication(request, response, authentication);
480
76
556
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/customer/JWTCustomerAuthenticationManager.java
JWTCustomerAuthenticationManager
attemptAuthentication
class JWTCustomerAuthenticationManager extends CustomAuthenticationManager { protected final Log logger = LogFactory.getLog(getClass()); @Inject private JWTTokenUtil jwtTokenUtil; @Inject private UserDetailsService jwtCustomerDetailsService; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {<FILL_FUNCTION_BODY>} @Override public void successfullAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws AuthenticationException { // TODO Auto-generated method stub } @Override public void unSuccessfullAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // TODO Auto-generated method stub } }
final String requestHeader = request.getHeader(super.getTokenHeader());//token String username = null; String authToken = null; if (requestHeader != null && requestHeader.startsWith("Bearer ")) {//Bearer authToken = requestHeader.substring(7); try { username = jwtTokenUtil.getUsernameFromToken(authToken); } catch (IllegalArgumentException e) { logger.error("an error occured during getting username from token", e); } catch (ExpiredJwtException e) { logger.warn("the token is expired and not valid anymore", e); } } else { throw new CustomAuthenticationException("No Bearer token found in the request"); } UsernamePasswordAuthenticationToken authentication = null; logger.info("checking authentication for user " + username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { // It is not compelling necessary to load the use details from the database. You could also store the information // in the token and read it from it. It's up to you ;) UserDetails userDetails = this.jwtCustomerDetailsService.loadUserByUsername(username); // For simple validation it is completely sufficient to just check the token integrity. You don't have to call // the database compellingly. Again it's up to you ;) if (userDetails != null && jwtTokenUtil.validateToken(authToken, userDetails)) { authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); logger.info("authenticated user " + username + ", setting security context"); //SecurityContextHolder.getContext().setAuthentication(authentication); } } return authentication;
201
469
670
<methods>public non-sealed void <init>() ,public abstract Authentication attemptAuthentication(HttpServletRequest, HttpServletResponse) throws AuthenticationException, java.lang.Exception,public void authenticateRequest(HttpServletRequest, HttpServletResponse) throws java.lang.Exception,public java.lang.String getTokenHeader() ,public void setTokenHeader(java.lang.String) ,public abstract void successfullAuthentication(HttpServletRequest, HttpServletResponse, Authentication) throws AuthenticationException,public abstract void unSuccessfullAuthentication(HttpServletRequest, HttpServletResponse) throws AuthenticationException<variables>protected final org.apache.commons.logging.Log logger,private java.lang.String tokenHeader
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/customer/JWTCustomerAuthenticationProvider.java
JWTCustomerAuthenticationProvider
authenticate
class JWTCustomerAuthenticationProvider extends DaoAuthenticationProvider { @Inject private UserDetailsService jwtCustomerDetailsService; @Inject private PasswordEncoder passwordEncoder; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException {<FILL_FUNCTION_BODY>} private boolean passwordMatch(String rawPassword, String user) { return passwordEncoder.matches(rawPassword, user); } @Override public boolean supports(Class<?> authentication) { return true; } public UserDetailsService getJwtCustomerDetailsService() { return jwtCustomerDetailsService; } public void setJwtCustomerDetailsService(UserDetailsService jwtCustomerDetailsService) { this.jwtCustomerDetailsService = jwtCustomerDetailsService; } }
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String name = auth.getName(); Object credentials = auth.getCredentials(); UserDetails customer = jwtCustomerDetailsService.loadUserByUsername(name); if (customer == null) { throw new BadCredentialsException("Username/Password does not match for " + auth.getPrincipal()); } String pass = credentials.toString(); String usr = name; if(!passwordMatch(pass, usr)) { throw new BadCredentialsException("Username/Password does not match for " + auth.getPrincipal()); } /** * username password auth */ return new UsernamePasswordAuthenticationToken(customer, credentials, customer.getAuthorities());
250
223
473
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/customer/JWTCustomerServicesImpl.java
JWTCustomerServicesImpl
userDetails
class JWTCustomerServicesImpl extends AbstractCustomerServices { @Inject public JWTCustomerServicesImpl(CustomerService customerService, PermissionService permissionService, GroupService groupService) { super(customerService, permissionService, groupService); this.customerService = customerService; this.permissionService = permissionService; this.groupService = groupService; } @Override protected UserDetails userDetails(String userName, Customer customer, Collection<GrantedAuthority> authorities) {<FILL_FUNCTION_BODY>} }
AuditSection section = null; section = customer.getAuditSection(); Date lastModified = null; //if(section != null) {//does not represent password change // lastModified = section.getDateModified(); //} return new JWTUser( customer.getId(), userName, customer.getBilling().getFirstName(), customer.getBilling().getLastName(), customer.getEmailAddress(), customer.getPassword(), authorities, true, lastModified );
139
160
299
<methods>public void <init>(com.salesmanager.core.business.services.customer.CustomerService, com.salesmanager.core.business.services.user.PermissionService, com.salesmanager.core.business.services.user.GroupService) ,public UserDetails loadUserByUsername(java.lang.String) throws UsernameNotFoundException, org.springframework.dao.DataAccessException<variables>private static final org.slf4j.Logger LOGGER,public static final java.lang.String ROLE_PREFIX,protected com.salesmanager.core.business.services.customer.CustomerService customerService,protected com.salesmanager.core.business.services.user.GroupService groupService,protected com.salesmanager.core.business.services.user.PermissionService permissionService
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/store/security/services/CredentialsServiceImpl.java
CredentialsServiceImpl
validateCredentials
class CredentialsServiceImpl implements CredentialsService { @Override public void validateCredentials(String password, String repeatPassword, MerchantStore store, Language language) throws CredentialsException {<FILL_FUNCTION_BODY>} @Override public String generatePassword(MerchantStore store, Language language) throws CredentialsException { // TODO Auto-generated method stub return null; } }
if(StringUtils.isBlank(password) || StringUtils.isBlank(repeatPassword) ) { throw new CredentialsException("Empty password not supported"); } /** * validate - both password match */ if(!password.equals(repeatPassword)) { throw new CredentialsException("Password don't match"); } //create your own rules PasswordValidator passwordValidator = new PasswordValidator( new CharacterRule(EnglishCharacterData.Digit, 1),//at least 1 digit new CharacterRule(EnglishCharacterData.Special, 1),// at least 1 special character new LengthRule(8, 12)//8 to 12 characters ); PasswordData passwordData = new PasswordData(password); RuleResult result = passwordValidator.validate(passwordData); if(!result.isValid()){ throw new CredentialsException("Password validation failed [" + passwordValidator.getMessages(result) + "]"); }
103
265
368
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/AbstractimageFilePath.java
AbstractimageFilePath
buildStaticImageUtils
class AbstractimageFilePath implements ImageFilePath { public abstract String getBasePath(MerchantStore store); public abstract void setBasePath(String basePath); public abstract void setContentUrlPath(String contentUrl); protected static final String CONTEXT_PATH = "CONTEXT_PATH"; public @Resource(name="shopizer-properties") Properties properties = new Properties();//shopizer-properties public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } /** * Builds a static content image file path that can be used by image servlet * utility for getting the physical image * @param store * @param imageName * @return */ public String buildStaticImageUtils(MerchantStore store, String imageName) {<FILL_FUNCTION_BODY>} /** * Builds a static content image file path that can be used by image servlet * utility for getting the physical image by specifying the image type * @param store * @param imageName * @return */ public String buildStaticImageUtils(MerchantStore store, String type, String imageName) { StringBuilder imgName = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH).append(type).append(Constants.SLASH); if(!StringUtils.isBlank(imageName)) { imgName.append(imageName); } return imgName.toString(); } /** * Builds a manufacturer image file path that can be used by image servlet * utility for getting the physical image * @param store * @param manufacturer * @param imageName * @return */ public String buildManufacturerImageUtils(MerchantStore store, Manufacturer manufacturer, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH). append(FileContentType.MANUFACTURER.name()).append(Constants.SLASH) .append(manufacturer.getId()).append(Constants.SLASH) .append(imageName).toString(); } /** * Builds a product image file path that can be used by image servlet * utility for getting the physical image * @param store * @param product * @param imageName * @return */ public String buildProductImageUtils(MerchantStore store, Product product, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.PRODUCTS_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH) .append(product.getSku()).append(Constants.SLASH).append(Constants.SMALL_IMAGE).append(Constants.SLASH).append(imageName).toString(); } /** * Builds a default product image file path that can be used by image servlet * utility for getting the physical image * @param store * @param sku * @param imageName * @return */ public String buildProductImageUtils(MerchantStore store, String sku, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.PRODUCTS_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH) .append(sku).append(Constants.SLASH).append(Constants.SMALL_IMAGE).append(Constants.SLASH).append(imageName).toString(); } /** * Builds a large product image file path that can be used by the image servlet * @param store * @param sku * @param imageName * @return */ public String buildLargeProductImageUtils(MerchantStore store, String sku, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH) .append(sku).append(Constants.SLASH).append(Constants.SMALL_IMAGE).append(Constants.SLASH).append(imageName).toString(); } /** * Builds a merchant store logo path * @param store * @return */ public String buildStoreLogoFilePath(MerchantStore store) { return new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH).append(FileContentType.LOGO).append(Constants.SLASH) .append(store.getStoreLogo()).toString(); } /** * Builds product property image url path * @param store * @param imageName * @return */ public String buildProductPropertyImageFilePath(MerchantStore store, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH).append(FileContentType.PROPERTY).append(Constants.SLASH) .append(imageName).toString(); } public String buildProductPropertyImageUtils(MerchantStore store, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append("/").append(FileContentType.PROPERTY).append("/") .append(imageName).toString(); } public String buildCustomTypeImageUtils(MerchantStore store, String imageName, FileContentType type) { return new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append("/").append(type).append("/") .append(imageName).toString(); } /** * Builds static file url path * @param store * @param imageName * @return */ public String buildStaticContentFilePath(MerchantStore store, String fileName) { StringBuilder sb = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH); if(!StringUtils.isBlank(fileName)) { sb.append(fileName); } return sb.toString(); } }
StringBuilder imgName = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH).append(FileContentType.IMAGE.name()).append(Constants.SLASH); if(!StringUtils.isBlank(imageName)) { imgName.append(imageName); } return imgName.toString();
1,629
109
1,738
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/AppConfiguration.java
AppConfiguration
getProperty
class AppConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfiguration.class); public Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public AppConfiguration() {} public String getProperty(String propertyKey) {<FILL_FUNCTION_BODY>} }
if(properties!=null) { return properties.getProperty(propertyKey); } else { LOGGER.warn("Application properties are not loaded"); return null; }
105
57
162
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/AuthorizationUtils.java
AuthorizationUtils
authorizeUser
class AuthorizationUtils { @Inject private UserFacade userFacade; public String authenticatedUser() { String authenticatedUser = userFacade.authenticatedUser(); if (authenticatedUser == null) { throw new UnauthorizedException(); } return authenticatedUser; } public void authorizeUser(String authenticatedUser, List<String> roles, MerchantStore store) {<FILL_FUNCTION_BODY>} }
userFacade.authorizedGroup(authenticatedUser, roles); if (!userFacade.userInRoles(authenticatedUser, Arrays.asList(Constants.GROUP_SUPERADMIN))) { if (!userFacade.authorizedStore(authenticatedUser, store.getCode())) { throw new UnauthorizedException("Operation unauthorized for user [" + authenticatedUser + "] and store [" + store.getCode() + "]"); } }
122
125
247
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/BeanUtils.java
BeanUtils
getPropertyValue
class BeanUtils { private BeanUtils(){ } public static BeanUtils newInstance(){ return new BeanUtils(); } @SuppressWarnings( "nls" ) public Object getPropertyValue( Object bean, String property ) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {<FILL_FUNCTION_BODY>} private PropertyDescriptor getPropertyDescriptor( Class<?> beanClass, String propertyname ) throws IntrospectionException { BeanInfo beanInfo = Introspector.getBeanInfo( beanClass ); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); PropertyDescriptor propertyDescriptor = null; for ( int i = 0; i < propertyDescriptors.length; i++ ) { PropertyDescriptor currentPropertyDescriptor = propertyDescriptors[i]; if ( currentPropertyDescriptor.getName().equals( propertyname ) ) { propertyDescriptor = currentPropertyDescriptor; } } return propertyDescriptor; } }
if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if(property == null){ throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } Class<?> beanClass = bean.getClass(); PropertyDescriptor propertyDescriptor = getPropertyDescriptor( beanClass, property ); if ( propertyDescriptor == null ) { throw new IllegalArgumentException( "No such property " + property + " for " + beanClass + " exists" ); } Method readMethod = propertyDescriptor.getReadMethod(); if ( readMethod == null ) { throw new IllegalStateException( "No getter available for property " + property + " on " + beanClass ); } return readMethod.invoke( bean );
270
200
470
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/CaptchaRequestUtils.java
CaptchaRequestUtils
checkCaptcha
class CaptchaRequestUtils { @Inject private CoreConfiguration configuration; //for reading public and secret key private static final String SUCCESS_INDICATOR = "success"; @Value("${config.recaptcha.secretKey}") private String secretKey; public boolean checkCaptcha(String gRecaptchaResponse) throws Exception {<FILL_FUNCTION_BODY>} }
HttpClient client = HttpClientBuilder.create().build(); String url = configuration.getProperty(ApplicationConstants.RECAPTCHA_URL);; List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("secret", secretKey)); data.add(new BasicNameValuePair("response", gRecaptchaResponse)); // Create a method instance. HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(data,StandardCharsets.UTF_8)); boolean checkCaptcha = false; try { // Execute the method. HttpResponse httpResponse = client.execute(post); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Got an invalid response from reCaptcha " + url + " [" + httpResponse.getStatusLine() + "]"); } // Read the response body. HttpEntity entity = httpResponse.getEntity(); byte[] responseBody =EntityUtils.toByteArray(entity); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data //System.out.println(new String(responseBody)); String json = new String(responseBody); Map<String,String> map = new HashMap<String,String>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}); String successInd = map.get(SUCCESS_INDICATOR); if(StringUtils.isBlank(successInd)) { throw new Exception("Unreadable response from reCaptcha " + json); } Boolean responseBoolean = Boolean.valueOf(successInd); if(responseBoolean) { checkCaptcha = true; } return checkCaptcha; } finally { // Release the connection. post.releaseConnection(); }
107
595
702
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/CloudFilePathUtils.java
CloudFilePathUtils
buildStaticImageUtils
class CloudFilePathUtils extends AbstractimageFilePath { private String basePath = Constants.STATIC_URI; private String contentUrl = null; @Override public String getBasePath(MerchantStore store) { //store has no incidence, basepath drives the url return basePath; } @Override public void setBasePath(String basePath) { this.basePath = basePath; } @Override public String getContextPath() { return super.getProperties().getProperty(CONTEXT_PATH); } /** * Builds a static content image file path that can be used by image servlet * utility for getting the physical image * @param store * @param imageName * @return */ @Override public String buildStaticImageUtils(MerchantStore store, String imageName) {<FILL_FUNCTION_BODY>} /** * Builds a static content image file path that can be used by image servlet * utility for getting the physical image by specifying the image type * @param store * @param imageName * @return */ @Override public String buildStaticImageUtils(MerchantStore store, String type, String imageName) { StringBuilder imgName = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH); if(type!=null && !FileContentType.IMAGE.name().equals(type)) { imgName.append(type).append(Constants.SLASH); } if(!StringUtils.isBlank(imageName)) { imgName.append(imageName); } return imgName.toString(); } @Override public void setContentUrlPath(String contentUrl) { this.contentUrl = contentUrl; } }
StringBuilder imgName = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH); if(!StringUtils.isBlank(imageName)) { imgName.append(imageName); } return imgName.toString();
467
91
558
<methods>public non-sealed void <init>() ,public java.lang.String buildCustomTypeImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, com.salesmanager.core.model.content.FileContentType) ,public java.lang.String buildLargeProductImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, java.lang.String) ,public java.lang.String buildManufacturerImageUtils(com.salesmanager.core.model.merchant.MerchantStore, com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer, java.lang.String) ,public java.lang.String buildProductImageUtils(com.salesmanager.core.model.merchant.MerchantStore, com.salesmanager.core.model.catalog.product.Product, java.lang.String) ,public java.lang.String buildProductImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, java.lang.String) ,public java.lang.String buildProductPropertyImageFilePath(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildProductPropertyImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildStaticContentFilePath(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildStaticImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildStaticImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, java.lang.String) ,public java.lang.String buildStoreLogoFilePath(com.salesmanager.core.model.merchant.MerchantStore) ,public abstract java.lang.String getBasePath(com.salesmanager.core.model.merchant.MerchantStore) ,public java.util.Properties getProperties() ,public abstract void setBasePath(java.lang.String) ,public abstract void setContentUrlPath(java.lang.String) ,public void setProperties(java.util.Properties) <variables>protected static final java.lang.String CONTEXT_PATH,public java.util.Properties properties
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/DateUtil.java
DateUtil
processPostedDates
class DateUtil { private Date startDate = new Date(new Date().getTime()); private Date endDate = new Date(new Date().getTime()); private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class); private final static String LONGDATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; /** * Generates a time stamp * yyyymmddhhmmss * @return */ public static String generateTimeStamp() { SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmSS"); return format.format(new Date()); } /** * yyyy-MM-dd * * @param dt * @return */ public static String formatDate(Date dt) { if (dt == null) dt = new Date(); SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT); return format.format(dt); } public static String formatYear(Date dt) { if (dt == null) return null; SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT_YEAR); return format.format(dt); } public static String formatLongDate(Date date) { if (date == null) return null; SimpleDateFormat format = new SimpleDateFormat(LONGDATE_FORMAT); return format.format(date); } /** * yy-MMM-dd * * @param dt * @return */ public static String formatDateMonthString(Date dt) { if (dt == null) return null; SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT); return format.format(dt); } public static Date getDate(String date) throws Exception { DateFormat myDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT); return myDateFormat.parse(date); } public static Date addDaysToCurrentDate(int days) { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DATE, days); return c.getTime(); } public static Date getDate() { return new Date(new Date().getTime()); } public static String getPresentDate() { Date dt = new Date(); SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT); return format.format(new Date(dt.getTime())); } public static String getPresentYear() { Date dt = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy"); return format.format(new Date(dt.getTime())); } public static boolean dateBeforeEqualsDate(Date firstDate, Date compareDate) { if(firstDate==null || compareDate==null) { return true; } if (firstDate.compareTo(compareDate) > 0) { return false; } else if (firstDate.compareTo(compareDate) < 0) { return true; } else if (firstDate.compareTo(compareDate) == 0) { return true; } else { return false; } } public void processPostedDates(HttpServletRequest request) {<FILL_FUNCTION_BODY>} public Date getEndDate() { return endDate; } public Date getStartDate() { return startDate; } }
Date dt = new Date(); DateFormat myDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT); Date sDate = null; Date eDate = null; try { if (request.getParameter("startdate") != null) { sDate = myDateFormat.parse(request.getParameter("startdate")); } if (request.getParameter("enddate") != null) { eDate = myDateFormat.parse(request.getParameter("enddate")); } this.startDate = sDate; this.endDate = eDate; } catch (Exception e) { LOGGER.error("",e); this.startDate = new Date(dt.getTime()); this.endDate = new Date(dt.getTime()); }
916
209
1,125
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/EmailUtils.java
EmailUtils
createEmailObjectsMap
class EmailUtils { private final static String EMAIL_STORE_NAME = "EMAIL_STORE_NAME"; private final static String EMAIL_FOOTER_COPYRIGHT = "EMAIL_FOOTER_COPYRIGHT"; private final static String EMAIL_DISCLAIMER = "EMAIL_DISCLAIMER"; private final static String EMAIL_SPAM_DISCLAIMER = "EMAIL_SPAM_DISCLAIMER"; private final static String EMAIL_ADMIN_LABEL = "EMAIL_ADMIN_LABEL"; private final static String LOGOPATH = "LOGOPATH"; @Inject @Qualifier("img") private ImageFilePath imageUtils; /** * Builds generic html email information * @param store * @param messages * @param locale * @return */ public Map<String, String> createEmailObjectsMap(String contextPath, MerchantStore store, LabelUtils messages, Locale locale){<FILL_FUNCTION_BODY>} }
Map<String, String> templateTokens = new HashMap<String, String>(); String[] adminNameArg = {store.getStorename()}; String[] adminEmailArg = {store.getStoreEmailAddress()}; String[] copyArg = {store.getStorename(), DateUtil.getPresentYear()}; templateTokens.put(EMAIL_ADMIN_LABEL, messages.getMessage("email.message.from", adminNameArg, locale)); templateTokens.put(EMAIL_STORE_NAME, store.getStorename()); templateTokens.put(EMAIL_FOOTER_COPYRIGHT, messages.getMessage("email.copyright", copyArg, locale)); templateTokens.put(EMAIL_DISCLAIMER, messages.getMessage("email.disclaimer", adminEmailArg, locale)); templateTokens.put(EMAIL_SPAM_DISCLAIMER, messages.getMessage("email.spam.disclaimer", locale)); if(store.getStoreLogo()!=null) { //TODO revise StringBuilder logoPath = new StringBuilder(); String scheme = Constants.HTTP_SCHEME; logoPath.append("<img src='").append(scheme).append("://").append(store.getDomainName()).append(contextPath).append("/").append(imageUtils.buildStoreLogoFilePath(store)).append("' style='max-width:400px;'>"); templateTokens.put(LOGOPATH, logoPath.toString()); } else { templateTokens.put(LOGOPATH, store.getStorename()); } return templateTokens;
267
426
693
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/EnumValidator.java
EnumValidator
isValid
class EnumValidator implements ConstraintValidator<Enum, String> { private Enum annotation; @Override public void initialize(Enum annotation) { this.annotation = annotation; } @Override public boolean isValid(String valueForValidation, ConstraintValidatorContext constraintValidatorContext) {<FILL_FUNCTION_BODY>} }
boolean result = false; Object[] enumValues = this.annotation.enumClass().getEnumConstants(); if(enumValues != null) { for(Object enumValue:enumValues) { if(valueForValidation.equals(enumValue.toString()) || (this.annotation.ignoreCase() && valueForValidation.equalsIgnoreCase(enumValue.toString()))) { result = true; break; } } } return result;
95
131
226
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/FieldMatchValidator.java
FieldMatchValidator
isValid
class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> { private static final Logger LOG=LoggerFactory.getLogger(FieldMatchValidator.class); private String firstFieldName; private String secondFieldName; private BeanUtils beanUtils; @Override public void initialize(final FieldMatch constraintAnnotation) { this.firstFieldName = constraintAnnotation.first(); this.secondFieldName = constraintAnnotation.second(); this.beanUtils=BeanUtils.newInstance(); } @SuppressWarnings( "nls" ) @Override public boolean isValid(final Object value, final ConstraintValidatorContext context) {<FILL_FUNCTION_BODY>} }
try { final Object firstObj = this.beanUtils.getPropertyValue(value, this.firstFieldName); final Object secondObj = this.beanUtils.getPropertyValue(value, this.secondFieldName); return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj); } catch (final Exception ex) { LOG.info( "Error while getting values from object", ex ); return false; }
181
126
307
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/FileNameUtils.java
FileNameUtils
validFileName
class FileNameUtils { public boolean validFileName(String fileName) {<FILL_FUNCTION_BODY>} }
boolean validName = true; //has an extention if(StringUtils.isEmpty(FilenameUtils.getExtension(fileName))) { validName = false; } //has a filename if(StringUtils.isEmpty(FilenameUtils.getBaseName(fileName))) { validName = false; } return validName;
34
102
136
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/FilePathUtils.java
FilePathUtils
buildStoreForwardedUri
class FilePathUtils { private static final String DOWNLOADS = "/downloads/"; private static final String DOUBLE_SLASH = "://"; private static final String CONTEXT_PATH = "CONTEXT_PATH"; public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; public static final String HTTP = "http://"; public static final String HTTPS = "https://"; @Inject private CoreConfiguration coreConfiguration; @Inject @Qualifier("img") private ImageFilePath imageUtils; @Resource(name = "shopizer-properties") public Properties properties = new Properties(); /** * Builds a static content content file path that can be used by image * servlet utility for getting the physical image Example: * /files/<storeCode>/ */ public String buildStaticFilePath(String storeCode, String fileName) { String path = FILES_URI + SLASH + storeCode + SLASH; if (StringUtils.isNotBlank(fileName)) { return path + fileName; } return path; } public String buildStaticFilePath(MerchantStore store) { return STATIC_URI + FILES_URI + SLASH + store.getCode() + SLASH; } /** * Example: /admin/files/downloads/<storeCode>/<product> */ public String buildAdminDownloadProductFilePath(MerchantStore store, DigitalProduct digitalProduct) { return ADMIN_URI + FILES_URI + DOWNLOADS + store.getCode() + SLASH + digitalProduct.getProductFileName(); } /** * Example: /shop/order/download/<orderId>.html */ public String buildOrderDownloadProductFilePath(MerchantStore store, ReadableOrderProductDownload digitalProduct, Long orderId) { return SHOP_URI + ORDER_DOWNLOAD_URI + SLASH + orderId + SLASH + digitalProduct.getId() + URL_EXTENSION; } /** * Example: /<baseImagePath>/files/<storeCode>/STATIC_FILE/<fileName> Or * example: /<shopScheme>://<domainName>/<contextPath>/files/<storeCode>/ */ public String buildStaticFileAbsolutePath(MerchantStore store, String fileName) { if (StringUtils.isNotBlank(imageUtils.getBasePath(store)) && imageUtils.getBasePath(store).startsWith(HTTP_SCHEME)) { return imageUtils.getBasePath(store) + FILES_URI + SLASH + store.getCode() + SLASH + FileContentType.STATIC_FILE + SLASH + fileName; } else { String scheme = this.getScheme(store); return scheme + SLASH + coreConfiguration.getProperty("CONTEXT_PATH") + buildStaticFilePath(store.getCode(), fileName); } } /** * Example: http[s]://<scheme>/<domainName>/<contextPath> */ public String buildStoreUri(MerchantStore store, HttpServletRequest request) { return buildBaseUrl(request, store); } /** * \/<contextPath> */ public String buildStoreUri(MerchantStore store, String contextPath) { return normalizePath(contextPath); } public String buildRelativeStoreUri(HttpServletRequest request, MerchantStore store) { return "" + normalizePath(request.getContextPath()); } /** * Access to the customer section */ public String buildCustomerUri(MerchantStore store, String contextPath) { return buildStoreUri(store, contextPath); } public String buildAdminUri(MerchantStore store, HttpServletRequest request) { String baseUrl = buildBaseUrl(request, store); return baseUrl + ADMIN_URI; } public String buildCategoryUrl(MerchantStore store, String contextPath, String url) { return buildStoreUri(store, contextPath) + SHOP_URI + CATEGORY_URI + SLASH + url + URL_EXTENSION; } public String buildProductUrl(MerchantStore store, String contextPath, String url) { return buildStoreUri(store, contextPath) + SHOP_URI + Constants.PRODUCT_URI + SLASH + url + URL_EXTENSION; } public String getContextPath() { return properties.getProperty(CONTEXT_PATH); } private String normalizePath(String path) { if (SLASH.equals(path)) { return BLANK; } else { return path; } } private String getDomainName(String domainName) { if (StringUtils.isBlank(domainName)) { return DEFAULT_DOMAIN_NAME; } else { return domainName; } } private String getScheme(MerchantStore store) { String baseScheme = store.getDomainName(); if (baseScheme != null && baseScheme.length() > 0 && baseScheme.charAt(baseScheme.length() - 1) == Constants.SLASH.charAt(0)) { baseScheme = baseScheme.substring(0, baseScheme.length() - 1); } // end no more return validUrl(baseScheme); } public String validUrl(final String url) { if (!StringUtils.isBlank(url) && !url.startsWith(HTTP) && !url.startsWith(HTTP)) { return HTTPS + url; } return url; } private String buildBaseUrl(HttpServletRequest request, MerchantStore store) { String contextPath = normalizePath(request.getContextPath()); String scheme = getScheme(store); return scheme + DOUBLE_SLASH + contextPath; } public String buildBaseUrl(String contextPath, MerchantStore store) { String normalizePath = normalizePath(contextPath); String scheme = getScheme(store); return scheme + SLASH + normalizePath; } /** * Requires web server headers to build image URL for social media * sharing.<br/> * * Nginx configuration example: * * <pre> * proxy_set_header X-Forwarded-Proto $scheme; * proxy_set_header X-Forwarded-Host $scheme://$host; * proxy_set_header X-Forwarded-Server $host; * </pre> * * @param merchantStore * @param request * @return */ public String buildStoreForwardedUri(MerchantStore merchantStore, HttpServletRequest request) {<FILL_FUNCTION_BODY>} public boolean isValidURL(String urlString) { try { URL url = new URL(urlString); url.toURI(); return true; } catch (Exception exception) { return false; } } }
String uri; if (StringUtils.isNotEmpty(request.getHeader(X_FORWARDED_HOST))) { uri = request.getHeader(X_FORWARDED_HOST); } else { uri = buildStoreUri(merchantStore, request); } return uri;
1,757
83
1,840
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/GeoLocationUtils.java
GeoLocationUtils
getClientIpAddress
class GeoLocationUtils { private static final String[] HEADERS_TO_TRY = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR" }; public static String getClientIpAddress(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
for (String header : HEADERS_TO_TRY) { String ip = request.getHeader(header); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { return ip; } } return request.getRemoteAddr();
184
80
264
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/LabelUtils.java
LabelUtils
getMessage
class LabelUtils implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public String getMessage(String key, Locale locale) { return applicationContext.getMessage(key, null, locale); } public String getMessage(String key, Locale locale, String defaultValue) {<FILL_FUNCTION_BODY>} public String getMessage(String key, String[] args, Locale locale) { return applicationContext.getMessage(key, args, locale); } }
try { return applicationContext.getMessage(key, null, locale); } catch(Exception ignore) {} return defaultValue;
161
37
198
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/LanguageUtils.java
LanguageUtils
getRESTLanguage
class LanguageUtils { protected final Log logger = LogFactory.getLog(getClass()); public static final String REQUEST_PARAMATER_STORE = "store"; private static final String ALL_LANGUALES = "_all"; @Inject LanguageService languageService; @Autowired private StoreFacade storeFacade; public Language getServiceLanguage(String lang) { Language l = null; if (!StringUtils.isBlank(lang)) { try { l = languageService.getByCode(lang); } catch (ServiceException e) { logger.error("Cannot retrieve language " + lang, e); } } if (l == null) { l = languageService.defaultLanguage(); } return l; } /** * Determines request language based on store rules * * @param request * @return */ public Language getRequestLanguage(HttpServletRequest request, HttpServletResponse response) { Locale locale = null; Language language = (Language) request.getSession().getAttribute(Constants.LANGUAGE); MerchantStore store = (MerchantStore) request.getSession().getAttribute(Constants.MERCHANT_STORE); if (language == null) { try { locale = LocaleContextHolder.getLocale();// should be browser locale if (store != null) { language = store.getDefaultLanguage(); if (language != null) { locale = languageService.toLocale(language, store); if (locale != null) { LocaleContextHolder.setLocale(locale); } request.getSession().setAttribute(Constants.LANGUAGE, language); } if (language == null) { language = languageService.toLanguage(locale); request.getSession().setAttribute(Constants.LANGUAGE, language); } } } catch (Exception e) { if (language == null) { try { language = languageService.getByCode(Constants.DEFAULT_LANGUAGE); } catch (Exception ignore) { } } } } else { Locale localeFromContext = LocaleContextHolder.getLocale();// should be browser locale if (!language.getCode().equals(localeFromContext.getLanguage())) { // get locale context language = languageService.toLanguage(localeFromContext); } } if (language != null) { locale = languageService.toLocale(language, store); } else { language = languageService.toLanguage(locale); } LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); if (localeResolver != null) { localeResolver.setLocale(request, response, locale); } response.setLocale(locale); request.getSession().setAttribute(Constants.LANGUAGE, language); return language; } /** * Should be used by rest web services * * @param request * @param store * @return * @throws Exception */ public Language getRESTLanguage(HttpServletRequest request, NativeWebRequest webRequest) {<FILL_FUNCTION_BODY>} }
Validate.notNull(request, "HttpServletRequest must not be null"); try { Language language = null; String lang = request.getParameter(Constants.LANG); if (StringUtils.isBlank(lang)) { if (language == null) { String storeValue = Optional.ofNullable(webRequest.getParameter(REQUEST_PARAMATER_STORE)) .filter(StringUtils::isNotBlank).orElse(DEFAULT_STORE); if(!StringUtils.isBlank(storeValue)) { try { MerchantStore storeModel = storeFacade.get(storeValue); language = storeModel.getDefaultLanguage(); } catch (Exception e) { logger.warn("Cannot get store with code [" + storeValue + "]"); } } else { language = languageService.defaultLanguage(); } } } else { if(!ALL_LANGUALES.equals(lang)) { language = languageService.getByCode(lang); if (language == null) { language = languageService.defaultLanguage(); } } } //if language is null then underlying facade must load all languages return language; } catch (ServiceException e) { throw new ServiceRuntimeException(e); }
851
358
1,209
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/LocalImageFilePathUtils.java
LocalImageFilePathUtils
getBasePath
class LocalImageFilePathUtils extends AbstractimageFilePath{ private String basePath = Constants.STATIC_URI; private static final String SCHEME = "http://"; private String contentUrl = null; @Autowired private ServerConfig serverConfig; @Override public String getBasePath(MerchantStore store) {<FILL_FUNCTION_BODY>} @Override public void setBasePath(String context) { this.basePath = context; } /** * Builds a static content image file path that can be used by image servlet * utility for getting the physical image * @param store * @param imageName * @return */ public String buildStaticimageUtils(MerchantStore store, String imageName) { StringBuilder imgName = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append("/").append(FileContentType.IMAGE.name()).append("/"); if(!StringUtils.isBlank(imageName)) { imgName.append(imageName); } return imgName.toString(); } /** * Builds a static content image file path that can be used by image servlet * utility for getting the physical image by specifying the image type * @param store * @param imageName * @return */ public String buildStaticimageUtils(MerchantStore store, String type, String imageName) { StringBuilder imgName = new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append("/").append(type).append("/"); if(!StringUtils.isBlank(imageName)) { imgName.append(imageName); } return imgName.toString(); } /** * Builds a manufacturer image file path that can be used by image servlet * utility for getting the physical image * @param store * @param manufacturer * @param imageName * @return */ public String buildManufacturerimageUtils(MerchantStore store, Manufacturer manufacturer, String imageName) { return new StringBuilder().append(getBasePath(store)).append("/").append(store.getCode()).append("/"). append(FileContentType.MANUFACTURER.name()).append("/") .append(manufacturer.getId()).append("/") .append(imageName).toString(); } /** * Builds a product image file path that can be used by image servlet * utility for getting the physical image * @param store * @param product * @param imageName * @return */ public String buildProductimageUtils(MerchantStore store, Product product, String imageName) { return new StringBuilder().append(getBasePath(store)).append("/products/").append(store.getCode()).append("/") .append(product.getSku()).append("/").append("LARGE").append("/").append(imageName).toString(); } /** * Builds a default product image file path that can be used by image servlet * utility for getting the physical image * @param store * @param sku * @param imageName * @return */ public String buildProductimageUtils(MerchantStore store, String sku, String imageName) { return new StringBuilder().append(getBasePath(store)).append("/products/").append(store.getCode()).append("/") .append(sku).append("/").append("LARGE").append("/").append(imageName).toString(); } /** * Builds a large product image file path that can be used by the image servlet * @param store * @param sku * @param imageName * @return */ public String buildLargeProductimageUtils(MerchantStore store, String sku, String imageName) { return new StringBuilder().append(getBasePath(store)).append("/products/").append(store.getCode()).append("/") .append(sku).append("/").append("LARGE").append("/").append(imageName).toString(); } /** * Builds a merchant store logo path * @param store * @return */ public String buildStoreLogoFilePath(MerchantStore store) { return new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append("/").append(FileContentType.LOGO).append("/") .append(store.getStoreLogo()).toString(); } /** * Builds product property image url path * @param store * @param imageName * @return */ public String buildProductPropertyimageUtils(MerchantStore store, String imageName) { return new StringBuilder().append(getBasePath(store)).append(Constants.FILES_URI).append(Constants.SLASH).append(store.getCode()).append("/").append(FileContentType.PROPERTY).append("/") .append(imageName).toString(); } @Override public String getContextPath() { return super.getProperties().getProperty(CONTEXT_PATH); } private String getScheme(MerchantStore store, String derivedHost) { return store.getDomainName() != null ? store.getDomainName():derivedHost; } @Override public void setContentUrlPath(String contentUrl) { this.contentUrl = contentUrl; } }
if(StringUtils.isBlank(contentUrl)) { String host = new StringBuilder().append(SCHEME).append(serverConfig.getApplicationHost()).toString(); return new StringBuilder().append(this.getScheme(store, host)).append(basePath).toString(); } else { return new StringBuilder().append(contentUrl).append(basePath).toString(); }
1,387
97
1,484
<methods>public non-sealed void <init>() ,public java.lang.String buildCustomTypeImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, com.salesmanager.core.model.content.FileContentType) ,public java.lang.String buildLargeProductImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, java.lang.String) ,public java.lang.String buildManufacturerImageUtils(com.salesmanager.core.model.merchant.MerchantStore, com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer, java.lang.String) ,public java.lang.String buildProductImageUtils(com.salesmanager.core.model.merchant.MerchantStore, com.salesmanager.core.model.catalog.product.Product, java.lang.String) ,public java.lang.String buildProductImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, java.lang.String) ,public java.lang.String buildProductPropertyImageFilePath(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildProductPropertyImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildStaticContentFilePath(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildStaticImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String) ,public java.lang.String buildStaticImageUtils(com.salesmanager.core.model.merchant.MerchantStore, java.lang.String, java.lang.String) ,public java.lang.String buildStoreLogoFilePath(com.salesmanager.core.model.merchant.MerchantStore) ,public abstract java.lang.String getBasePath(com.salesmanager.core.model.merchant.MerchantStore) ,public java.util.Properties getProperties() ,public abstract void setBasePath(java.lang.String) ,public abstract void setContentUrlPath(java.lang.String) ,public void setProperties(java.util.Properties) <variables>protected static final java.lang.String CONTEXT_PATH,public java.util.Properties properties
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/LocaleUtils.java
LocaleUtils
getLocale
class LocaleUtils { private static final Logger LOGGER = LoggerFactory.getLogger(LocaleUtils.class); public static Locale getLocale(Language language) { return new Locale(language.getCode()); } /** * Creates a Locale object for currency format only with country code * This method ignoes the language * @param store * @return */ public static Locale getLocale(MerchantStore store) {<FILL_FUNCTION_BODY>} }
Locale defaultLocale = Constants.DEFAULT_LOCALE; Locale[] locales = Locale.getAvailableLocales(); for(int i = 0; i< locales.length; i++) { Locale l = locales[i]; try { if(l.toLanguageTag().equals(store.getDefaultLanguage().getCode())) { defaultLocale = l; break; } } catch(Exception e) { LOGGER.error("An error occured while getting ISO code for locale " + l.toString()); } } return defaultLocale;
132
162
294
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/MerchantUtils.java
MerchantUtils
getBigDecimal
class MerchantUtils { public String getFooterMessage(MerchantStore store, String prefix, String suffix) { StringBuilder footerMessage = new StringBuilder(); if(!StringUtils.isBlank(prefix)) { footerMessage.append(prefix).append(" "); } Date sinceDate = null; String inBusinessSince = store.getDateBusinessSince(); return null; } /** * Locale based bigdecimal parser * @return */ public static BigDecimal getBigDecimal(String bigDecimal) throws ParseException {<FILL_FUNCTION_BODY>} }
NumberFormat decimalFormat = NumberFormat.getInstance(Locale.getDefault()); BigDecimal value; if(decimalFormat instanceof DecimalFormat) { ((DecimalFormat) decimalFormat).setParseBigDecimal(true); value = (BigDecimal) decimalFormat.parse(bigDecimal); } else { value = new BigDecimal(bigDecimal); } return value;
166
108
274
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/SanitizeUtils.java
SanitizeUtils
getSafeRequestParamString
class SanitizeUtils { /** * should not contain / */ private static List<Character> blackList = Arrays.asList(';','%', '&', '=', '|', '*', '+', '_', '^', '%','$','(', ')', '{', '}', '<', '>', '[', ']', '`', '\'', '~','\\', '?','\''); private final static String POLICY_FILE = "antisamy-slashdot.xml"; private static Policy policy = null; static { try { ClassLoader loader = Policy.class.getClassLoader(); InputStream configStream = loader.getResourceAsStream(POLICY_FILE); policy = Policy.getInstance(configStream); } catch (Exception e) { throw new ServiceRuntimeException(e); } } private SanitizeUtils() { //Utility class } public static String getSafeString(String value) { try { if(policy == null) { throw new ServiceRuntimeException("Error in " + SanitizeUtils.class.getName() + " html sanitize utils is null"); } AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(value, policy); return cr.getCleanHTML(); } catch (Exception e) { throw new ServiceRuntimeException(e); } } public static String getSafeRequestParamString(String value) {<FILL_FUNCTION_BODY>} /* public static String getSafeString(String value) { //value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); //value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); //value = value.replaceAll("'", "& #39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", ""); value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", ""); value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", ""); value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", ""); //value = value.replaceAll("<script>", ""); //value = value.replaceAll("</script>", ""); //return HtmlUtils.htmlEscape(value); StringBuilder safe = new StringBuilder(); if(StringUtils.isNotEmpty(value)) { // Fastest way for short strings - https://stackoverflow.com/a/11876086/195904 for(int i=0; i<value.length(); i++) { char current = value.charAt(i); if(!blackList.contains(current)) { safe.append(current); } } } return StringEscapeUtils.escapeXml11(safe.toString()); }*/ }
StringBuilder safe = new StringBuilder(); if(StringUtils.isNotEmpty(value)) { // Fastest way for short strings - https://stackoverflow.com/a/11876086/195904 for(int i=0; i<value.length(); i++) { char current = value.charAt(i); if(!blackList.contains(current)) { safe.append(current); } } } return StringEscapeUtils.escapeXml11(safe.toString());
892
138
1,030
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/ServerConfig.java
ServerConfig
getHost
class ServerConfig implements ApplicationListener<WebServerInitializedEvent> { private String applicationHost = null; @Override public void onApplicationEvent(final WebServerInitializedEvent event) { int port = event.getWebServer().getPort(); final String host = getHost(); setApplicationHost(String.join(":", host, String.valueOf(port))); } private String getHost() {<FILL_FUNCTION_BODY>} public String getApplicationHost() { return applicationHost; } public void setApplicationHost(String applicationHost) { this.applicationHost = applicationHost; } }
try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); return "127.0.0.1"; }
160
58
218
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/ServiceRequestCriteriaBuilderUtils.java
ServiceRequestCriteriaBuilderUtils
buildRequest
class ServiceRequestCriteriaBuilderUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRequestCriteriaBuilderUtils.class); /** * Binds request parameter values to specific request criterias * @param criteria * @param mappingFields * @param request * @return * @throws Exception */ public static Criteria buildRequestCriterias(Criteria criteria, Map<String, String> mappingFields, HttpServletRequest request) throws RestApiException { if(criteria == null) throw new RestApiException("A criteria class type must be instantiated"); mappingFields.keySet().stream().forEach(p -> { try { setValue(criteria, request, p, mappingFields.get(p)); } catch (Exception e) { e.printStackTrace(); } }); return criteria; } private static void setValue(Criteria criteria, HttpServletRequest request, String parameterName, String setterValue) throws Exception { try { PropertyAccessor criteriaAccessor = PropertyAccessorFactory.forDirectFieldAccess(criteria); String parameterValue = request.getParameter(parameterName); if(parameterValue == null) return; // set the property directly, bypassing the mutator (if any) //String setterName = "set" + WordUtils.capitalize(setterValue); String setterName = setterValue; System.out.println("Trying to do this binding " + setterName + "('" + parameterValue + "') on " + criteria.getClass()); criteriaAccessor.setPropertyValue(setterName, parameterValue); } catch(Exception e) { throw new Exception("An error occured while parameter bindding", e); } } /** deprecated **/ public static Criteria buildRequest(Map<String, String> mappingFields, HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
/** * Works assuming datatable sends query data */ MerchantStoreCriteria criteria = new MerchantStoreCriteria(); String searchParam = request.getParameter("search[value]"); String orderColums = request.getParameter("order[0][column]"); if (!StringUtils.isBlank(orderColums)) { String columnName = request.getParameter("columns[" + orderColums + "][data]"); String overwriteField = columnName; if (mappingFields != null && mappingFields.get(columnName) != null) { overwriteField = mappingFields.get(columnName); } criteria.setCriteriaOrderByField(overwriteField); criteria.setOrderBy( CriteriaOrderBy.valueOf(request.getParameter("order[0][dir]").toUpperCase())); } String storeName = request.getParameter("storeName"); criteria.setName(storeName); String retailers = request.getParameter("retailers"); String stores = request.getParameter("stores"); try { boolean retail = Boolean.valueOf(retailers); boolean sto = Boolean.valueOf(stores); criteria.setRetailers(retail); criteria.setStores(sto); } catch(Exception e) { LOGGER.error("Error parsing boolean values",e); } criteria.setSearch(searchParam); return criteria;
518
378
896
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/TokenizeTool.java
TokenizeTool
tokenizeString
class TokenizeTool { private final static String CIPHER = "AES/ECB/PKCS5Padding"; private static final Logger LOGGER = LoggerFactory.getLogger(TokenizeTool.class); private TokenizeTool(){} private static SecretKey key = null; static { try { KeyGenerator keygen = KeyGenerator.getInstance("DES"); key = keygen.generateKey(); } catch (Exception e) { LOGGER.error("Cannot generate key",e); } } public static String tokenizeString(String token) throws Exception {<FILL_FUNCTION_BODY>} }
Cipher aes = Cipher.getInstance(CIPHER); aes.init(Cipher.ENCRYPT_MODE, key); byte[] ciphertext = aes.doFinal(token.getBytes()); return new String(ciphertext);
186
81
267
<no_super_class>
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/UserUtils.java
UserUtils
userInGroup
class UserUtils { public static boolean userInGroup(User user,String groupName) {<FILL_FUNCTION_BODY>} }
List<Group> logedInUserGroups = user.getGroups(); for(Group group : logedInUserGroups) { if(group.getGroupName().equals(groupName)) { return true; } } return false;
38
76
114
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/backo/Backoff.java
Backoff
duration
class Backoff { private long ms = 100; private long max = 10000; private int factor = 2; private double jitter; private int attempts; public Backoff() {} public long duration() {<FILL_FUNCTION_BODY>} public void reset() { this.attempts = 0; } public Backoff setMin(long min) { this.ms = min; return this; } public Backoff setMax(long max) { this.max = max; return this; } public Backoff setFactor(int factor) { this.factor = factor; return this; } public Backoff setJitter(double jitter) { boolean isValid = jitter >= 0 && jitter < 1; if (!isValid) { throw new IllegalArgumentException("jitter must be between 0 and 1"); } this.jitter = jitter; return this; } public int getAttempts() { return this.attempts; } }
BigInteger ms = BigInteger.valueOf(this.ms) .multiply(BigInteger.valueOf(this.factor).pow(this.attempts++)); if (jitter != 0.0) { double rand = Math.random(); BigInteger deviation = BigDecimal.valueOf(rand) .multiply(BigDecimal.valueOf(jitter)) .multiply(new BigDecimal(ms)).toBigInteger(); ms = (((int) Math.floor(rand * 10)) & 1) == 0 ? ms.subtract(deviation) : ms.add(deviation); } return ms .min(BigInteger.valueOf(this.max)) .max(BigInteger.valueOf(this.ms)) .longValue();
289
203
492
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/client/IO.java
IO
socket
class IO { private static final Logger logger = Logger.getLogger(IO.class.getName()); private static final ConcurrentHashMap<String, Manager> managers = new ConcurrentHashMap<>(); /** * Protocol version. */ public static int protocol = Parser.protocol; public static void setDefaultOkHttpWebSocketFactory(WebSocket.Factory factory) { Manager.defaultWebSocketFactory = factory; } public static void setDefaultOkHttpCallFactory(Call.Factory factory) { Manager.defaultCallFactory = factory; } private IO() {} public static Socket socket(String uri) throws URISyntaxException { return socket(uri, null); } public static Socket socket(String uri, Options opts) throws URISyntaxException { return socket(new URI(uri), opts); } public static Socket socket(URI uri) { return socket(uri, null); } /** * Initializes a {@link Socket} from an existing {@link Manager} for multiplexing. * * @param uri uri to connect. * @param opts options for socket. * @return {@link Socket} instance. */ public static Socket socket(URI uri, Options opts) {<FILL_FUNCTION_BODY>} public static class Options extends Manager.Options { public boolean forceNew; /** * Whether to enable multiplexing. Default is true. */ public boolean multiplex = true; /** * <p> * Retrieve new builder class that helps creating socket option as builder pattern. * This method returns exactly same result as : * </p> * <code> * SocketOptionBuilder builder = SocketOptionBuilder.builder(); * </code> * * @return builder class that helps creating socket option as builder pattern. * @see SocketOptionBuilder#builder() */ public static SocketOptionBuilder builder() { return SocketOptionBuilder.builder(); } } }
if (opts == null) { opts = new Options(); } Url.ParsedURI parsed = Url.parse(uri); URI source = parsed.uri; String id = parsed.id; boolean sameNamespace = managers.containsKey(id) && managers.get(id).nsps.containsKey(source.getPath()); boolean newConnection = opts.forceNew || !opts.multiplex || sameNamespace; Manager io; String query = source.getQuery(); if (query != null && (opts.query == null || opts.query.isEmpty())) { opts.query = query; } if (newConnection) { if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("ignoring socket cache for %s", source)); } io = new Manager(source, opts); } else { if (!managers.containsKey(id)) { if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("new io instance for %s", source)); } managers.putIfAbsent(id, new Manager(source, opts)); } io = managers.get(id); } return io.socket(source.getPath(), opts);
525
333
858
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/client/On.java
On
on
class On { private On() {} public static Handle on(final Emitter obj, final String ev, final Emitter.Listener fn) {<FILL_FUNCTION_BODY>} public interface Handle { void destroy(); } }
obj.on(ev, fn); return new Handle() { @Override public void destroy() { obj.off(ev, fn); } };
68
47
115
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/client/Url.java
ParsedURI
parse
class ParsedURI { public final URI uri; public final String id; public ParsedURI(URI uri, String id) { this.uri = uri; this.id = id; } } public static ParsedURI parse(URI uri) {<FILL_FUNCTION_BODY>
String protocol = uri.getScheme(); if (protocol == null || !protocol.matches("^https?|wss?$")) { protocol = "https"; } int port = uri.getPort(); if (port == -1) { if ("http".equals(protocol) || "ws".equals(protocol)) { port = 80; } else if ("https".equals(protocol) || "wss".equals(protocol)) { port = 443; } } String path = uri.getRawPath(); if (path == null || path.length() == 0) { path = "/"; } String userInfo = uri.getRawUserInfo(); String query = uri.getRawQuery(); String fragment = uri.getRawFragment(); String _host = uri.getHost(); if (_host == null) { // might happen on some of Samsung Devices such as S4. _host = extractHostFromAuthorityPart(uri.getRawAuthority()); } URI completeUri = URI.create(protocol + "://" + (userInfo != null ? userInfo + "@" : "") + _host + (port != -1 ? ":" + port : "") + path + (query != null ? "?" + query : "") + (fragment != null ? "#" + fragment : "")); String id = protocol + "://" + _host + ":" + port; return new ParsedURI(completeUri, id);
85
387
472
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/hasbinary/HasBinary.java
HasBinary
_hasBinary
class HasBinary { private static final Logger logger = Logger.getLogger(HasBinary.class.getName()); private HasBinary() {} public static boolean hasBinary(Object data) { return _hasBinary(data); } private static boolean _hasBinary(Object obj) {<FILL_FUNCTION_BODY>} }
if (obj == null) return false; if (obj instanceof byte[]) { return true; } if (obj instanceof JSONArray) { JSONArray _obj = (JSONArray)obj; int length = _obj.length(); for (int i = 0; i < length; i++) { Object v; try { v = _obj.isNull(i) ? null : _obj.get(i); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while retrieving data from JSONArray", e); return false; } if (_hasBinary(v)) { return true; } } } else if (obj instanceof JSONObject) { JSONObject _obj = (JSONObject)obj; Iterator keys = _obj.keys(); while (keys.hasNext()) { String key = (String)keys.next(); Object v; try { v = _obj.get(key); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while retrieving data from JSONObject", e); return false; } if (_hasBinary(v)) { return true; } } } return false;
91
331
422
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/parser/Binary.java
Binary
_deconstructPacket
class Binary { private static final String KEY_PLACEHOLDER = "_placeholder"; private static final String KEY_NUM = "num"; private static final Logger logger = Logger.getLogger(Binary.class.getName()); @SuppressWarnings("unchecked") public static DeconstructedPacket deconstructPacket(Packet packet) { List<byte[]> buffers = new ArrayList<>(); packet.data = _deconstructPacket(packet.data, buffers); packet.attachments = buffers.size(); DeconstructedPacket result = new DeconstructedPacket(); result.packet = packet; result.buffers = buffers.toArray(new byte[buffers.size()][]); return result; } private static Object _deconstructPacket(Object data, List<byte[]> buffers) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") public static Packet reconstructPacket(Packet packet, byte[][] buffers) { packet.data = _reconstructPacket(packet.data, buffers); packet.attachments = -1; return packet; } private static Object _reconstructPacket(Object data, byte[][] buffers) { if (data instanceof JSONArray) { JSONArray _data = (JSONArray)data; int len = _data.length(); for (int i = 0; i < len; i ++) { try { _data.put(i, _reconstructPacket(_data.get(i), buffers)); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while putting packet data to JSONObject", e); return null; } } return _data; } else if (data instanceof JSONObject) { JSONObject _data = (JSONObject)data; if (_data.optBoolean(KEY_PLACEHOLDER)) { int num = _data.optInt(KEY_NUM, -1); return num >= 0 && num < buffers.length ? buffers[num] : null; } Iterator<?> iterator = _data.keys(); while (iterator.hasNext()) { String key = (String)iterator.next(); try { _data.put(key, _reconstructPacket(_data.get(key), buffers)); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while putting data to JSONObject", e); return null; } } return _data; } return data; } public static class DeconstructedPacket { public Packet packet; public byte[][] buffers; } }
if (data == null) return null; if (data instanceof byte[]) { JSONObject placeholder = new JSONObject(); try { placeholder.put(KEY_PLACEHOLDER, true); placeholder.put(KEY_NUM, buffers.size()); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while putting data to JSONObject", e); return null; } buffers.add((byte[])data); return placeholder; } else if (data instanceof JSONArray) { JSONArray newData = new JSONArray(); JSONArray _data = (JSONArray)data; int len = _data.length(); for (int i = 0; i < len; i ++) { try { newData.put(i, _deconstructPacket(_data.get(i), buffers)); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while putting packet data to JSONObject", e); return null; } } return newData; } else if (data instanceof JSONObject) { JSONObject newData = new JSONObject(); JSONObject _data = (JSONObject)data; Iterator<?> iterator = _data.keys(); while (iterator.hasNext()) { String key = (String)iterator.next(); try { newData.put(key, _deconstructPacket(_data.get(key), buffers)); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while putting data to JSONObject", e); return null; } } return newData; } return data;
707
432
1,139
<no_super_class>
socketio_socket.io-client-java
socket.io-client-java/src/main/java/io/socket/parser/IOParser.java
Decoder
decodeString
class Decoder implements Parser.Decoder { /*package*/ BinaryReconstructor reconstructor; private Decoder.Callback onDecodedCallback; public Decoder() { this.reconstructor = null; } @Override public void add(String obj) { Packet packet = decodeString(obj); if (BINARY_EVENT == packet.type || BINARY_ACK == packet.type) { this.reconstructor = new BinaryReconstructor(packet); if (this.reconstructor.reconPack.attachments == 0) { if (this.onDecodedCallback != null) { this.onDecodedCallback.call(packet); } } } else { if (this.onDecodedCallback != null) { this.onDecodedCallback.call(packet); } } } @Override public void add(byte[] obj) { if (this.reconstructor == null) { throw new RuntimeException("got binary data when not reconstructing a packet"); } else { Packet packet = this.reconstructor.takeBinaryData(obj); if (packet != null) { this.reconstructor = null; if (this.onDecodedCallback != null) { this.onDecodedCallback.call(packet); } } } } private static Packet decodeString(String str) {<FILL_FUNCTION_BODY>} private static boolean isPayloadValid(int type, Object payload) { switch (type) { case Parser.CONNECT: case Parser.CONNECT_ERROR: return payload instanceof JSONObject; case Parser.DISCONNECT: return payload == null; case Parser.EVENT: case Parser.BINARY_EVENT: return payload instanceof JSONArray && ((JSONArray) payload).length() > 0 && !((JSONArray) payload).isNull(0); case Parser.ACK: case Parser.BINARY_ACK: return payload instanceof JSONArray; default: return false; } } @Override public void destroy() { if (this.reconstructor != null) { this.reconstructor.finishReconstruction(); } this.onDecodedCallback = null; } @Override public void onDecoded (Callback callback) { this.onDecodedCallback = callback; } }
int i = 0; int length = str.length(); Packet<Object> p = new Packet<>(Character.getNumericValue(str.charAt(0))); if (p.type < 0 || p.type > types.length - 1) { throw new DecodingException("unknown packet type " + p.type); } if (BINARY_EVENT == p.type || BINARY_ACK == p.type) { if (!str.contains("-") || length <= i + 1) { throw new DecodingException("illegal attachments"); } StringBuilder attachments = new StringBuilder(); while (str.charAt(++i) != '-') { attachments.append(str.charAt(i)); } p.attachments = Integer.parseInt(attachments.toString()); } if (length > i + 1 && '/' == str.charAt(i + 1)) { StringBuilder nsp = new StringBuilder(); while (true) { ++i; char c = str.charAt(i); if (',' == c) break; nsp.append(c); if (i + 1 == length) break; } p.nsp = nsp.toString(); } else { p.nsp = "/"; } if (length > i + 1){ Character next = str.charAt(i + 1); if (Character.getNumericValue(next) > -1) { StringBuilder id = new StringBuilder(); while (true) { ++i; char c = str.charAt(i); if (Character.getNumericValue(c) < 0) { --i; break; } id.append(c); if (i + 1 == length) break; } try { p.id = Integer.parseInt(id.toString()); } catch (NumberFormatException e){ throw new DecodingException("invalid payload"); } } } if (length > i + 1){ try { str.charAt(++i); p.data = new JSONTokener(str.substring(i)).nextValue(); } catch (JSONException e) { logger.log(Level.WARNING, "An error occured while retrieving data from JSONTokener", e); throw new DecodingException("invalid payload"); } if (!isPayloadValid(p.type, p.data)) { throw new DecodingException("invalid payload"); } } if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("decoded %s as %s", str, p)); } return p;
639
698
1,337
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/AbstractLifeCycle.java
AbstractLifeCycle
ensureStarted
class AbstractLifeCycle implements LifeCycle { private final AtomicBoolean isStarted = new AtomicBoolean(false); @Override public void startup() throws LifeCycleException { if (isStarted.compareAndSet(false, true)) { return; } throw new LifeCycleException("this component has started"); } @Override public void shutdown() throws LifeCycleException { if (isStarted.compareAndSet(true, false)) { return; } throw new LifeCycleException("this component has closed"); } @Override public boolean isStarted() { return isStarted.get(); } /** * ensure the component has been startup before providing service. */ protected void ensureStarted() {<FILL_FUNCTION_BODY>} }
if (!isStarted()) { throw new LifeCycleException(String.format( "Component(%s) has not been started yet, please startup first!", getClass() .getSimpleName())); }
215
57
272
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/AbstractRemotingProcessor.java
ProcessTask
run
class ProcessTask implements Runnable { RemotingContext ctx; T msg; public ProcessTask(RemotingContext ctx, T msg) { this.ctx = ctx; this.msg = msg; } @Override public void run() {<FILL_FUNCTION_BODY>} }
try { AbstractRemotingProcessor.this.doProcess(ctx, msg); } catch (Throwable e) { //protect the thread running this task String remotingAddress = RemotingUtil.parseRemoteAddress(ctx.getChannelContext() .channel()); logger .error( "Exception caught when process rpc request command in AbstractRemotingProcessor, Id=" + msg.getId() + "! Invoke source address is [" + remotingAddress + "].", e); }
86
127
213
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/AbstractRemotingServer.java
AbstractRemotingServer
startup
class AbstractRemotingServer extends AbstractLifeCycle implements RemotingServer, ConfigurableInstance { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); private String ip; private int port; private final BoltOptions options; private final GlobalSwitch globalSwitch; private final ConfigContainer configContainer; public AbstractRemotingServer(int port) { this(new InetSocketAddress(port).getAddress().getHostAddress(), port); } public AbstractRemotingServer(String ip, int port) { if (port < 0 || port > 65535) { throw new IllegalArgumentException(String.format( "Illegal port value: %d, which should between 0 and 65535.", port)); } this.ip = ip; this.port = port; this.options = new BoltOptions(); this.globalSwitch = new GlobalSwitch(); this.configContainer = new DefaultConfigContainer(); } @Override @Deprecated public void init() { // Do not call this method, it will be removed in the next version } @Override @Deprecated public boolean start() { startup(); return true; } @Override @Deprecated public boolean stop() { shutdown(); return true; } @Override public void startup() throws LifeCycleException {<FILL_FUNCTION_BODY>} @Override public void shutdown() throws LifeCycleException { super.shutdown(); if (!doStop()) { throw new LifeCycleException("doStop fail"); } } @Override public String ip() { return ip; } @Override public int port() { return port; } /** * override the random port zero with the actual binding port value. * @param port local binding port */ protected void setLocalBindingPort(int port) { if (port() == 0) { this.port = port; } } protected abstract void doInit(); protected abstract boolean doStart() throws InterruptedException; protected abstract boolean doStop(); @Override public <T> T option(BoltOption<T> option) { return options.option(option); } @Override public <T> Configuration option(BoltOption<T> option, T value) { options.option(option, value); return this; } @Override @Deprecated public ConfigContainer conf() { return this.configContainer; } @Override @Deprecated public GlobalSwitch switches() { return this.globalSwitch; } @Override public void initWriteBufferWaterMark(int low, int high) { option(BoltServerOption.NETTY_BUFFER_LOW_WATER_MARK, low); option(BoltServerOption.NETTY_BUFFER_HIGH_WATER_MARK, high); } @Override public int netty_buffer_low_watermark() { return option(BoltServerOption.NETTY_BUFFER_LOW_WATER_MARK); } @Override public int netty_buffer_high_watermark() { return option(BoltServerOption.NETTY_BUFFER_HIGH_WATER_MARK); } }
super.startup(); try { doInit(); logger.warn("Prepare to start server on port {} ", port); if (doStart()) { logger.warn("Server started on port {}", port); } else { logger.warn("Failed starting server on port {}", port); throw new LifeCycleException("Failed starting server on port: " + port); } } catch (Throwable t) { this.shutdown();// do stop to ensure close resources created during doInit() throw new IllegalStateException("ERROR: Failed to start the Server!", t); }
889
154
1,043
<methods>public non-sealed void <init>() ,public boolean isStarted() ,public void shutdown() throws com.alipay.remoting.LifeCycleException,public void startup() throws com.alipay.remoting.LifeCycleException<variables>private final java.util.concurrent.atomic.AtomicBoolean isStarted
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ConnectionEventListener.java
ConnectionEventListener
onEvent
class ConnectionEventListener { private ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>> processors = new ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>>( 3); /** * Dispatch events. * * @param type ConnectionEventType * @param remoteAddress remoting address * @param connection Connection */ public void onEvent(ConnectionEventType type, String remoteAddress, Connection connection) {<FILL_FUNCTION_BODY>} /** * Add event processor. * * @param type ConnectionEventType * @param processor ConnectionEventProcessor */ public void addConnectionEventProcessor(ConnectionEventType type, ConnectionEventProcessor processor) { List<ConnectionEventProcessor> processorList = this.processors.get(type); if (processorList == null) { this.processors.putIfAbsent(type, new CopyOnWriteArrayList<ConnectionEventProcessor>()); processorList = this.processors.get(type); } processorList.add(processor); } }
List<ConnectionEventProcessor> processorList = this.processors.get(type); if (processorList != null) { for (ConnectionEventProcessor processor : processorList) { processor.onEvent(remoteAddress, connection); } }
270
65
335
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ConnectionPool.java
ConnectionPool
get
class ConnectionPool implements Scannable { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); private CopyOnWriteArrayList<Connection> connections; private ConnectionSelectStrategy strategy; private volatile long lastAccessTimestamp; private volatile boolean asyncCreationDone; /** * Constructor * * @param strategy ConnectionSelectStrategy */ public ConnectionPool(ConnectionSelectStrategy strategy) { this.strategy = strategy; this.connections = new CopyOnWriteArrayList<Connection>(); this.lastAccessTimestamp = System.currentTimeMillis(); this.asyncCreationDone = true; } /** * add a connection * * @param connection Connection */ public void add(Connection connection) { markAccess(); if (null == connection) { return; } boolean res = connections.addIfAbsent(connection); if (res) { connection.increaseRef(); } } /** * check weather a connection already added * * @param connection Connection * @return whether this pool contains the target connection */ public boolean contains(Connection connection) { return connections.contains(connection); } /** * removeAndTryClose a connection * * @param connection Connection */ public void removeAndTryClose(Connection connection) { if (null == connection) { return; } boolean res = connections.remove(connection); if (res) { connection.decreaseRef(); } if (connection.noRef()) { connection.close(); } } /** * remove all connections */ public void removeAllAndTryClose() { for (Connection conn : connections) { removeAndTryClose(conn); } connections.clear(); } /** * get a connection * * @return Connection */ public Connection get() {<FILL_FUNCTION_BODY>} /** * get all connections * * @return Connection List */ public List<Connection> getAll() { return new ArrayList<Connection>(connections); } /** * connection pool size * * @return pool size */ public int size() { return connections.size(); } /** * is connection pool empty * * @return true if this connection pool has no connection */ public boolean isEmpty() { return connections.isEmpty(); } /** * Getter method for property <tt>lastAccessTimestamp</tt>. * * @return property value of lastAccessTimestamp */ public long getLastAccessTimestamp() { return lastAccessTimestamp; } /** * do mark the time stamp when access this pool */ private void markAccess() { lastAccessTimestamp = System.currentTimeMillis(); } /** * is async create connection done * @return true if async create connection done */ public boolean isAsyncCreationDone() { return asyncCreationDone; } /** * do mark async create connection done */ public void markAsyncCreationDone() { asyncCreationDone = true; } /** * do mark async create connection start */ public void markAsyncCreationStart() { asyncCreationDone = false; } @Override public void scan() { if (null != connections && !connections.isEmpty()) { for (Connection conn : connections) { if (!conn.isFine()) { logger.warn( "Remove bad connection when scanning conns of ConnectionPool - {}:{}", conn.getRemoteIP(), conn.getRemotePort()); conn.close(); removeAndTryClose(conn); } } } } }
if (null != connections) { List<Connection> snapshot = new ArrayList<Connection>(connections); if (snapshot.size() > 0) { return strategy.select(snapshot); } else { return null; } } else { return null; }
1,004
79
1,083
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/CustomSerializerManager.java
CustomSerializerManager
registerCustomSerializer
class CustomSerializerManager { /** For rpc */ private static ConcurrentHashMap<String/* class name */, CustomSerializer> classCustomSerializer = new ConcurrentHashMap<String, CustomSerializer>(); /** For user defined command */ private static ConcurrentHashMap<CommandCode/* command code */, CustomSerializer> commandCustomSerializer = new ConcurrentHashMap<CommandCode, CustomSerializer>(); /** * Register custom serializer for class name. * * @param className * @param serializer * @return */ public static void registerCustomSerializer(String className, CustomSerializer serializer) {<FILL_FUNCTION_BODY>} /** * Get the custom serializer for class name. * * @param className * @return */ public static CustomSerializer getCustomSerializer(String className) { if (!classCustomSerializer.isEmpty()) { return classCustomSerializer.get(className); } return null; } /** * Register custom serializer for command code. * * @param code * @param serializer * @return */ public static void registerCustomSerializer(CommandCode code, CustomSerializer serializer) { CustomSerializer prevSerializer = commandCustomSerializer.putIfAbsent(code, serializer); if (prevSerializer != null) { throw new RuntimeException("CustomSerializer has been registered for command code: " + code + ", the custom serializer is: " + prevSerializer.getClass().getName()); } } /** * Get the custom serializer for command code. * * @param code * @return */ public static CustomSerializer getCustomSerializer(CommandCode code) { if (!commandCustomSerializer.isEmpty()) { return commandCustomSerializer.get(code); } return null; } /** * clear the custom serializers. */ public static void clear() { classCustomSerializer.clear(); commandCustomSerializer.clear(); } }
CustomSerializer prevSerializer = classCustomSerializer.putIfAbsent(className, serializer); if (prevSerializer != null) { throw new RuntimeException("CustomSerializer has been registered for class: " + className + ", the custom serializer is: " + prevSerializer.getClass().getName()); }
510
78
588
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/DefaultBizContext.java
DefaultBizContext
getConnection
class DefaultBizContext implements BizContext { /** * remoting context */ private RemotingContext remotingCtx; /** * Constructor with RemotingContext * * @param remotingCtx */ public DefaultBizContext(RemotingContext remotingCtx) { this.remotingCtx = remotingCtx; } /** * get remoting context * * @return RemotingContext */ protected RemotingContext getRemotingCtx() { return this.remotingCtx; } /** * @see com.alipay.remoting.BizContext#getRemoteAddress() */ @Override public String getRemoteAddress() { if (null != this.remotingCtx) { ChannelHandlerContext channelCtx = this.remotingCtx.getChannelContext(); Channel channel = channelCtx.channel(); if (null != channel) { return RemotingUtil.parseRemoteAddress(channel); } } return "UNKNOWN_ADDRESS"; } /** * @see com.alipay.remoting.BizContext#getRemoteHost() */ @Override public String getRemoteHost() { if (null != this.remotingCtx) { ChannelHandlerContext channelCtx = this.remotingCtx.getChannelContext(); Channel channel = channelCtx.channel(); if (null != channel) { return RemotingUtil.parseRemoteIP(channel); } } return "UNKNOWN_HOST"; } /** * @see com.alipay.remoting.BizContext#getRemotePort() */ @Override public int getRemotePort() { if (null != this.remotingCtx) { ChannelHandlerContext channelCtx = this.remotingCtx.getChannelContext(); Channel channel = channelCtx.channel(); if (null != channel) { return RemotingUtil.parseRemotePort(channel); } } return -1; } /** * @see BizContext#getConnection() */ @Override public Connection getConnection() {<FILL_FUNCTION_BODY>} /** * @see com.alipay.remoting.BizContext#isRequestTimeout() */ @Override public boolean isRequestTimeout() { return this.remotingCtx.isRequestTimeout(); } /** * get the timeout value from rpc client. * * @return */ @Override public int getClientTimeout() { return this.remotingCtx.getTimeout(); } /** * get the arrive time stamp * * @return */ @Override public long getArriveTimestamp() { return this.remotingCtx.getArriveTimestamp(); } /** * @see com.alipay.remoting.BizContext#put(java.lang.String, java.lang.String) */ @Override public void put(String key, String value) { } /** * @see com.alipay.remoting.BizContext#get(java.lang.String) */ @Override public String get(String key) { return null; } /** * @see BizContext#getInvokeContext() */ @Override public InvokeContext getInvokeContext() { return this.remotingCtx.getInvokeContext(); } }
if (null != this.remotingCtx) { return this.remotingCtx.getConnection(); } return null;
921
39
960
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/DefaultConnectionMonitor.java
DefaultConnectionMonitor
startup
class DefaultConnectionMonitor extends AbstractLifeCycle { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); private final ConnectionManager connectionManager; private final ConnectionMonitorStrategy strategy; private ScheduledThreadPoolExecutor executor; public DefaultConnectionMonitor(ConnectionMonitorStrategy strategy, ConnectionManager connectionManager) { if (strategy == null) { throw new IllegalArgumentException("null strategy"); } if (connectionManager == null) { throw new IllegalArgumentException("null connectionManager"); } this.strategy = strategy; this.connectionManager = connectionManager; } @Override public void startup() throws LifeCycleException {<FILL_FUNCTION_BODY>} @Override public void shutdown() throws LifeCycleException { super.shutdown(); executor.purge(); executor.shutdown(); } /** * Start schedule task * please use {@link DefaultConnectionMonitor#startup()} instead */ @Deprecated public void start() { startup(); } /** * cancel task and shutdown executor * please use {@link DefaultConnectionMonitor#shutdown()} instead */ @Deprecated public void destroy() { shutdown(); } }
super.startup(); /* initial delay to execute schedule task, unit: ms */ long initialDelay = ConfigManager.conn_monitor_initial_delay(); /* period of schedule task, unit: ms*/ long period = ConfigManager.conn_monitor_period(); this.executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory( "ConnectionMonitorThread", true), new ThreadPoolExecutor.AbortPolicy()); this.executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { Map<String, RunStateRecordedFutureTask<ConnectionPool>> connPools = null; if (connectionManager instanceof DefaultConnectionManager) { connPools = ((DefaultConnectionManager) connectionManager).getConnPools(); } strategy.monitor(connPools); } catch (Exception e) { logger.warn("MonitorTask error", e); } } }, initialDelay, period, TimeUnit.MILLISECONDS);
333
256
589
<methods>public non-sealed void <init>() ,public boolean isStarted() ,public void shutdown() throws com.alipay.remoting.LifeCycleException,public void startup() throws com.alipay.remoting.LifeCycleException<variables>private final java.util.concurrent.atomic.AtomicBoolean isStarted
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/NamedThreadFactory.java
NamedThreadFactory
newThread
class NamedThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final AtomicInteger threadNumber = new AtomicInteger(1); private final ThreadGroup group; private final String namePrefix; private final boolean isDaemon; public NamedThreadFactory() { this("ThreadPool"); } public NamedThreadFactory(String name) { this(name, false); } public NamedThreadFactory(String prefix, boolean daemon) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = prefix + "-" + poolNumber.getAndIncrement() + "-thread-"; isDaemon = daemon; } /** * Create a thread. * * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) */ @Override public Thread newThread(Runnable r) {<FILL_FUNCTION_BODY>} }
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); t.setDaemon(isDaemon); if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t;
286
89
375
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ProcessorManager.java
ProcessorManager
registerDefaultProcessor
class ProcessorManager { private static final Logger logger = BoltLoggerFactory .getLogger("CommonDefault"); private ConcurrentHashMap<CommandCode, RemotingProcessor<?>> cmd2processors = new ConcurrentHashMap<CommandCode, RemotingProcessor<?>>( 4); private RemotingProcessor<?> defaultProcessor; /** The default executor, if no executor is set for processor, this one will be used */ private ExecutorService defaultExecutor; private int minPoolSize = ConfigManager .default_tp_min_size(); private int maxPoolSize = ConfigManager .default_tp_max_size(); private int queueSize = ConfigManager .default_tp_queue_size(); private long keepAliveTime = ConfigManager .default_tp_keepalive_time(); public ProcessorManager() { defaultExecutor = new ThreadPoolExecutor(minPoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize), new NamedThreadFactory( "Bolt-default-executor", true)); } /** * Register processor to process command that has the command code of cmdCode. * * @param cmdCode * @param processor */ public void registerProcessor(CommandCode cmdCode, RemotingProcessor<?> processor) { if (this.cmd2processors.containsKey(cmdCode)) { logger .warn( "Processor for cmd={} is already registered, the processor is {}, and changed to {}", cmdCode, cmd2processors.get(cmdCode).getClass().getName(), processor.getClass() .getName()); } this.cmd2processors.put(cmdCode, processor); } /** * Register the default processor to process command with no specific processor registered. * * @param processor */ public void registerDefaultProcessor(RemotingProcessor<?> processor) {<FILL_FUNCTION_BODY>} /** * Get the specific processor with command code of cmdCode if registered, otherwise the default processor is returned. * * @param cmdCode * @return */ public RemotingProcessor<?> getProcessor(CommandCode cmdCode) { RemotingProcessor<?> processor = this.cmd2processors.get(cmdCode); if (processor != null) { return processor; } return this.defaultProcessor; } /** * Getter method for property <tt>defaultExecutor</tt>. * * @return property value of defaultExecutor */ public ExecutorService getDefaultExecutor() { return defaultExecutor; } /** * Set the default executor. * * @param executor */ public void registerDefaultExecutor(ExecutorService executor) { this.defaultExecutor = executor; } }
if (this.defaultProcessor == null) { this.defaultProcessor = processor; } else { throw new IllegalStateException("The defaultProcessor has already been registered: " + this.defaultProcessor.getClass()); }
757
60
817
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ProtocolCode.java
ProtocolCode
equals
class ProtocolCode { /** bytes to represent protocol code */ byte[] version; private ProtocolCode(byte... version) { this.version = version; } public static ProtocolCode fromBytes(byte... version) { return new ProtocolCode(version); } /** * get the first single byte if your protocol code is single code. * @return */ public byte getFirstByte() { return this.version[0]; } public int length() { return this.version.length; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Arrays.hashCode(version); } @Override public String toString() { return "ProtocolVersion{" + "version=" + Arrays.toString(version) + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ProtocolCode that = (ProtocolCode) o; return Arrays.equals(version, that.version);
239
74
313
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ProtocolManager.java
ProtocolManager
registerProtocol
class ProtocolManager { private static final ConcurrentMap<ProtocolCode, Protocol> protocols = new ConcurrentHashMap<ProtocolCode, Protocol>(); public static Protocol getProtocol(ProtocolCode protocolCode) { return protocols.get(protocolCode); } public static void registerProtocol(Protocol protocol, byte... protocolCodeBytes) { registerProtocol(protocol, ProtocolCode.fromBytes(protocolCodeBytes)); } public static void registerProtocol(Protocol protocol, ProtocolCode protocolCode) {<FILL_FUNCTION_BODY>} public static Protocol unRegisterProtocol(byte protocolCode) { return ProtocolManager.protocols.remove(ProtocolCode.fromBytes(protocolCode)); } }
if (null == protocolCode || null == protocol) { throw new RuntimeException("Protocol: " + protocol + " and protocol code:" + protocolCode + " should not be null!"); } Protocol exists = ProtocolManager.protocols.putIfAbsent(protocolCode, protocol); if (exists != null) { throw new RuntimeException("Protocol for code: " + protocolCode + " already exists!"); }
180
109
289
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/RandomSelectStrategy.java
RandomSelectStrategy
select
class RandomSelectStrategy implements ConnectionSelectStrategy { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); private static final int MAX_TIMES = 5; private final Random random = new Random(); private final Configuration configuration; public RandomSelectStrategy(Configuration configuration) { this.configuration = configuration; } @Override public Connection select(List<Connection> connections) {<FILL_FUNCTION_BODY>} /** * get one connection randomly * * @param connections source connections * @return result connection */ private Connection randomGet(List<Connection> connections) { if (null == connections || connections.isEmpty()) { return null; } int size = connections.size(); int tries = 0; Connection result = null; while ((result == null || !result.isFine()) && tries++ < MAX_TIMES) { result = connections.get(this.random.nextInt(size)); } if (result != null && !result.isFine()) { result = null; } return result; } }
try { if (connections == null) { return null; } int size = connections.size(); if (size == 0) { return null; } Connection result; if (configuration != null && configuration.option(BoltClientOption.CONN_MONITOR_SWITCH)) { List<Connection> serviceStatusOnConnections = new ArrayList<Connection>(); for (Connection conn : connections) { String serviceStatus = (String) conn.getAttribute(Configs.CONN_SERVICE_STATUS); if (!StringUtils.equals(serviceStatus, Configs.CONN_SERVICE_STATUS_OFF)) { serviceStatusOnConnections.add(conn); } } if (serviceStatusOnConnections.size() == 0) { throw new Exception( "No available connection when select in RandomSelectStrategy."); } result = randomGet(serviceStatusOnConnections); } else { result = randomGet(connections); } return result; } catch (Throwable e) { logger.error("Choose connection failed using RandomSelectStrategy!", e); return null; }
293
294
587
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ReconnectManager.java
HealConnectionRunner
run
class HealConnectionRunner implements Runnable { private long lastConnectTime = -1; @Override public void run() {<FILL_FUNCTION_BODY>} }
while (isStarted()) { long start = -1; ReconnectTask task = null; try { if (this.lastConnectTime < HEAL_CONNECTION_INTERVAL) { Thread.sleep(HEAL_CONNECTION_INTERVAL); } try { task = ReconnectManager.this.tasks.take(); } catch (InterruptedException e) { // ignore } if (task == null) { continue; } start = System.currentTimeMillis(); if (!canceled.contains(task.url)) { task.run(); } else { logger.warn("Invalid reconnect request task {}, cancel list size {}", task.url, canceled.size()); } this.lastConnectTime = System.currentTimeMillis() - start; } catch (Exception e) { if (start != -1) { this.lastConnectTime = System.currentTimeMillis() - start; } if (task != null) { logger.warn("reconnect target: {} failed.", task.url, e); tasks.add(task); } } }
49
302
351
<methods>public non-sealed void <init>() ,public boolean isStarted() ,public void shutdown() throws com.alipay.remoting.LifeCycleException,public void startup() throws com.alipay.remoting.LifeCycleException<variables>private final java.util.concurrent.atomic.AtomicBoolean isStarted
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/RemotingContext.java
RemotingContext
isRequestTimeout
class RemotingContext { private ChannelHandlerContext channelContext; private boolean serverSide = false; /** whether need handle request timeout, if true, request will be discarded. The default value is true */ private boolean timeoutDiscard = true; /** request arrive time stamp */ private long arriveTimestamp; /** request timeout setting by invoke side */ private int timeout; /** rpc command type */ private int rpcCommandType; private ConcurrentHashMap<String, UserProcessor<?>> userProcessors; private InvokeContext invokeContext; /** * Constructor. * * @param ctx */ public RemotingContext(ChannelHandlerContext ctx) { this.channelContext = ctx; } /** * Constructor. * @param ctx * @param serverSide */ public RemotingContext(ChannelHandlerContext ctx, boolean serverSide) { this.channelContext = ctx; this.serverSide = serverSide; } /** * Constructor. * @param ctx * @param serverSide * @param userProcessors */ public RemotingContext(ChannelHandlerContext ctx, boolean serverSide, ConcurrentHashMap<String, UserProcessor<?>> userProcessors) { this.channelContext = ctx; this.serverSide = serverSide; this.userProcessors = userProcessors; } /** * Constructor. * @param ctx * @param invokeContext * @param serverSide * @param userProcessors */ public RemotingContext(ChannelHandlerContext ctx, InvokeContext invokeContext, boolean serverSide, ConcurrentHashMap<String, UserProcessor<?>> userProcessors) { this.channelContext = ctx; this.serverSide = serverSide; this.userProcessors = userProcessors; this.invokeContext = invokeContext; } /** * Wrap the writeAndFlush method. * * @param msg as msg * @return channel future */ public ChannelFuture writeAndFlush(RemotingCommand msg) { return this.channelContext.writeAndFlush(msg); } /** * Wrap the write method. * * @param msg as msg * @return channel future */ public ChannelFuture write(RemotingCommand msg) { return this.channelContext.write(msg); } /** * Wrap the write method. * */ public void flush() { this.channelContext.flush(); } /** * whether this request already timeout * * @return */ public boolean isRequestTimeout() {<FILL_FUNCTION_BODY>} /** * The server side * * @return */ public boolean isServerSide() { return this.serverSide; } /** * Get user processor for class name. * * @param className * @return */ public UserProcessor<?> getUserProcessor(String className) { return StringUtils.isBlank(className) ? null : this.userProcessors.get(className); } /** * Get connection from channel * * @return */ public Connection getConnection() { return ConnectionUtil.getConnectionFromChannel(channelContext.channel()); } /** * Get the channel handler context. * * @return */ public ChannelHandlerContext getChannelContext() { return channelContext; } /** * Set the channel handler context. * * @param ctx */ public void setChannelContext(ChannelHandlerContext ctx) { this.channelContext = ctx; } /** * Getter method for property <tt>invokeContext</tt>. * * @return property value of invokeContext */ public InvokeContext getInvokeContext() { return invokeContext; } /** * Setter method for property <tt>arriveTimestamp<tt>. * * @param arriveTimestamp value to be assigned to property arriveTimestamp */ public void setArriveTimestamp(long arriveTimestamp) { this.arriveTimestamp = arriveTimestamp; } /** * Getter method for property <tt>arriveTimestamp</tt>. * * @return property value of arriveTimestamp */ public long getArriveTimestamp() { return arriveTimestamp; } /** * Setter method for property <tt>timeout<tt>. * * @param timeout value to be assigned to property timeout */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * Getter method for property <tt>timeout</tt>. * * @return property value of timeout */ public int getTimeout() { return timeout; } /** * Setter method for property <tt>rpcCommandType<tt>. * * @param rpcCommandType value to be assigned to property rpcCommandType */ public void setRpcCommandType(int rpcCommandType) { this.rpcCommandType = rpcCommandType; } public boolean isTimeoutDiscard() { return timeoutDiscard; } public RemotingContext setTimeoutDiscard(boolean failFastEnabled) { this.timeoutDiscard = failFastEnabled; return this; } }
if (this.timeout > 0 && (this.rpcCommandType != RpcCommandType.REQUEST_ONEWAY) && (System.currentTimeMillis() - this.arriveTimestamp) > this.timeout) { return true; } return false;
1,419
70
1,489
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ScheduledDisconnectStrategy.java
ScheduledDisconnectStrategy
filter
class ScheduledDisconnectStrategy implements ConnectionMonitorStrategy { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); private final int connectionThreshold; private final Random random; public ScheduledDisconnectStrategy() { this.connectionThreshold = ConfigManager.conn_threshold(); this.random = new Random(); } /** * This method only invoked in ScheduledDisconnectStrategy, so no need to be exposed. * This method will be remove in next version, do not use this method. * * The user cannot call ScheduledDisconnectStrategy#filter, so modifying the implementation of this method is safe. * * @param connections connections from a connection pool */ @Deprecated @Override public Map<String, List<Connection>> filter(List<Connection> connections) {<FILL_FUNCTION_BODY>} @Override public void monitor(Map<String, RunStateRecordedFutureTask<ConnectionPool>> connPools) { try { if (connPools == null || connPools.size() == 0) { return; } for (Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>> entry : connPools .entrySet()) { String poolKey = entry.getKey(); ConnectionPool pool = FutureTaskUtil.getFutureTaskResult(entry.getValue(), logger); List<Connection> serviceOnConnections = new ArrayList<Connection>(); List<Connection> serviceOffConnections = new ArrayList<Connection>(); for (Connection connection : pool.getAll()) { if (isConnectionOn(connection)) { serviceOnConnections.add(connection); } else { serviceOffConnections.add(connection); } } if (serviceOnConnections.size() > connectionThreshold) { Connection freshSelectConnect = serviceOnConnections.get(random .nextInt(serviceOnConnections.size())); freshSelectConnect.setAttribute(Configs.CONN_SERVICE_STATUS, Configs.CONN_SERVICE_STATUS_OFF); serviceOffConnections.add(freshSelectConnect); } else { if (logger.isInfoEnabled()) { logger.info("serviceOnConnections({}) size[{}], CONNECTION_THRESHOLD[{}].", poolKey, serviceOnConnections.size(), connectionThreshold); } } for (Connection offConn : serviceOffConnections) { if (offConn.isInvokeFutureMapFinish()) { if (offConn.isFine()) { offConn.close(); } } else { if (logger.isInfoEnabled()) { logger.info("Address={} won't close at this schedule turn", RemotingUtil.parseRemoteAddress(offConn.getChannel())); } } } } } catch (Exception e) { logger.error("ScheduledDisconnectStrategy monitor error", e); } } private boolean isConnectionOn(Connection connection) { String serviceStatus = (String) connection.getAttribute(Configs.CONN_SERVICE_STATUS); return serviceStatus == null || Boolean.parseBoolean(serviceStatus); } }
List<Connection> serviceOnConnections = new ArrayList<Connection>(); List<Connection> serviceOffConnections = new ArrayList<Connection>(); Map<String, List<Connection>> filteredConnections = new ConcurrentHashMap<String, List<Connection>>(); for (Connection connection : connections) { if (isConnectionOn(connection)) { serviceOnConnections.add(connection); } else { serviceOffConnections.add(connection); } } filteredConnections.put(Configs.CONN_SERVICE_STATUS_ON, serviceOnConnections); filteredConnections.put(Configs.CONN_SERVICE_STATUS_OFF, serviceOffConnections); return filteredConnections;
814
179
993
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/ServerIdleHandler.java
ServerIdleHandler
userEventTriggered
class ServerIdleHandler extends ChannelDuplexHandler { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); /** * @see io.netty.channel.ChannelInboundHandlerAdapter#userEventTriggered(io.netty.channel.ChannelHandlerContext, java.lang.Object) */ @Override public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>} }
if (evt instanceof IdleStateEvent) { try { logger.warn("Connection idle, close it from server side: {}", RemotingUtil.parseRemoteAddress(ctx.channel())); ctx.close(); } catch (Exception e) { logger.warn("Exception caught when closing connection in ServerIdleHandler.", e); } } else { super.userEventTriggered(ctx, evt); }
123
111
234
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/Url.java
Url
setConnNum
class Url { /** origin url */ private String originUrl; /** ip, can be number format or hostname format*/ private String ip; /** port, should be integer between (0, 65535]*/ private int port; /** unique key of this url */ private String uniqueKey; /** URL args: timeout value when do connect */ private int connectTimeout; /** URL args: protocol */ private byte protocol; /** URL args: version */ private byte version = RpcProtocolV2.PROTOCOL_VERSION_1; /** URL agrs: connection number */ private int connNum = Configs.DEFAULT_CONN_NUM_PER_URL; /** URL agrs: whether need warm up connection */ private boolean connWarmup; /** URL agrs: all parsed args of each originUrl */ private Properties properties; /** * Constructor with originUrl * * @param originUrl */ protected Url(String originUrl) { this.originUrl = originUrl; } /** * Constructor with ip and port * <ul> * <li>Initialize ip:port as {@link Url#originUrl} </li> * <li>Initialize {@link Url#originUrl} as {@link Url#uniqueKey} </li> * </ul> * * @param ip * @param port */ public Url(String ip, int port) { this(ip + RemotingAddressParser.COLON + port); this.ip = ip; this.port = port; this.uniqueKey = this.originUrl; } /** * Constructor with originUrl, ip and port * * <ul> * <li>Initialize @param originUrl as {@link Url#originUrl} </li> * <li>Initialize ip:port as {@link Url#uniqueKey} </li> * </ul> * * @param originUrl * @param ip * @param port */ public Url(String originUrl, String ip, int port) { this(originUrl); this.ip = ip; this.port = port; this.uniqueKey = ip + RemotingAddressParser.COLON + port; } /** * Constructor with originUrl, ip, port and properties * * <ul> * <li>Initialize @param originUrl as {@link Url#originUrl} </li> * <li>Initialize ip:port as {@link Url#uniqueKey} </li> * <li>Initialize @param properties as {@link Url#properties} </li> * </ul> * * @param originUrl * @param ip * @param port * @param properties */ public Url(String originUrl, String ip, int port, Properties properties) { this(originUrl, ip, port); this.properties = properties; } /** * Constructor with originUrl, ip, port, uniqueKey and properties * * <ul> * <li>Initialize @param originUrl as {@link Url#originUrl} </li> * <li>Initialize @param uniqueKey as {@link Url#uniqueKey} </li> * <li>Initialize @param properties as {@link Url#properties} </li> * </ul> * * @param originUrl * @param ip * @param port * @param uniqueKey * @param properties */ public Url(String originUrl, String ip, int port, String uniqueKey, Properties properties) { this(originUrl, ip, port); this.uniqueKey = uniqueKey; this.properties = properties; } /** * Get property value according to property key * * @param key property key * @return property value */ public String getProperty(String key) { if (properties == null) { return null; } return properties.getProperty(key); } public String getOriginUrl() { return originUrl; } public String getIp() { return ip; } public int getPort() { return port; } public String getUniqueKey() { return uniqueKey; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { if (connectTimeout <= 0) { throw new IllegalArgumentException("Illegal value of connection number [" + connNum + "], must be a positive integer]."); } this.connectTimeout = connectTimeout; } public byte getProtocol() { return protocol; } public void setProtocol(byte protocol) { this.protocol = protocol; } public int getConnNum() { return connNum; } public void setConnNum(int connNum) {<FILL_FUNCTION_BODY>} public boolean isConnWarmup() { return connWarmup; } public void setConnWarmup(boolean connWarmup) { this.connWarmup = connWarmup; } public Properties getProperties() { return properties; } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Url url = (Url) obj; if (this.getOriginUrl().equals(url.getOriginUrl())) { return true; } else { return false; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.getOriginUrl() == null) ? 0 : this.getOriginUrl().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(32); sb.append("Origin url [").append(this.originUrl).append("], Unique key [") .append(this.uniqueKey).append("]."); return sb.toString(); } /** Use {@link SoftReference} to cache parsed urls. Key is the original url. */ public static ConcurrentHashMap<String, SoftReference<Url>> parsedUrls = new ConcurrentHashMap<String, SoftReference<Url>>(); /** for unit test only, indicate this object have already been GCed */ public static volatile boolean isCollected = false; /** logger */ private static final Logger logger = BoltLoggerFactory .getLogger("RpcRemoting"); @Override protected void finalize() { try { isCollected = true; parsedUrls.remove(this.getOriginUrl()); } catch (Exception e) { logger.error("Exception occurred when do finalize for Url [{}].", this.getOriginUrl(), e); } } public byte getVersion() { return version; } public void setVersion(byte version) { this.version = version; } }
if (connNum <= 0 || connNum > Configs.MAX_CONN_NUM_PER_URL) { throw new IllegalArgumentException("Illegal value of connection number [" + connNum + "], must be an integer between [" + Configs.DEFAULT_CONN_NUM_PER_URL + ", " + Configs.MAX_CONN_NUM_PER_URL + "]."); } this.connNum = connNum;
1,907
110
2,017
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java
ProtocolCodeBasedDecoder
decode
class ProtocolCodeBasedDecoder extends AbstractBatchDecoder { /** by default, suggest design a single byte for protocol version. */ public static final int DEFAULT_PROTOCOL_VERSION_LENGTH = 1; /** protocol version should be a positive number, we use -1 to represent illegal */ public static final int DEFAULT_ILLEGAL_PROTOCOL_VERSION_LENGTH = -1; /** the length of protocol code */ protected int protocolCodeLength; public ProtocolCodeBasedDecoder(int protocolCodeLength) { super(); this.protocolCodeLength = protocolCodeLength; } /** * decode the protocol code * * @param in input byte buf * @return an instance of ProtocolCode */ protected ProtocolCode decodeProtocolCode(ByteBuf in) { if (in.readableBytes() >= protocolCodeLength) { byte[] protocolCodeBytes = new byte[protocolCodeLength]; in.readBytes(protocolCodeBytes); return ProtocolCode.fromBytes(protocolCodeBytes); } return null; } /** * decode the protocol version * * @param in input byte buf * @return a byte to represent protocol version */ protected byte decodeProtocolVersion(ByteBuf in) { if (in.readableBytes() >= DEFAULT_PROTOCOL_VERSION_LENGTH) { return in.readByte(); } return DEFAULT_ILLEGAL_PROTOCOL_VERSION_LENGTH; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>} }
in.markReaderIndex(); ProtocolCode protocolCode; Protocol protocol; try { protocolCode = decodeProtocolCode(in); if (protocolCode == null) { // read to end return; } byte protocolVersion = decodeProtocolVersion(in); if (ctx.channel().attr(Connection.PROTOCOL).get() == null) { ctx.channel().attr(Connection.PROTOCOL).set(protocolCode); if (DEFAULT_ILLEGAL_PROTOCOL_VERSION_LENGTH != protocolVersion) { ctx.channel().attr(Connection.VERSION).set(protocolVersion); } } protocol = ProtocolManager.getProtocol(protocolCode); } finally { // reset the readerIndex before throwing an exception or decoding content // to ensure that the packet is complete in.resetReaderIndex(); } if (protocol == null) { throw new CodecException("Unknown protocol code: [" + protocolCode + "] while decode in ProtocolDecoder."); } protocol.getDecoder().decode(ctx, in, out);
422
283
705
<methods>public non-sealed void <init>() ,public void channelInactive(ChannelHandlerContext) throws java.lang.Exception,public void channelRead(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception,public void channelReadComplete(ChannelHandlerContext) throws java.lang.Exception,public final void handlerRemoved(ChannelHandlerContext) throws java.lang.Exception,public boolean isSingleDecode() ,public void setCumulator(com.alipay.remoting.codec.AbstractBatchDecoder.Cumulator) ,public void setDiscardAfterReads(int) ,public void setSingleDecode(boolean) <variables>public static final com.alipay.remoting.codec.AbstractBatchDecoder.Cumulator COMPOSITE_CUMULATOR,public static final com.alipay.remoting.codec.AbstractBatchDecoder.Cumulator MERGE_CUMULATOR,ByteBuf cumulation,private com.alipay.remoting.codec.AbstractBatchDecoder.Cumulator cumulator,private boolean decodeWasNull,private int discardAfterReads,private boolean first,private int numReads,private boolean singleDecode
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedEncoder.java
ProtocolCodeBasedEncoder
encode
class ProtocolCodeBasedEncoder extends MessageToByteEncoder<Serializable> { /** default protocol code */ protected ProtocolCode defaultProtocolCode; public ProtocolCodeBasedEncoder(ProtocolCode defaultProtocolCode) { super(); this.defaultProtocolCode = defaultProtocolCode; } @Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {<FILL_FUNCTION_BODY>} }
Attribute<ProtocolCode> att = ctx.channel().attr(Connection.PROTOCOL); ProtocolCode protocolCode; if (att == null || att.get() == null) { protocolCode = this.defaultProtocolCode; } else { protocolCode = att.get(); } Protocol protocol = ProtocolManager.getProtocol(protocolCode); protocol.getEncoder().encode(ctx, msg, out);
119
109
228
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/config/BoltOption.java
BoltOption
equals
class BoltOption<T> { private final String name; private T defaultValue; protected BoltOption(String name, T defaultValue) { this.name = name; this.defaultValue = defaultValue; } public String name() { return name; } public T defaultValue() { return defaultValue; } public static <T> BoltOption<T> valueOf(String name) { return new BoltOption<T>(name, null); } public static <T> BoltOption<T> valueOf(String name, T defaultValue) { return new BoltOption<T>(name, defaultValue); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return name != null ? name.hashCode() : 0; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BoltOption<?> that = (BoltOption<?>) o; return name != null ? name.equals(that.name) : that.name == null;
241
94
335
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/config/BoltOptions.java
BoltOptions
option
class BoltOptions { private ConcurrentHashMap<BoltOption<?>, Object> options = new ConcurrentHashMap<BoltOption<?>, Object>(); /** * Get the optioned value. * Return default value if option does not exist. * * @param option target option * @return the optioned value of default value if option does not exist. */ @SuppressWarnings("unchecked") public <T> T option(BoltOption<T> option) {<FILL_FUNCTION_BODY>} /** * Set up an new option with specific value. * Use a value of {@code null} to remove a previous set {@link BoltOption}. * * @param option target option * @param value option value, null for remove a previous set {@link BoltOption}. * @return this BoltOptions instance */ public <T> BoltOptions option(BoltOption<T> option, T value) { if (value == null) { options.remove(option); return this; } options.put(option, value); return this; } }
Object value = options.get(option); if (value == null) { value = option.defaultValue(); } return value == null ? null : (T) value;
297
50
347
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/config/configs/DefaultConfigContainer.java
DefaultConfigContainer
validate
class DefaultConfigContainer implements ConfigContainer { /** logger */ private static final Logger logger = BoltLoggerFactory .getLogger("CommonDefault"); /** * use a hash map to store the user configs with different config types and config items. */ private Map<ConfigType, Map<ConfigItem, Object>> userConfigs = new HashMap<ConfigType, Map<ConfigItem, Object>>(); @Override public boolean contains(ConfigType configType, ConfigItem configItem) { validate(configType, configItem); return null != userConfigs.get(configType) && userConfigs.get(configType).containsKey(configItem); } @Override @SuppressWarnings("unchecked") public <T> T get(ConfigType configType, ConfigItem configItem) { validate(configType, configItem); if (userConfigs.containsKey(configType)) { return (T) userConfigs.get(configType).get(configItem); } return null; } @Override public void set(ConfigType configType, ConfigItem configItem, Object value) { validate(configType, configItem, value); Map<ConfigItem, Object> items = userConfigs.get(configType); if (null == items) { items = new HashMap<ConfigItem, Object>(); userConfigs.put(configType, items); } Object prev = items.put(configItem, value); if (null != prev) { logger.warn("the value of ConfigType {}, ConfigItem {} changed from {} to {}", configType, configItem, prev.toString(), value.toString()); } } private void validate(ConfigType configType, ConfigItem configItem) { if (null == configType || null == configItem) { throw new IllegalArgumentException(String.format( "ConfigType {%s}, ConfigItem {%s} should not be null!", configType, configItem)); } } private void validate(ConfigType configType, ConfigItem configItem, Object value) {<FILL_FUNCTION_BODY>} }
if (null == configType || null == configItem || null == value) { throw new IllegalArgumentException(String.format( "ConfigType {%s}, ConfigItem {%s}, value {%s} should not be null!", configType, configItem, value == null ? null : value.toString())); }
535
77
612
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/config/switches/ProtocolSwitch.java
ProtocolSwitch
toByte
class ProtocolSwitch implements Switch { // switch index public static final int CRC_SWITCH_INDEX = 0x000; // default value public static final boolean CRC_SWITCH_DEFAULT_VALUE = true; /** protocol switches */ private BitSet bs = new BitSet(); // ~~~ public methods @Override public void turnOn(int index) { this.bs.set(index); } @Override public void turnOff(int index) { this.bs.clear(index); } @Override public boolean isOn(int index) { return this.bs.get(index); } /** * generate byte value according to the bit set in ProtocolSwitchStatus */ public byte toByte() { return toByte(this.bs); } //~~~ static methods /** * check switch status whether on according to specified value * * @param switchIndex * @param value * @return */ public static boolean isOn(int switchIndex, int value) { return toBitSet(value).get(switchIndex); } /** * create an instance of {@link ProtocolSwitch} according to byte value * * @param value * @return ProtocolSwitchStatus with initialized bit set. */ public static ProtocolSwitch create(int value) { ProtocolSwitch status = new ProtocolSwitch(); status.setBs(toBitSet(value)); return status; } /** * create an instance of {@link ProtocolSwitch} according to switch index * * @param index the switch index which you want to set true * @return ProtocolSwitchStatus with initialized bit set. */ public static ProtocolSwitch create(int[] index) { ProtocolSwitch status = new ProtocolSwitch(); for (int i = 0; i < index.length; ++i) { status.turnOn(index[i]); } return status; } /** * from bit set to byte * @param bs * @return byte represent the bit set */ public static byte toByte(BitSet bs) {<FILL_FUNCTION_BODY>} /** * from byte to bit set * @param value * @return bit set represent the byte */ public static BitSet toBitSet(int value) { if (value < 0 || value > Byte.MAX_VALUE) { throw new IllegalArgumentException( "The value " + value + " is out of byte range, should be limited between [0] to [" + Byte.MAX_VALUE + "]"); } BitSet bs = new BitSet(); int index = 0; while (value != 0) { if (value % 2 != 0) { bs.set(index); } ++index; value = (byte) (value >> 1); } return bs; } // ~~~ getter and setters /** * Setter method for property <tt>bs<tt>. * * @param bs value to be assigned to property bs */ public void setBs(BitSet bs) { this.bs = bs; } }
int value = 0; for (int i = 0; i < bs.length(); ++i) { if (bs.get(i)) { value += 1 << i; } } if (bs.length() > 7) { throw new IllegalArgumentException( "The byte value " + value + " generated according to bit set " + bs + " is out of range, should be limited between [0] to [" + Byte.MAX_VALUE + "]"); } return (byte) value;
850
135
985
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/log/BoltLoggerFactory.java
BoltLoggerFactory
getLogger
class BoltLoggerFactory { public static final String BOLT_LOG_SPACE_PROPERTY = "bolt.log.space"; private static String BOLT_LOG_SPACE = "com.alipay.remoting"; private static final String LOG_PATH = "logging.path"; private static final String LOG_PATH_DEFAULT = System.getProperty("user.home") + File.separator + "logs"; private static final String CLIENT_LOG_LEVEL = "com.alipay.remoting.client.log.level"; private static final String CLIENT_LOG_LEVEL_DEFAULT = "INFO"; private static final String CLIENT_LOG_ENCODE = "com.alipay.remoting.client.log.encode"; private static final String COMMON_ENCODE = "file.encoding"; private static final String CLIENT_LOG_ENCODE_DEFAULT = "UTF-8"; static { String logSpace = System.getProperty(BOLT_LOG_SPACE_PROPERTY); if (null != logSpace && !logSpace.isEmpty()) { BOLT_LOG_SPACE = logSpace; } String logPath = System.getProperty(LOG_PATH); if (StringUtils.isBlank(logPath)) { System.setProperty(LOG_PATH, LOG_PATH_DEFAULT); } String logLevel = System.getProperty(CLIENT_LOG_LEVEL); if (StringUtils.isBlank(logLevel)) { System.setProperty(CLIENT_LOG_LEVEL, CLIENT_LOG_LEVEL_DEFAULT); } String commonEncode = System.getProperty(COMMON_ENCODE); if (StringUtils.isNotBlank(commonEncode)) { System.setProperty(CLIENT_LOG_ENCODE, commonEncode); } else { String logEncode = System.getProperty(CLIENT_LOG_ENCODE); if (StringUtils.isBlank(logEncode)) { System.setProperty(CLIENT_LOG_ENCODE, CLIENT_LOG_ENCODE_DEFAULT); } } } public static Logger getLogger(Class<?> clazz) {<FILL_FUNCTION_BODY>} public static Logger getLogger(String name) { if (name == null || name.isEmpty()) { return LoggerSpaceManager.getLoggerBySpace("", BOLT_LOG_SPACE); } return LoggerSpaceManager.getLoggerBySpace(name, BOLT_LOG_SPACE); } }
if (clazz == null) { return getLogger(""); } return getLogger(clazz.getCanonicalName());
652
37
689
<no_super_class>
sofastack_sofa-bolt
sofa-bolt/src/main/java/com/alipay/remoting/rpc/DefaultInvokeFuture.java
DefaultInvokeFuture
executeInvokeCallback
class DefaultInvokeFuture implements InvokeFuture { private static final Logger logger = BoltLoggerFactory .getLogger("RpcRemoting"); private int invokeId; private InvokeCallbackListener callbackListener; private InvokeCallback callback; private volatile ResponseCommand responseCommand; private final CountDownLatch countDownLatch = new CountDownLatch(1); private final AtomicBoolean executeCallbackOnlyOnce = new AtomicBoolean(false); private Timeout timeout; private Throwable cause; private ClassLoader classLoader; private byte protocol; private InvokeContext invokeContext; private CommandFactory commandFactory; /** * Constructor. * * @param invokeId invoke id * @param callbackListener callback listener * @param callback callback * @param protocol protocol code * @param commandFactory command factory */ public DefaultInvokeFuture(int invokeId, InvokeCallbackListener callbackListener, InvokeCallback callback, byte protocol, CommandFactory commandFactory) { this.invokeId = invokeId; this.callbackListener = callbackListener; this.callback = callback; this.classLoader = Thread.currentThread().getContextClassLoader(); this.protocol = protocol; this.commandFactory = commandFactory; } /** * Constructor. * * @param invokeId invoke id * @param callbackListener callback listener * @param callback callback * @param protocol protocol * @param commandFactory command factory * @param invokeContext invoke context */ public DefaultInvokeFuture(int invokeId, InvokeCallbackListener callbackListener, InvokeCallback callback, byte protocol, CommandFactory commandFactory, InvokeContext invokeContext) { this(invokeId, callbackListener, callback, protocol, commandFactory); this.invokeContext = invokeContext; } @Override public ResponseCommand waitResponse(long timeoutMillis) throws InterruptedException { this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS); return this.responseCommand; } @Override public ResponseCommand waitResponse() throws InterruptedException { this.countDownLatch.await(); return this.responseCommand; } @Override public RemotingCommand createConnectionClosedResponse(InetSocketAddress responseHost) { return this.commandFactory.createConnectionClosedResponse(responseHost, null); } /** * @see com.alipay.remoting.InvokeFuture#putResponse(com.alipay.remoting.RemotingCommand) */ @Override public void putResponse(RemotingCommand response) { this.responseCommand = (ResponseCommand) response; this.countDownLatch.countDown(); } /** * * @see com.alipay.remoting.InvokeFuture#isDone() */ @Override public boolean isDone() { return this.countDownLatch.getCount() <= 0; } @Override public ClassLoader getAppClassLoader() { return this.classLoader; } /** * @see com.alipay.remoting.InvokeFuture#invokeId() */ @Override public int invokeId() { return this.invokeId; } @Override public void executeInvokeCallback() {<FILL_FUNCTION_BODY>} /** * @see com.alipay.remoting.InvokeFuture#getInvokeCallback() */ @Override public InvokeCallback getInvokeCallback() { return this.callback; } /** * @see com.alipay.remoting.InvokeFuture#addTimeout(io.netty.util.Timeout) */ @Override public void addTimeout(Timeout timeout) { this.timeout = timeout; } /** * @see com.alipay.remoting.InvokeFuture#cancelTimeout() */ @Override public void cancelTimeout() { if (this.timeout != null) { this.timeout.cancel(); } } /** * @see com.alipay.remoting.InvokeFuture#setCause(java.lang.Throwable) */ @Override public void setCause(Throwable cause) { this.cause = cause; } /** * @see com.alipay.remoting.InvokeFuture#getCause() */ @Override public Throwable getCause() { return this.cause; } /** * @see com.alipay.remoting.InvokeFuture#getProtocolCode() */ @Override public byte getProtocolCode() { return this.protocol; } /** * @see InvokeFuture#getInvokeContext() */ @Override public void setInvokeContext(InvokeContext invokeContext) { this.invokeContext = invokeContext; } /** * @see InvokeFuture#setInvokeContext(InvokeContext) */ @Override public InvokeContext getInvokeContext() { return invokeContext; } /** * @see com.alipay.remoting.InvokeFuture#tryAsyncExecuteInvokeCallbackAbnormally() */ @Override public void tryAsyncExecuteInvokeCallbackAbnormally() { try { Protocol protocol = ProtocolManager.getProtocol(ProtocolCode.fromBytes(this.protocol)); if (null != protocol) { CommandHandler commandHandler = protocol.getCommandHandler(); if (null != commandHandler) { ExecutorService executor = commandHandler.getDefaultExecutor(); if (null != executor) { executor.execute(new Runnable() { @Override public void run() { ClassLoader oldClassLoader = null; try { if (DefaultInvokeFuture.this.getAppClassLoader() != null) { oldClassLoader = Thread.currentThread() .getContextClassLoader(); Thread.currentThread().setContextClassLoader( DefaultInvokeFuture.this.getAppClassLoader()); } DefaultInvokeFuture.this.executeInvokeCallback(); } finally { if (null != oldClassLoader) { Thread.currentThread() .setContextClassLoader(oldClassLoader); } } } }); } } else { logger.error("Executor null in commandHandler of protocolCode [{}].", this.protocol); } } else { logger.error("protocolCode [{}] not registered!", this.protocol); } } catch (Exception e) { logger.error("Exception caught when executing invoke callback abnormally.", e); } } }
if (callbackListener != null) { if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) { callbackListener.onResponse(this); } }
1,757
50
1,807
<no_super_class>