Java Code Examples for org.springframework.util.StringUtils

The following examples show how to use org.springframework.util.StringUtils. These examples are extracted from open source projects.
Example 1
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 2
Project: servicecomb-java-chassis   File: InheritInvocationContextFilter.java    License: 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 3
Project: singleton   File: TranslationCollectKeyAPI.java    License: 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 4
Project: spring-analysis-note   File: WebSocketServerSockJsSession.java    License: 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
Project: spring-cloud-stream-app-starters   File: GreenplumDataSourceFactoryBean.java    License: 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 6
Project: sofa-dashboard   File: ZkCommandPushManager.java    License: 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 7
Project: java-technology-stack   File: DefaultRequestToViewNameTranslator.java    License: 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 8
Project: oodt   File: SolrIndexer.java    License: 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 9
Project: jetcache   File: CreateCacheAnnotationBeanPostProcessor.java    License: 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 10
Project: wopihost   File: WopiLockService.java    License: 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 11
Project: multitenant   File: ScriptServiceImpl.java    License: 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 12
Project: spring-boot-starter-swagger   File: SwaggerAutoConfiguration.java    License: 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 13
Project: litemall   File: LitemallAftersaleService.java    License: 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
Project: iotplatform   File: SendMailAction.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<Template> toTemplate(String source, String name) throws ParseException {
  if (!StringUtils.isEmpty(source)) {
    return Optional.of(VelocityUtils.create(source, name));
  } else {
    return Optional.empty();
  }
}
 
Example 15
Project: hawkbit   File: JpaSoftwareModuleManagement.java    License: 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 16
Project: A.CTable-Frame   File: BaseCRUDManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据实体对象的非Null字段作为Where条件进行删除操作,如果对象的属性值都为null则删除表全部数据
 *
 * @param t 实体对象
 * @param <T> 实体类型
 * @return 返回成功条数
 */
@Override
public <T> int delete(T t) {

    // 得到表名
    String tableName = ColumnUtils.getTableName(t.getClass());
    if (StringUtils.isEmpty(tableName)) {
        log.error("必须使用model中的对象!");
        throw new RuntimeException("必须使用model中的对象!");
    }
    Field[] declaredFields = FieldUtils.getAllFields(t);
    Map<Object, Object> tableMap = new HashMap<Object, Object>();
    Map<Object, Object> dataMap = new HashMap<Object, Object>();
    for (Field field : declaredFields){
        // 设置访问权限
        field.setAccessible(true);
        // 得到字段的配置
        Column column = field.getAnnotation(Column.class);
        if (column == null) {
            log.debug("该field没有配置注解不是表中在字段!");
            continue;
        }
        try{
            dataMap.put(ColumnUtils.getColumnName(field), field.get(t));
        }catch (Exception e){
            log.error("操作对象的Field出现异常",e);
            throw new RuntimeException("操作对象的Field出现异常");
        }
    }
    tableMap.put(tableName, dataMap);
    return baseCRUDMapper.delete(tableMap);
}
 
Example 17
Project: Moss   File: CloudFoundryInstanceIdGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public InstanceId generateId(Registration registration) {
    String applicationId = registration.getMetadata().get("applicationId");
    String instanceId = registration.getMetadata().get("instanceId");

    if (StringUtils.hasText(applicationId) && StringUtils.hasText(instanceId)) {
        return InstanceId.of(String.format("%s:%s", applicationId, instanceId));
    }
    return fallbackIdGenerator.generateId(registration);
}
 
Example 18
Project: Building-RESTful-Web-Services-with-Spring-5-Second-Edition   File: FileUploadServerImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void uploadFile(MultipartFile file) throws IOException {
	String fileName = StringUtils.cleanPath(file.getOriginalFilename());
	if (fileName.isEmpty()) {
		throw new IOException("File is empty " + fileName);
	}
	try {
		Files.copy(file.getInputStream(), this.location.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);
	} catch (IOException e) {
		throw new IOException("File Upload Error : " + fileName);
	}
}
 
Example 19
Project: pinpoint   File: UserGroupController.java    License: Apache License 2.0 5 votes vote down vote up
@PreAuthorize("hasPermission(#userGroupMember.getUserGroupId(), null, T(com.navercorp.pinpoint.web.controller.UserGroupController).EDIT_GROUP_ONLY_GROUPMEMBER)")
@RequestMapping(value = "/member", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> insertUserGroupMember(@RequestBody UserGroupMemberParam userGroupMember) {
    if (StringUtils.isEmpty(userGroupMember.getMemberId()) || StringUtils.isEmpty(userGroupMember.getUserGroupId())) {
        return createErrorMessage("500", "there is not userGroupId or memberId in params to insert user group member");
    }

    userGroupService.insertMember(userGroupMember);
    Map<String, String> result = new HashMap<>();
    result.put("result", "SUCCESS");
    return result;

}
 
Example 20
Project: spring-cloud-stream-binder-rabbit   File: RabbitServiceAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
static void configureCachingConnectionFactory(
		CachingConnectionFactory connectionFactory,
		ConfigurableApplicationContext applicationContext,
		RabbitProperties rabbitProperties) throws Exception {

	if (StringUtils.hasText(rabbitProperties.getAddresses())) {
		connectionFactory.setAddresses(rabbitProperties.determineAddresses());
	}

	connectionFactory.setPublisherConfirmType(rabbitProperties.getPublisherConfirmType() == null ? ConfirmType.NONE : rabbitProperties.getPublisherConfirmType());
	connectionFactory.setPublisherReturns(rabbitProperties.isPublisherReturns());
	if (rabbitProperties.getCache().getChannel().getSize() != null) {
		connectionFactory.setChannelCacheSize(
				rabbitProperties.getCache().getChannel().getSize());
	}
	if (rabbitProperties.getCache().getConnection().getMode() != null) {
		connectionFactory
				.setCacheMode(rabbitProperties.getCache().getConnection().getMode());
	}
	if (rabbitProperties.getCache().getConnection().getSize() != null) {
		connectionFactory.setConnectionCacheSize(
				rabbitProperties.getCache().getConnection().getSize());
	}
	if (rabbitProperties.getCache().getChannel().getCheckoutTimeout() != null) {
		connectionFactory.setChannelCheckoutTimeout(rabbitProperties.getCache()
				.getChannel().getCheckoutTimeout().toMillis());
	}
	connectionFactory.setApplicationContext(applicationContext);
	applicationContext.addApplicationListener(connectionFactory);
	connectionFactory.afterPropertiesSet();
}
 
Example 21
Project: spring-data-jpa-entity-graph   File: RepositoryMethodEntityGraphExtractor.java    License: MIT License 5 votes vote down vote up
private EntityGraphBean buildEntityGraphCandidate(
    EntityGraph providedEntityGraph, ResolvableType returnType) {
  boolean isPrimary = true;
  if (EntityGraphs.isEmpty(providedEntityGraph)) {
    providedEntityGraph = defaultEntityGraph;
    isPrimary = false;
  }
  if (providedEntityGraph == null) {
    return null;
  }

  EntityGraphType entityGraphType = requireNonNull(providedEntityGraph.getEntityGraphType());

  org.springframework.data.jpa.repository.EntityGraph.EntityGraphType type;
  switch (entityGraphType) {
    case FETCH:
      type = org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.FETCH;
      break;
    case LOAD:
      type = org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;
      break;
    default:
      throw new RuntimeException("Unexpected entity graph type '" + entityGraphType + "'");
  }

  List<String> attributePaths = providedEntityGraph.getEntityGraphAttributePaths();
  JpaEntityGraph jpaEntityGraph =
      new JpaEntityGraph(
          StringUtils.hasText(providedEntityGraph.getEntityGraphName())
              ? providedEntityGraph.getEntityGraphName()
              : domainClass.getName() + "-_-_-_-_-_-",
          type,
          attributePaths != null
              ? attributePaths.toArray(new String[attributePaths.size()])
              : null);

  return new EntityGraphBean(
      jpaEntityGraph, domainClass, returnType, providedEntityGraph.isOptional(), isPrimary);
}
 
Example 22
Project: java-technology-stack   File: CustomBooleanEditor.java    License: MIT License 5 votes vote down vote up
@Override
public void setAsText(@Nullable String text) throws IllegalArgumentException {
	String input = (text != null ? text.trim() : null);
	if (this.allowEmpty && !StringUtils.hasLength(input)) {
		// Treat empty String as null value.
		setValue(null);
	}
	else if (this.trueString != null && this.trueString.equalsIgnoreCase(input)) {
		setValue(Boolean.TRUE);
	}
	else if (this.falseString != null && this.falseString.equalsIgnoreCase(input)) {
		setValue(Boolean.FALSE);
	}
	else if (this.trueString == null &&
			(VALUE_TRUE.equalsIgnoreCase(input) || VALUE_ON.equalsIgnoreCase(input) ||
					VALUE_YES.equalsIgnoreCase(input) || VALUE_1.equals(input))) {
		setValue(Boolean.TRUE);
	}
	else if (this.falseString == null &&
			(VALUE_FALSE.equalsIgnoreCase(input) || VALUE_OFF.equalsIgnoreCase(input) ||
					VALUE_NO.equalsIgnoreCase(input) || VALUE_0.equals(input))) {
		setValue(Boolean.FALSE);
	}
	else {
		throw new IllegalArgumentException("Invalid boolean value [" + text + "]");
	}
}
 
Example 23
Project: yshopmall   File: TokenFilter.java    License: Apache License 2.0 5 votes vote down vote up
private String resolveToken(HttpServletRequest request) {
   SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
   String bearerToken = request.getHeader(properties.getHeader());
   if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
      return bearerToken.substring(7);
   }
   return null;
}
 
Example 24
Project: hawkbit   File: ActionHistoryLayout.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getActionHistoryCaption(final String targetName) {
    final String caption;
    if (StringUtils.hasText(targetName)) {
        caption = getI18n().getMessage(UIMessageIdProvider.CAPTION_ACTION_HISTORY_FOR, targetName);
    } else {
        caption = getI18n().getMessage(UIMessageIdProvider.CAPTION_ACTION_HISTORY);
    }

    return caption;
}
 
Example 25
Project: cacheonix-core   File: OsCacheFlushingModel.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Sets the groups that should be flushed.
 * 
 * @param csvGroups
 *          a comma-delimited list containing the new groups to flush
 */
public void setGroups(String csvGroups) {
  String[] newGroups = null;
  if (StringUtils.hasText(csvGroups)) {
    newGroups = StringUtils.commaDelimitedListToStringArray(csvGroups);
  }
  setGroups(newGroups);
}
 
Example 26
Project: lams   File: DisposableBeanAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check whether the given bean has any kind of destroy method to call.
 * @param bean the bean instance
 * @param beanDefinition the corresponding bean definition
 */
public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
	if (bean instanceof DisposableBean || closeableInterface.isInstance(bean)) {
		return true;
	}
	String destroyMethodName = beanDefinition.getDestroyMethodName();
	if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) {
		return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
				ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
	}
	return StringUtils.hasLength(destroyMethodName);
}
 
Example 27
Project: cloud-config   File: ZkClientBeanDefinitionParser.java    License: MIT License 5 votes vote down vote up
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
    String connectionString = element.getAttribute("connection-string");
    if(StringUtils.hasLength(connectionString)) {
        builder.addPropertyValue("connectionString", connectionString);
    }
    
    String credentialString = element.getAttribute("credential-string");
    if(StringUtils.hasLength(credentialString)) {
        builder.addPropertyValue("credentialString", credentialString);
    }

    Integer maxRetries = getSafeInteger(element.getAttribute("max-retries"));
    if(maxRetries!=null) {
        builder.addPropertyValue("maxRetries", maxRetries);
    }

    Integer baseSleepTime = getSafeInteger(element.getAttribute("base-sleep-time"));
    if(baseSleepTime!=null) {
        builder.addPropertyValue("baseSleepTime", baseSleepTime);
    }

    Boolean readOnly = getSafeBoolean(element.getAttribute("read-only"));
    if(readOnly!=null) {
        builder.addPropertyValue("canReadOnly", readOnly);
    }
}
 
Example 28
Project: java-technology-stack   File: Jsr310DateTimeFormatAnnotationFormatterFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Factory method used to create a {@link DateTimeFormatter}.
 * @param annotation the format annotation for the field
 * @param fieldType the declared type of the field
 * @return a {@link DateTimeFormatter} instance
 */
protected DateTimeFormatter getFormatter(DateTimeFormat annotation, Class<?> fieldType) {
	DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
	String style = resolveEmbeddedValue(annotation.style());
	if (StringUtils.hasLength(style)) {
		factory.setStylePattern(style);
	}
	factory.setIso(annotation.iso());
	String pattern = resolveEmbeddedValue(annotation.pattern());
	if (StringUtils.hasLength(pattern)) {
		factory.setPattern(pattern);
	}
	return factory.createDateTimeFormatter();
}
 
Example 29
Project: faster-framework-project   File: LocalDateFormatter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String date = p.getText();
    if (StringUtils.isEmpty(date)) {
        return null;
    }
    return LocalDate.parse(date, formatter);
}
 
Example 30
Project: NoteBlog   File: IndexController.java    License: MIT License 5 votes vote down vote up
@GetMapping("/token/logout")
public String logout(HttpServletRequest request, String from, @CookieValue(SessionParam.SESSION_ID_COOKIE) String uuid) {
    blogContext.removeSessionUser(uuid);
    request.getSession().invalidate();
    if (StringUtils.isEmpty(from)) {
        return "redirect:/";
    } else {
        return "redirect:" + SessionParam.MANAGEMENT_INDEX;
    }
}
 
Example 31
Project: singleton   File: SourceServiceImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void updateStringSource(ComponentSourceDTO comp, String key, String source, String comment) {
   	   MapUtil.updateKeyValue(comp.getMessages(), key, source);
		if (!StringUtils.isEmpty(comment)) {
			MapUtil.updateKeyValue(comp.getComments(), key, comment);
		}
   }
 
Example 32
Project: roncoo-education   File: AuthApiOrderInfoBiz.java    License: MIT License 5 votes vote down vote up
/**
 * 订单详情
 *
 * @param orderInfoBO
 * @return
 */
public Result<AuthOrderInfoDTO> view(AuthOrderInfoViewBO authOrderInfoViewBO) {
	if (StringUtils.isEmpty(authOrderInfoViewBO.getOrderNo())) {
		return Result.error("orderNo不能为空");
	}
	// 根据订单编号查找订单信息
	OrderInfo order = orderInfoDao.getByOrderNo(authOrderInfoViewBO.getOrderNo());
	if (ObjectUtil.isNull(order)) {
		return Result.error("orderNo不正确");
	}
	return Result.success(BeanUtil.copyProperties(order, AuthOrderInfoDTO.class));
}
 
Example 33
Project: springboot-shiro   File: ShiroServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 初始化权限
 */
@Override
public Map<String, String> loadFilterChainDefinitions() {
    /*
        配置访问权限
        - anon:所有url都都可以匿名访问
        - authc: 需要认证才能进行访问(此处指所有非匿名的路径都需要登陆才能访问)
        - user:配置记住我或认证通过可以访问
     */
    Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
    // 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
    filterChainDefinitionMap.put("/passport/logout", "logout");
    filterChainDefinitionMap.put("/passport/login", "anon");
    filterChainDefinitionMap.put("/passport/signin", "anon");
    filterChainDefinitionMap.put("/favicon.ico", "anon");
    filterChainDefinitionMap.put("/error", "anon");
    filterChainDefinitionMap.put("/assets/**", "anon");
    // 加载数据库中配置的资源权限列表
    List<Resources> resourcesList = resourcesService.listUrlAndPermission();
    for (Resources resources : resourcesList) {
        if (!StringUtils.isEmpty(resources.getUrl()) && !StringUtils.isEmpty(resources.getPermission())) {
            String permission = "perms[" + resources.getPermission() + "]";
            filterChainDefinitionMap.put(resources.getUrl(), permission);
        }
    }
    // 本例子中并不存在什么特别关键的操作,所以直接使用user认证。如果有朋友是参考本例子的shiro开发其他安全功能(比如支付等)时,建议针对这类操作使用authc权限 by yadong.zhang
    filterChainDefinitionMap.put("/**", "user");
    return filterChainDefinitionMap;
}
 
Example 34
Project: angularjs-springboot-bookstore   File: DatabaseHealthIndicator.java    License: MIT License 5 votes vote down vote up
protected String detectQuery(String product) {
    String query = this.query;
    if (!StringUtils.hasText(query)) {
        query = queries.get(product);
    }
    if (!StringUtils.hasText(query)) {
        query = DEFAULT_QUERY;
    }
    return query;
}
 
Example 35
Project: entando-core   File: Submit.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void populateComponentHtmlId(Form form) {
       String _tmp_id = "";
       if (id != null) {
           // this check is needed for backwards compatibility with 2.1.x
       	_tmp_id = super.findStringIfAltSyntax(id);
       }
	if (!StringUtils.isEmpty(_tmp_id)) {
		this.addParameter("id", _tmp_id);
	}
   }
 
Example 36
Project: sofa-rpc-boot-projects   File: ServerConfigContainer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建 bolt ServerConfig。rest 的 配置不需要外层 starter 设置默认值。
 *
 * @return Bolt 的服务端配置信息
 */
ServerConfig createBoltServerConfig() {
    String portStr = sofaBootRpcProperties.getBoltPort();
    String boltThreadPoolCoreSizeStr = sofaBootRpcProperties.getBoltThreadPoolCoreSize();
    String boltThreadPoolMaxSizeStr = sofaBootRpcProperties.getBoltThreadPoolMaxSize();
    String acceptsSizeStr = sofaBootRpcProperties.getBoltAcceptsSize();
    String boltThreadPoolQueueSizeStr = sofaBootRpcProperties.getBoltThreadPoolQueueSize();

    ServerConfig serverConfig = new ServerConfig();

    if (StringUtils.hasText(portStr)) {
        serverConfig.setPort(Integer.parseInt(portStr));
    } else {
        serverConfig.setPort(SofaBootRpcConfigConstants.BOLT_PORT_DEFAULT);
    }

    if (StringUtils.hasText(boltThreadPoolMaxSizeStr)) {
        serverConfig.setMaxThreads(Integer.parseInt(boltThreadPoolMaxSizeStr));
    }

    if (StringUtils.hasText(boltThreadPoolCoreSizeStr)) {
        serverConfig.setCoreThreads(Integer.parseInt(boltThreadPoolCoreSizeStr));
    }

    if (StringUtils.hasText(acceptsSizeStr)) {
        serverConfig.setAccepts(Integer.parseInt(acceptsSizeStr));
    }

    if (StringUtils.hasText(boltThreadPoolQueueSizeStr)) {
        serverConfig.setQueues(Integer.parseInt(boltThreadPoolQueueSizeStr));
    }

    serverConfig.setAutoStart(false);
    serverConfig.setProtocol(SofaBootRpcConfigConstants.RPC_PROTOCOL_BOLT);

    addCommonServerConfig(serverConfig);

    return serverConfig;
}
 
Example 37
Project: spring-cloud-contract   File: DefaultImports.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Imports call() {
	String fqnBaseClass = fqnBaseClass();
	if (StringUtils.hasText(fqnBaseClass)) {
		this.blockBuilder.addLineWithEnding("import " + fqnBaseClass);
	}
	return this;
}
 
Example 38
Project: ZTuoExchange_framework   File: GoogleVerificationController.java    License: MIT License 5 votes vote down vote up
/**
 * google解绑
 * @author shenzucai
 * @time 2018.04.09 12:47
 * @param codes
 * @param user
 * @return true
 */

@RequestMapping(value = "/jcgoogle" ,method = RequestMethod.POST)
public MessageResult jcgoogle(String codes, @SessionAttribute(SESSION_MEMBER) AuthMember user,String password) {
    // enter the code shown on device. Edit this and run it fast before the
    // code expires!
    //String GoogleKey = (String) request.getSession().getAttribute("googleKey");
    Member member = memberService.findOne(user.getId());
    String GoogleKey = member.getGoogleKey();
    if(StringUtils.isEmpty(password)){
        return MessageResult.error("密码不能为空");
    }
    try {
        if(!(Md5.md5Digest(password + member.getSalt()).toLowerCase().equals(member.getPassword().toLowerCase()))){
            return MessageResult.error("密码错误");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    long code = Long.parseLong(codes);
    long t = System.currentTimeMillis();
    GoogleAuthenticatorUtil ga = new GoogleAuthenticatorUtil();
    // ga.setWindowSize(0); // should give 5 * 30 seconds of grace...
    boolean r = ga.check_code(GoogleKey, code, t);
    if(!r){
        return MessageResult.error("验证失败");

    }else{
        member.setGoogleDate(new Date());
        member.setGoogleState(0);
        Member result = memberService.save(member);
        if(result != null){
            return MessageResult.success("解绑成功");
        }else{
            return MessageResult.error("解绑失败");
        }
    }
}
 
Example 39
Project: ServiceCutter   File: DatabaseHealthIndicator.java    License: 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);
        }
    }
}
 
Example 40
Project: server   File: JSONFormatIfHasTextValidator.java    License: 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;
}