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 jwtAdmi... |
//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(... | 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(HttpStat... |
/**
* 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}/varian... |
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).col... | 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 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).col... | 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(... |
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 -> convertTo... |
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.get... | 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) {<FI... |
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));
... | 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 createRea... |
//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 persistable... |
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... |
ReadableProductPopulator populator = new ReadableProductPopulator();
populator.setPricingService(pricingService);
populator.setimageUtils(imageUtils);
try {
return populator.populate(product, new ReadableProduct(), merchantStore, language);
} catch (ConversionException e) {
throw new ConversionRuntim... | 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 Grou... |
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(n... | 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}")
... |
MerchantConfig configs = getMerchantConfig(merchantStore);
Configs readableConfig = new Configs();
readableConfig.setAllowOnlinePurchase(configs.isAllowPurchaseItems());
readableConfig.setDisplaySearchBox(configs.isDisplaySearchBox());
readableConfig.setDisplayContactUs(configs.isDisplayCo... | 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, Merc... |
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))
... | 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... |
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
Stri... | 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 ReadableOrderPro... |
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.conv... | 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<Re... |
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.getInformation... | 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
... |
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()... | 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;
@A... |
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 ResourceNotF... | 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 persis... |
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 ServiceRuntimeExce... | 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 ... |
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... | 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;
@Autowir... |
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.getproduct... | 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
privat... |
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 instanceIma... | 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;
... |
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 ... | 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.salesm... |
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 [" + cust... | 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;
... |
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 TY... |
//{"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.pu... | 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 Str... |
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 " ... | 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 st... |
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", ... | 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 CustomerServicesIm... |
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.springfr... |
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";
... |
final Date created = getIssuedAtDateFromToken(token);
boolean t = isCreatedBeforeLastPasswordResetWithGrace(created, lastPasswordReset);
boolean u = isTokenExpiredWithGrace(token);
boolean v = ignoreTokenExpiration(token);
System.out.println(t + " " + u + " " + v);
... | 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 {
... |
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{
respons... |
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 ServletE... |
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
clearAuthenticationAttributes(request);
return;
}
String targetUrlParam = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl() || (targetUrlParam !=... | 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 ... |
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 Authen... | 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 getToken... |
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 ... |
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String name = auth.getName();
Object credentials = auth.getCredentials();
UserDetails user = jwtAdminDetailsService.loadUserByUsername(name);
if (user == null) {
th... | 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 sta... |
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 " + us... | 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;
}
p... |
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 attemptAuthentica... |
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 {
... | 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 getToken... |
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 Authentica... |
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String name = auth.getName();
Object credentials = auth.getCredentials();
UserDetails customer = jwtCustomerDetailsService.loadUserByUsername(name);
if (customer == null) {
... | 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.per... |
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.getB... | 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.springfr... |
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 langua... |
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");
}
//creat... | 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="... |
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);
}
re... | 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 AppConfiguratio... |
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 authen... |
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
... | 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, IllegalAcce... |
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.getCla... | 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 Ex... |
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(... | 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(Strin... |
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, ... |
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 s... |
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") !... | 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";
priv... |
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... | 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 constraintValidat... |
boolean result = false;
Object[] enumValues = this.annotation.enumClass().getEnumConstants();
if(enumValues != null)
{
for(Object enumValue:enumValues)
{
if(valueForValidation.equals(enumValue.toString())
||... | 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(fi... |
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(secon... | 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 fi... |
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",
... |
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 lo... |
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 ... |
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(R... | 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_FUNC... |
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).t... | 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, ... |
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
* ... |
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)... | 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.getDa... |
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);
}
... | 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 = "a... |
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)) {
... | 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(Strin... |
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
... |
/**
* 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)) {
... | 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")... |
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(lo... |
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)... | 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 setDefaultOkHt... |
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());
... | 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;
... | 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;
... | 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 p... |
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) {
... | 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 = decodeS... |
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 (... | 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 componen... |
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());
... | 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 ... |
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);
... | 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);
/**
... |
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 lastAccessTimest... |
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 prevSerializer = classCustomSerializer.putIfAbsent(className, serializer);
if (prevSerializer != null) {
throw new RuntimeException("CustomSerializer has been registered for class: "
+ className + ", the custom serializer is: "
... | 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;
... |
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 ... |
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 ScheduledThreadPoolExe... | 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 ... |
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 = ... |
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 i... |
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 pr... |
if (null == protocolCode || null == protocol) {
throw new RuntimeException("Protocol: " + protocol + " and protocol code:"
+ protocolCode + " should not be null!");
}
Protocol exists = ProtocolManager.protocols.putIfAbsent(protocolCode, protoco... | 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... |
try {
if (connections == null) {
return null;
}
int size = connections.size();
if (size == 0) {
return null;
}
Connection result;
if (configuration != null && configuration.option(BoltClientOpti... | 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 {... | 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 ... |
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.connectio... |
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) {
... | 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 ... |
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 caugh... | 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:... |
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_... | 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... |
in.markReaderIndex();
ProtocolCode protocolCode;
Protocol protocol;
try {
protocolCode = decodeProtocolCode(in);
if (protocolCode == null) {
// read to end
return;
}
byte protocolVersion = decodeProtocolVer... | 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 handlerR... |
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;
}
@Over... |
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 = ProtocolMan... | 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() {
re... |
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 i... |
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... |
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();
... |
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... | 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 ... |
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 callback... |
if (callbackListener != null) {
if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) {
callbackListener.onResponse(this);
}
}
| 1,757 | 50 | 1,807 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.