@Override @SuppressWarnings( {"unchecked"}) public PersisterFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) { final Object customImpl = configurationValues.get( IMPL_NAME ); if ( customImpl == null ) { return new PersisterFactoryImpl(); } if ( PersisterFactory.class.isInstance( customImpl ) ) { return (PersisterFactory) customImpl; } final Class<? extends PersisterFactory> customImplClass = Class.class.isInstance( customImpl ) ? ( Class<? extends PersisterFactory> ) customImpl : locate( registry, customImpl.toString() ); try { return customImplClass.newInstance(); } catch (Exception e) { throw new ServiceException( "Could not initialize custom PersisterFactory impl [" + customImplClass.getName() + "]", e ); } }
@Override @SuppressWarnings( {"unchecked"}) public PersisterClassResolver initiateService(Map configurationValues, ServiceRegistryImplementor registry) { final Object customImpl = configurationValues.get( IMPL_NAME ); if ( customImpl == null ) { return new StandardPersisterClassResolver(); } if ( PersisterClassResolver.class.isInstance( customImpl ) ) { return (PersisterClassResolver) customImpl; } final Class<? extends PersisterClassResolver> customImplClass = Class.class.isInstance( customImpl ) ? (Class<? extends PersisterClassResolver>) customImpl : locate( registry, customImpl.toString() ); try { return customImplClass.newInstance(); } catch (Exception e) { throw new ServiceException( "Could not initialize custom PersisterClassResolver impl [" + customImplClass.getName() + "]", e ); } }
@Override public BatchBuilder initiateService(Map configurationValues, ServiceRegistryImplementor registry) { final Object builder = configurationValues.get( BUILDER ); if ( builder == null ) { return new BatchBuilderImpl( ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, 1 ) ); } if ( BatchBuilder.class.isInstance( builder ) ) { return (BatchBuilder) builder; } final String builderClassName = builder.toString(); try { return (BatchBuilder) registry.getService( ClassLoaderService.class ).classForName( builderClassName ).newInstance(); } catch (Exception e) { throw new ServiceException( "Could not build explicit BatchBuilder [" + builderClassName + "]", e ); } }
@Test public void testNamedClient_noInstance() throws Exception { exception.expect(ServiceException.class); exception.expectCause(allOf(isA(CacheException.class), new BaseMatcher<CacheException>() { @Override public boolean matches(Object item) { return ((CacheException) item).getMessage().contains("No client with name [dev-custom] could be found."); } @Override public void describeTo(Description description) { } })); Properties props = new Properties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.setProperty(CacheEnvironment.USE_NATIVE_CLIENT, "true"); props.setProperty(CacheEnvironment.NATIVE_CLIENT_INSTANCE_NAME, "dev-custom"); props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); Configuration configuration = new Configuration(); configuration.addProperties(props); SessionFactory sf = configuration.buildSessionFactory(); sf.close(); }
private Driver loadDriverIfPossible(String driverClassName) { if ( driverClassName == null ) { log.debug( "No driver class specified" ); return null; } if ( serviceRegistry != null ) { final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class ); final Class<Driver> driverClass = classLoaderService.classForName( driverClassName ); try { return driverClass.newInstance(); } catch ( Exception e ) { throw new ServiceException( "Specified JDBC Driver " + driverClassName + " could not be loaded", e ); } } try { return (Driver) Class.forName( driverClassName ).newInstance(); } catch ( Exception e1 ) { try{ return (Driver) ReflectHelper.classForName( driverClassName ).newInstance(); } catch ( Exception e2 ) { throw new ServiceException( "Specified JDBC Driver " + driverClassName + " could not be loaded", e2 ); } } }
/** * 500 - Internal Server Error */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(ServiceException.class) public ResponseEntity handleServiceException(ServiceException e) { LOGGER.error("业务逻辑异常", e); return ResponseEntity.badRequest().body("业务逻辑异常:" + e.getMessage()); }
/** * 500 - Internal Server Error */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(ServiceException.class) public Response handleServiceException(ServiceException e) { log.error("服务运行异常: {}", e); return new Response().failure(e.getMessage()); }
@ExceptionHandler(ServiceException.class) public @ResponseBody ResponseBean handleCustomException(ServiceException ex) { LOGGER.error("SERVICE EXCEPTION HANDLER ",ex); final ResponseBean responseBase = new ResponseBean(); responseBase.setStatusCode(400); responseBase.setStatusMessage(ex.getLocalizedMessage()); responseBase.setSuccess(false); return responseBase; }
@Test public void testNamedInstance_noInstance() { exception.expect(ServiceException.class); exception.expectCause(allOf(isA(CacheException.class), new BaseMatcher<CacheException>() { @Override public boolean matches(Object item) { return ((CacheException) item).getMessage().contains("No instance with name [hibernate] could be found."); } @Override public void describeTo(Description description) { } })); Config config = new Config(); config.setInstanceName("hibernate"); Properties props = new Properties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate"); props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false"); props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); Configuration configuration = new Configuration(); configuration.addProperties(props); SessionFactory sf = configuration.buildSessionFactory(); sf.close(); }
@Test(expected = ServiceException.class) public void testWrongHazelcastConfigurationFilePathShouldThrow() { Properties props = new Properties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); //we give a non-exist config file address, should fail fast props.setProperty("hibernate.cache.hazelcast.configuration_file_path", "non-exist.xml"); Configuration configuration = new Configuration(); configuration.addProperties(props); SessionFactory sf = configuration.buildSessionFactory(); sf.close(); }
/** * 处理激活 */ @ApiOperation(value = "处理激活", notes = "处理激活", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @RequestMapping(value = "validateEmail", method = RequestMethod.POST) public Result validateEmail(@RequestBody UserModel user ) throws ServiceException, ParseException, UserNotFoundException { //数据访问层,通过email获取用户信息 UserModel userModel = service.findUserByEmail(user.getEmail()); if (userModel != null) { return new Result(CodeConst.USER_REPEAT.getResultCode(), CodeConst.USER_REPEAT.getMessage()); } //验证码是否过期 if (user.getRegisterTime() + TimeUtil.ONE_DAY_IN_MILLISECONDS < TimeUtil.getNowOfMills()) { LOGGER.info("用户{}使用己过期的激活码{}激活邮箱失败!", user.getEmail(), user.getEmail()); return new Result(CodeConst.TIME_PASSED.getResultCode(), CodeConst.TIME_PASSED.getMessage()); } //激活 String salt = RandomUtil.createSalt(); userModel = new UserModel(); userModel.setNickName(user.getNickName()); userModel.setEmail(user.getEmail()); userModel.setGender(GenderConst.SECRET); userModel.setValidateCode(Md5Util.encode(user.getEmail(), salt)); userModel.setPhone(0L); userModel.setSalt(salt); userModel.setAddress(""); userModel.setPassword(Md5Util.encode(user.getPassword(), salt)); userModel = service.addUser(userModel); LOGGER.info("用户{}使用激活码{}激活邮箱成功!", userModel.getEmail(), userModel.getValidateCode()); return new Result<>(userModel); }
@Override @SuppressWarnings( {"unchecked"}) public MultiTenantConnectionProvider initiateService(Map configurationValues, ServiceRegistryImplementor registry) { final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy( configurationValues ); if ( strategy == MultiTenancyStrategy.NONE || strategy == MultiTenancyStrategy.DISCRIMINATOR ) { // nothing to do, but given the separate hierarchies have to handle this here. return null; } final Object configValue = configurationValues.get( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER ); if ( configValue == null ) { // if they also specified the data source *name*, then lets assume they want // DataSourceBasedMultiTenantConnectionProviderImpl final Object dataSourceConfigValue = configurationValues.get( AvailableSettings.DATASOURCE ); if ( dataSourceConfigValue != null && String.class.isInstance( dataSourceConfigValue ) ) { return new DataSourceBasedMultiTenantConnectionProviderImpl(); } return null; } if ( MultiTenantConnectionProvider.class.isInstance( configValue ) ) { return (MultiTenantConnectionProvider) configValue; } else { final Class<MultiTenantConnectionProvider> implClass; if ( Class.class.isInstance( configValue ) ) { implClass = (Class) configValue; } else { final String className = configValue.toString(); final ClassLoaderService classLoaderService = registry.getService( ClassLoaderService.class ); try { implClass = classLoaderService.classForName( className ); } catch (ClassLoadingException cle) { log.warn( "Unable to locate specified class [" + className + "]", cle ); throw new ServiceException( "Unable to locate specified multi-tenant connection provider [" + className + "]" ); } } try { return implClass.newInstance(); } catch (Exception e) { log.warn( "Unable to instantiate specified class [" + implClass.getName() + "]", e ); throw new ServiceException( "Unable to instantiate specified multi-tenant connection provider [" + implClass.getName() + "]" ); } } }
@Override public <R extends Service> R initiateService(ServiceInitiator<R> serviceInitiator) { throw new ServiceException( "Boot-strap registry should only contain provided services" ); }
@Override public <R extends Service> void configureService(ServiceBinding<R> binding) { throw new ServiceException( "Boot-strap registry should only contain provided services" ); }
@Override public <R extends Service> void injectDependencies(ServiceBinding<R> binding) { throw new ServiceException( "Boot-strap registry should only contain provided services" ); }
@Override public <R extends Service> void startService(ServiceBinding<R> binding) { throw new ServiceException( "Boot-strap registry should only contain provided services" ); }
/** * Gets user names from the specified text. * * <p> * A user name is between @ and a punctuation, a blank or a line break (\n). For example, the specified text is * <pre>@88250 It is a nice day. @Vanessa, we are on the way.</pre> There are two user names in the text, * 88250 and Vanessa. * </p> * * @param text the specified text * @return user names, returns an empty set if not found * @throws ServiceException service exception */ public static Set<String> getUserNames(final String text) throws ServiceException { final Set<String> ret = new HashSet<>(); int idx = text.indexOf('@'); if (-1 == idx) { return ret; } String copy = text.trim(); copy = copy.replaceAll("\\n", " "); copy = copy.replaceAll("```.+?```", " "); // pre 单行 copy = copy.replaceAll("^```[\\s\\S]+?^```", " "); // ``` 里面的是 pre 标签内容 copy = copy.replaceAll("`[\\s\\S]+?`", " "); // 同一行中,`some code` 中内容也不该被解析 copy = copy.replaceAll("/^ .*", " "); // 4个空格也是 pre 标签,在这里 . 不会匹配换行 copy = copy.replaceAll("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?", " "); // email copy = copy.replaceAll("\\[@.+?\\]\\(\\/.+?\\)", " ");// 已经被 link 的 username String[] uNames = StringUtils.substringsBetween(copy, "@", " "); String tail = StringUtils.substringAfterLast(copy, "@"); if (tail.contains(" ")) { tail = null; } if (null != tail) { if (null == uNames) { uNames = new String[1]; uNames[0] = tail; } else { uNames = Arrays.copyOf(uNames, uNames.length + 1); uNames[uNames.length - 1] = tail; } } if (null == uNames) { return ret; } for (int i = 0; i < uNames.length; i++) { final String maybeUserName = uNames[i]; ret.add(maybeUserName); copy = copy.replaceFirst("@" + maybeUserName, ""); idx = copy.indexOf('@'); if (-1 == idx) { return ret; } } return ret; }