org.springframework.util.StringUtils Java Examples

The following examples show how to use org.springframework.util.StringUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultRequestToViewNameTranslator.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Transform the request URI (in the context of the webapp) stripping
 * slashes and extensions, and replacing the separator as required.
 * @param lookupPath the lookup path for the current request,
 * as determined by the UrlPathHelper
 * @return the transformed path, with slashes and extensions stripped
 * if desired
 */
@Nullable
protected String transformPath(String lookupPath) {
	String path = lookupPath;
	if (this.stripLeadingSlash && path.startsWith(SLASH)) {
		path = path.substring(1);
	}
	if (this.stripTrailingSlash && path.endsWith(SLASH)) {
		path = path.substring(0, path.length() - 1);
	}
	if (this.stripExtension) {
		path = StringUtils.stripFilenameExtension(path);
	}
	if (!SLASH.equals(this.separator)) {
		path = StringUtils.replace(path, SLASH, this.separator);
	}
	return path;
}
 
Example #2
Source File: TranslationCollectKeyAPI.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
/**
 *Post a string key's source to l10n server.
 *
 */
@ApiIgnore
@ApiOperation(value = APIOperation.KEY_SOURCE_POST_VALUE, notes = APIOperation.KEY_SOURCE_POST_NOTES)
@RequestMapping(value = L10nI18nAPI.TRANSLATION_PRODUCT_NOCOMOPONENT_KEY_APIV1, method = RequestMethod.POST, produces = { API.API_CHARSET })
@ResponseStatus(HttpStatus.OK)
public SourceAPIResponseDTO collectV1KeyTranslationNoComponent(
		@ApiParam(name = APIParamName.PRODUCT_NAME, required = true, value = APIParamValue.PRODUCT_NAME) @PathVariable(APIParamName.PRODUCT_NAME) String productName,
		@ApiParam(name = APIParamName.VERSION, required = true, value = APIParamValue.VERSION) @RequestParam(value = APIParamName.VERSION, required = true) String version,
		@ApiParam(name = APIParamName.KEY, required = true, value = APIParamValue.KEY) @PathVariable(APIParamName.KEY) String key,
		@ApiParam(name = APIParamName.SOURCE, required = false, value = APIParamValue.SOURCE) @RequestParam(value = APIParamName.SOURCE, required = false) String source,
		@ApiParam(name = APIParamName.COMMENT_SOURCE, value = APIParamValue.COMMENT_SOURCE) @RequestParam(value = APIParamName.COMMENT_SOURCE, required = false) String commentForSource,
		@ApiParam(name = APIParamName.LOCALE, value = APIParamValue.LOCALE) @RequestParam(value = APIParamName.LOCALE, required = false) String locale,
		@ApiParam(name = APIParamName.SOURCE_FORMAT, value = APIParamValue.SOURCE_FORMAT) @RequestParam(value = APIParamName.SOURCE_FORMAT, required = false) String sourceFormat,
		@ApiParam(name = APIParamName.COLLECT_SOURCE, value = APIParamValue.COLLECT_SOURCE) @RequestParam(value = APIParamName.COLLECT_SOURCE, required = true, defaultValue = "true") String collectSource,
	//	@ApiParam(name = APIParamName.PSEUDO, value = APIParamValue.PSEUDO) @RequestParam(value = APIParamName.PSEUDO, required = false, defaultValue = ConstantsKeys.FALSE) String pseudo,
		HttpServletRequest request) throws L10nAPIException {
	String newLocale = locale == null ? ConstantsUnicode.EN : locale;
	String newKey = StringUtils.isEmpty(sourceFormat) ? key
			: (key + ConstantsChar.DOT + ConstantsChar.POUND + sourceFormat.toUpperCase());
	String newSource = source == null ? "" : source;
	StringSourceDTO sourceObj = SourceUtils.createSourceDTO(productName, version, ConstantsFile.DEFAULT_COMPONENT, newLocale, newKey,
			newSource, commentForSource, sourceFormat);
	boolean isSourceCached = sourceService.cacheSource(sourceObj);
	return SourceUtils.handleSourceResponse(isSourceCached);
	
}
 
Example #3
Source File: InheritInvocationContextFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether users can inherit specified InvocationContext from outer request
 */
@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
  String invocationContextHeader = requestEx.getHeader(Const.CSE_CONTEXT);
  if (StringUtils.isEmpty(invocationContextHeader)) {
    return null;
  }

  try {
    @SuppressWarnings("unchecked")
    Map<String, String> invocationContext =
        JsonUtils.readValue(invocationContextHeader.getBytes(StandardCharsets.UTF_8), Map.class);
    // Here only the specific invocation context "allowInherit" can be inherited,
    // and other context key-value pairs are ignored.
    // If you want to inherit invocation context from outer requests,
    // it's better to implement such a white-list logic to filter the invocation context.
    // CAUTION: to avoid potential security problem, please do not add all invocation context key-value pairs
    // into InvocationContext without checking or filtering.
    if (!StringUtils.isEmpty(invocationContext.get("allowInherit"))) {
      invocation.addContext("allowInherit", invocationContext.get("allowInherit"));
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example #4
Source File: WebSocketServerSockJsSession.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public void handleMessage(TextMessage message, WebSocketSession wsSession) throws Exception {
	String payload = message.getPayload();
	if (!StringUtils.hasLength(payload)) {
		return;
	}
	String[] messages;
	try {
		messages = getSockJsServiceConfig().getMessageCodec().decode(payload);
	}
	catch (Throwable ex) {
		logger.error("Broken data received. Terminating WebSocket connection abruptly", ex);
		tryCloseWithSockJsTransportError(ex, CloseStatus.BAD_DATA);
		return;
	}
	if (messages != null) {
		delegateMessages(messages);
	}
}
 
Example #5
Source File: CreateCacheAnnotationBeanPostProcessor.java    From jetcache with Apache License 2.0 6 votes vote down vote up
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, PropertyValues pvs) {
    // Fall back to class name as cache key, for backwards compatibility with custom callers.
    String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
    // Quick check on the concurrent map first, with minimal locking.
    InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(cacheKey);
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                if (metadata != null) {
                    clear(metadata, pvs);
                }
                try {
                    metadata = buildAutowiringMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                } catch (NoClassDefFoundError err) {
                    throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() +
                            "] for autowiring metadata: could not find class that it depends on", err);
                }
            }
        }
    }
    return metadata;
}
 
Example #6
Source File: SolrIndexer.java    From oodt with Apache License 2.0 6 votes vote down vote up
/**
 * This method deletes a product(s) from the Solr index identified by a given name
 * 
 * @param productName
 * @throws IOException
 * @throws SolrServerException
 */
public void deleteProductByName(String productName) {
	LOG.info("Attempting to delete product: " + productName);

	try {
		String productNameField = config.mapProperties.getProperty(PRODUCT_NAME);
		if (StringUtils.hasText(productNameField)) {
			server.deleteByQuery(productNameField+":"+productName);
		} else {
			LOG.warning("Metadata field "+PRODUCT_NAME+" is not mapped to any Solr field, cannot delete product by name");
		}
	} catch(Exception e) {
		LOG.warning("Could not delete product: "+productName+" from Solr index");
	}

}
 
Example #7
Source File: WopiLockService.java    From wopihost with MIT License 6 votes vote down vote up
/**
 * Processes a Unlock request
 *
 * @param request
 * @param fileName
 * @return
 */
public ResponseEntity unlock(HttpServletRequest request, String fileName) {
    LockInfo lockInfo = lockRepository.getLockInfo(fileName);
    String requestLock = request.getHeader(WopiRequestHeader.LOCK);
    // Ensure the file has a valid lock
    if (lockInfo == null || StringUtils.isEmpty(lockInfo.getLockValue())) {
        return setLockMismatch(EMPTY_STRING, "File isn't locked");
    } else if (lockInfo.isExpired()) {
        // File lock expired, so clear it out
        lockRepository.delete(fileName);
        return setLockMismatch(EMPTY_STRING, "File isn't locked");
    } else if (!lockInfo.getLockValue().equals(requestLock)) {
        return setLockMismatch(lockInfo.getLockValue(), "Lock mismatch");
    } else {
        // Unlock the file and return success 200
        lockRepository.delete(fileName);
    }
    return ResponseEntity.ok().build();
}
 
Example #8
Source File: ScriptServiceImpl.java    From multitenant with Apache License 2.0 6 votes vote down vote up
private List<Resource> getResources(String locations) {
	List<Resource> resources = new ArrayList<Resource>();
	for (String location : StringUtils.commaDelimitedListToStringArray(locations)) {
		try {
			for (Resource resource : this.applicationContext.getResources(location)) {
				if (resource.exists()) {
					resources.add(resource);
				}
			}
		}
		catch (IOException ex) {
			throw new IllegalStateException(
					"Unable to load resource from " + location, ex);
		}
	}
	return resources;
}
 
Example #9
Source File: ZkCommandPushManager.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private String covertToConfig(List<ArkOperation> arkOperations) {
    StringBuilder sb = new StringBuilder();
    for (ArkOperation arkOperation : arkOperations) {
        sb.append(arkOperation.getBizName()).append(SofaDashboardConstants.COLON)
            .append(arkOperation.getBizVersion()).append(SofaDashboardConstants.COLON)
            .append(arkOperation.getState());
        if (!StringUtils.isEmpty(arkOperation.getParameters())) {
            sb.append(SofaDashboardConstants.Q_MARK).append(arkOperation.getParameters());
        }
        sb.append(SofaDashboardConstants.SEMICOLON);
    }
    String ret = sb.toString();
    if (ret.endsWith(SofaDashboardConstants.SEMICOLON)) {
        ret = ret.substring(0, ret.length() - 1);
    }
    return ret;
}
 
Example #10
Source File: SwaggerAutoConfiguration.java    From spring-boot-starter-swagger with Apache License 2.0 6 votes vote down vote up
/**
 * 获取返回消息体列表
 *
 * @param globalResponseMessageBodyList 全局Code消息返回集合
 * @return
 */
private List<ResponseMessage> getResponseMessageList
(List<SwaggerProperties.GlobalResponseMessageBody> globalResponseMessageBodyList) {
    List<ResponseMessage> responseMessages = new ArrayList<>();
    for (SwaggerProperties.GlobalResponseMessageBody globalResponseMessageBody : globalResponseMessageBodyList) {
        ResponseMessageBuilder responseMessageBuilder = new ResponseMessageBuilder();
        responseMessageBuilder.code(globalResponseMessageBody.getCode()).message(globalResponseMessageBody.getMessage());

        if (!StringUtils.isEmpty(globalResponseMessageBody.getModelRef())) {
            responseMessageBuilder.responseModel(new ModelRef(globalResponseMessageBody.getModelRef()));
        }
        responseMessages.add(responseMessageBuilder.build());
    }

    return responseMessages;
}
 
Example #11
Source File: GreenplumDataSourceFactoryBean.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if (controlFile != null) {
		if (StringUtils.hasText(controlFile.getHost())) {
			dbHost = controlFile.getHost();
		}
		if (StringUtils.hasText(controlFile.getDatabase())) {
			dbName = controlFile.getDatabase();
		}
		if (StringUtils.hasText(controlFile.getUser())) {
			dbUser = controlFile.getUser();
		}
		if (StringUtils.hasText(controlFile.getPassword())) {
			dbPassword = controlFile.getPassword();
		}
		if (controlFile.getPort() != null) {
			dbPort = controlFile.getPort();
		}
	}
	super.afterPropertiesSet();
}
 
Example #12
Source File: DistributionSetTypeSoftwareModuleSelectLayout.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
private void addTooltTipToSelectedTable() {
    selectedTable.setItemDescriptionGenerator(new ItemDescriptionGenerator() {
        private static final long serialVersionUID = 1L;

        @Override
        public String generateDescription(final Component source, final Object itemId, final Object propertyId) {
            final Item item = selectedTable.getItem(itemId);
            final String description = (String) (item.getItemProperty(DIST_TYPE_DESCRIPTION).getValue());
            if (DIST_TYPE_NAME.equals(propertyId) && !StringUtils.isEmpty(description)) {
                return i18n.getMessage("label.description") + description;
            } else if (DIST_TYPE_MANDATORY.equals(propertyId)) {
                return i18n.getMessage(UIMessageIdProvider.TOOLTIP_CHECK_FOR_MANDATORY);
            }
            return null;
        }
    });
}
 
Example #13
Source File: LitemallAftersaleService.java    From litemall with MIT License 6 votes vote down vote up
public List<LitemallAftersale> queryList(Integer userId, Short status, Integer page, Integer limit, String sort, String order) {
    LitemallAftersaleExample example = new LitemallAftersaleExample();
    LitemallAftersaleExample.Criteria criteria = example.or();
    criteria.andUserIdEqualTo(userId);
    if (status != null) {
        criteria.andStatusEqualTo(status);
    }
    criteria.andDeletedEqualTo(false);
    if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
        example.setOrderByClause(sort + " " + order);
    }
    else{
        example.setOrderByClause(LitemallAftersale.Column.addTime.desc());
    }

    PageHelper.startPage(page, limit);
    return aftersaleMapper.selectByExample(example);
}
 
Example #14
Source File: ScriptTemplateView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * See {@link ScriptTemplateConfigurer#setResourceLoaderPath(String)} documentation.
 */
public void setResourceLoaderPath(String resourceLoaderPath) {
	String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	this.resourceLoaderPaths = new String[paths.length + 1];
	this.resourceLoaderPaths[0] = "";
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (!path.endsWith("/") && !path.endsWith(":")) {
			path = path + "/";
		}
		this.resourceLoaderPaths[i + 1] = path;
	}
}
 
Example #15
Source File: CacheNameAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
private String resolveSpringApplicationName(Environment environment) {

		return Optional.ofNullable(environment)
			.filter(it -> it.containsProperty(SPRING_APPLICATION_NAME_PROPERTY))
			.map(it -> it.getProperty(SPRING_APPLICATION_NAME_PROPERTY))
			.filter(StringUtils::hasText)
			.orElse(null);
	}
 
Example #16
Source File: RouterRuleCache.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * if a server don't have rule , avoid registered too many callback , it may cause memory leak
 *
 * @param targetServiceName
 * @return
 */
public static boolean isServerContainRule(String targetServiceName) {
  DynamicStringProperty lookFor = DynamicPropertyFactory.getInstance()
      .getStringProperty(String.format(ROUTE_RULE, targetServiceName), null);
  if (StringUtils.isEmpty(lookFor.get())) {
    return false;
  }
  return true;
}
 
Example #17
Source File: SofaBootRpcProperties.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
public String getBoltPort() {

        if (environment.containsProperty(SofaOptions.CONFIG_TR_PORT)) {
            return environment.getProperty(SofaOptions.CONFIG_TR_PORT);
        }

        return StringUtils.isEmpty(boltPort) ? getDotString(new Object() {
        }.getClass().getEnclosingMethod().getName()) : boltPort;
    }
 
Example #18
Source File: ComponentScanBeanDefinitionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
	String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
	basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
	String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
			ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

	// Actually scan for bean definitions and register them.
	ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
	Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
	registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

	return null;
}
 
Example #19
Source File: OAuth2Utils.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
/**
 * Extract a map from a query string.
 * 
 * @param query a query (or fragment) string from a URI
 * @return a Map of the values in the query
 */
public static Map<String, String> extractMap(String query) {
	Map<String, String> map = new HashMap<String, String>();
	Properties properties = StringUtils.splitArrayElementsIntoProperties(
			StringUtils.delimitedListToStringArray(query, "&"), "=");
	if (properties != null) {
		for (Object key : properties.keySet()) {
			map.put(key.toString(), properties.get(key).toString());
		}
	}
	return map;
}
 
Example #20
Source File: CookieCsrfSignedTokenRepository.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    // Add padding if necessary
    // HS256 need, at least, 32 ascii characters
    secret = org.apache.commons.lang3.StringUtils.leftPad(secret, 32, '0');

    signer = new MACSigner(secret);
    verifier = new MACVerifier(secret);
}
 
Example #21
Source File: WebLogAspect.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
/**
 * 根据方法和传入的参数获取请求参数
 */
private Object getParameter(Method method, Object[] args) {
    List<Object> argList = new ArrayList<>();
    Parameter[] parameters = method.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        //将RequestBody注解修饰的参数作为请求参数
        RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
        if (requestBody != null) {
            argList.add(args[i]);
        }
        //将RequestParam注解修饰的参数作为请求参数
        RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
        if (requestParam != null) {
            Map<String, Object> map = new HashMap<>();
            String key = parameters[i].getName();
            if (!StringUtils.isEmpty(requestParam.value())) {
                key = requestParam.value();
            }
            map.put(key, args[i]);
            argList.add(map);
        }
    }
    if (argList.size() == 0) {
        return null;
    } else if (argList.size() == 1) {
        return argList.get(0);
    } else {
        return argList;
    }
}
 
Example #22
Source File: JpaSoftwareModuleManagement.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private List<Specification<JpaSoftwareModule>> buildSpecificationList(final String searchText, final Long typeId) {
    final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(3);
    if (!StringUtils.isEmpty(searchText)) {
        specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText));
    }
    if (typeId != null) {
        throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);

        specList.add(SoftwareModuleSpecification.equalType(typeId));
    }
    specList.add(SoftwareModuleSpecification.isDeletedFalse());
    return specList;
}
 
Example #23
Source File: SimpleUserService.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public UserEntity selectByUsername(String username) {
    if (!StringUtils.hasLength(username)) {
        return null;
    }
    return createQuery().where("username", username).single();
}
 
Example #24
Source File: JedisProviderFactoryBean.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if(jedisPoolConfig == null)throw new Exception("jedisPoolConfig Not config ??");
	if(org.apache.commons.lang3.StringUtils.isAnyBlank(mode,servers)){
		throw new Exception("type or servers is empty??");
	}
	registerRedisProvier(); 
}
 
Example #25
Source File: HierarchicalUriComponents.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String toUriString() {
	StringBuilder uriBuilder = new StringBuilder();
	if (getScheme() != null) {
		uriBuilder.append(getScheme()).append(':');
	}
	if (this.userInfo != null || this.host != null) {
		uriBuilder.append("//");
		if (this.userInfo != null) {
			uriBuilder.append(this.userInfo).append('@');
		}
		if (this.host != null) {
			uriBuilder.append(this.host);
		}
		if (getPort() != -1) {
			uriBuilder.append(':').append(this.port);
		}
	}
	String path = getPath();
	if (StringUtils.hasLength(path)) {
		if (uriBuilder.length() != 0 && path.charAt(0) != PATH_DELIMITER) {
			uriBuilder.append(PATH_DELIMITER);
		}
		uriBuilder.append(path);
	}
	String query = getQuery();
	if (query != null) {
		uriBuilder.append('?').append(query);
	}
	if (getFragment() != null) {
		uriBuilder.append('#').append(getFragment());
	}
	return uriBuilder.toString();
}
 
Example #26
Source File: PropertiesPlaceholderResolver.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve placeholders in specified {@link Map properties}
 *
 * @param properties {@link Map source properties}
 * @return Resolved {@link Properties source properties}
 */
public Properties resolve(Map<?, ?> properties) {
	Properties resolvedProperties = new Properties();
	for (Map.Entry<?, ?> entry : properties.entrySet()) {
		if (entry.getValue() instanceof CharSequence) {
			String key = String.valueOf(entry.getKey());
			String value = String.valueOf(entry.getValue());
			String resolvedValue = propertyResolver.resolvePlaceholders(value);
			if (StringUtils.hasText(resolvedValue)) { // set properties if has test
				resolvedProperties.setProperty(key, resolvedValue);
			}
		}
	}
	return resolvedProperties;
}
 
Example #27
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextLoaderListenerWithLocalContextInitializers() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
	sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, StringUtils.arrayToCommaDelimitedString(
			new Object[] {TestContextInitializer.class.getName(), TestWebContextInitializer.class.getName()}));
	ContextLoaderListener listener = new ContextLoaderListener();
	listener.contextInitialized(new ServletContextEvent(sc));
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	TestBean testBean = wac.getBean(TestBean.class);
	assertThat(testBean.getName(), equalTo("testName"));
	assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
 
Example #28
Source File: RegisteredServiceThemeBasedViewResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Uses the viewName and the theme associated with the service.
 * being requested and returns the appropriate view.
 * @param viewName the name of the view to be resolved
 * @return a theme-based UrlBasedView
 * @throws Exception an exception
 */
@Override
protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final WebApplicationService service = WebUtils.getService(requestContext);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final String themeId = service != null && registeredService != null
            && registeredService.getAccessStrategy().isServiceAccessAllowed()
            && StringUtils.hasText(registeredService.getTheme()) ? registeredService.getTheme() : defaultThemeId;

    final String themePrefix = String.format("%s/%s/ui/", pathPrefix, themeId);
    LOGGER.debug("Prefix {} set for service {} with theme {}", themePrefix, service, themeId);

    //Build up the view like the base classes do, but we need to forcefully set the prefix for each request.
    //From UrlBasedViewResolver.buildView
    final InternalResourceView view = (InternalResourceView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(themePrefix + viewName + getSuffix());
    final String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }
    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    //From InternalResourceViewResolver.buildView
    view.setAlwaysInclude(false);
    view.setExposeContextBeansAsAttributes(false);
    view.setPreventDispatchLoop(true);

    LOGGER.debug("View resolved: {}", view.getUrl());

    return view;
}
 
Example #29
Source File: JSONFormatIfHasTextValidator.java    From server with MIT License 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (StringUtils.hasText(value)) {
        try {
            JSONObject.parseObject(value);
        } catch (Exception e) {
            return false;
        }
    }

    return true;
}
 
Example #30
Source File: DatabaseHealthIndicator.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    String product = getProduct();
    builder.up().withDetail("database", product);
    String query = detectQuery(product);
    if (StringUtils.hasText(query)) {
        try {
            builder.withDetail("hello",
                this.jdbcTemplate.queryForObject(query, Object.class));
        } catch (Exception ex) {
            builder.down(ex);
        }
    }
}