Java Code Examples for io.netty.util.internal.StringUtil#isNullOrEmpty()

The following examples show how to use io.netty.util.internal.StringUtil#isNullOrEmpty() . 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: CookieIntercept.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
  String acceptValue = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
  if (acceptValue != null && acceptValue.contains("application/x-sniff-cookie")) {
    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, new DefaultHttpHeaders());
    httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
    //https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
    AsciiString customHeadKey = AsciiString.cached("X-Sniff-Cookie");
    String cookie = pipeline.getHttpRequest().headers().get(HttpHeaderNames.COOKIE);
    httpResponse.headers().set(customHeadKey, cookie == null ? "" : cookie);
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, customHeadKey);
    String origin = httpRequest.headers().get(HttpHeaderNames.ORIGIN);
    if (StringUtil.isNullOrEmpty(origin)) {
      String referer = httpRequest.headers().get(HttpHeaderNames.REFERER);
      URL url = new URL(referer);
      origin = url.getHost();
    }
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
    clientChannel.writeAndFlush(httpResponse);
    clientChannel.writeAndFlush(new DefaultLastHttpContent());
    clientChannel.close();
  } else {
    super.beforeRequest(clientChannel, httpRequest, pipeline);
  }
}
 
Example 2
Source File: PhpFormatDocumentationProvider.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@Override
public @Nullable PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement psiElement) {
    if (!(object instanceof String)) {
        return null;
    }

    String fqn = getCallToFormatFunc(psiElement);
    if (StringUtil.isNullOrEmpty(fqn)) {
        return null;
    }

    String tokenText = (String)object;

    if ("%%".equals(tokenText)) {
        tokenText = "%";
    }
    else if (!"%".equals(tokenText)) {
        tokenText = StringUtils.strip((String)object, "%");
    }
    String functionName = StringUtils.strip(fqn, "\\");
    return new FormatTokenDocElement(psiManager, psiElement.getLanguage(), tokenText, functionName);
}
 
Example 3
Source File: DefaultMQProducerImpl.java    From elephant with Apache License 2.0 6 votes vote down vote up
public static void checkMessage(Message msg,DefaultMQProducer defaultMQProducer) throws MQClientException {
	if (null == msg) {
		throw new MQClientException(1,"the message is null");
	}
	if (null == msg.getBody()) {
		throw new MQClientException(2,"the message body is null");
	}
	if (0 == msg.getBody().length) {
		throw new MQClientException(3,"the message body length is zero");
	}
	if (msg.getBody().length > defaultMQProducer.getMaxMessageSize()) {
		throw new MQClientException(4,"the message body size over max value, MAX: " + defaultMQProducer.getMaxMessageSize());
	}
	if(StringUtil.isNullOrEmpty(msg.getMessageId())){
		msg.setMessageId(UUID.randomUUID().toString());
	}
}
 
Example 4
Source File: Orderer.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
Orderer(String name, String url, Properties properties) throws InvalidArgumentException {

        if (StringUtil.isNullOrEmpty(name)) {
            throw new InvalidArgumentException("Invalid name for orderer");
        }
        Exception e = checkGrpcUrl(url);
        if (e != null) {
            throw new InvalidArgumentException(e);
        }

        this.name = name;
        this.url = url;
        this.properties = properties == null ? new Properties() : (Properties) properties.clone(); //keep our own copy.
        logger.trace("Created " + toString());

    }
 
Example 5
Source File: DatasourceConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) {
    
    ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl());
    Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);
    if ( !StringUtil.isNullOrEmpty(properties.getUser())) {
        ob = ob.option(USER, properties.getUser());
    }

    if ( !StringUtil.isNullOrEmpty(properties.getPassword())) {
        ob = ob.option(PASSWORD, properties.getPassword());
    }
    
    ConnectionFactory cf = ConnectionFactories.get(ob.build());
    return cf;
}
 
Example 6
Source File: Peer.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
Peer(String name, String grpcURL, Properties properties) throws InvalidArgumentException {
    reconnectCount = new AtomicLong(0L);
    id = config.getNextID();

    Exception e = checkGrpcUrl(grpcURL);
    if (e != null) {
        throw new InvalidArgumentException("Bad peer url.", e);

    }

    if (StringUtil.isNullOrEmpty(name)) {
        throw new InvalidArgumentException("Invalid name for peer");
    }

    this.url = grpcURL;
    this.name = name;
    this.properties = properties == null ? new Properties() : (Properties) properties.clone(); //keep our own copy.

    logger.debug("Created " + toString());
}
 
Example 7
Source File: BasePackage.java    From one-net with Apache License 2.0 6 votes vote down vote up
/**
 * Encoding a string to byte buffer.
 * The first is the string byte array length ,
 * So the String byte array length should not exced 128.
 * The empty string will encoding as lenght 0.
 * @param str
 * @param byteBuf
 */
protected static void stringEncoding(String str, ByteBuffer byteBuf) {
    //All string need to encoding must be less than 128
    if (StringUtil.isNullOrEmpty(str)) {
        byteBuf.put((byte) 0);
    } else {
        byte[] bytes = str.getBytes(Charsets.toCharset("UTF-8"));
        if(bytes.length<128) {
            byteBuf.put((byte) bytes.length);
            byteBuf.put(bytes);
        }else{
            log.warn("String byte array length exced 128, can't do encoding.");
            byteBuf.put((byte)128);
            for(int i=0;i<128;i++){
                byteBuf.put(bytes[i]);
            }
        }
    }
}
 
Example 8
Source File: MsgTimeoutTimerManager.java    From NettyChat with Apache License 2.0 6 votes vote down vote up
/**
 * 从发送超时管理器中移除消息,并停止定时器
 *
 * @param msgId
 */
public void remove(String msgId) {
    if (StringUtil.isNullOrEmpty(msgId)) {
        return;
    }

    MsgTimeoutTimer timer = mMsgTimeoutMap.remove(msgId);
    MessageProtobuf.Msg msg = null;
    if (timer != null) {
        msg = timer.getMsg();
        timer.cancel();
        timer = null;
    }

    System.out.println("从发送消息管理器移除消息,message=" + msg);
}
 
Example 9
Source File: NettyTcpClient.java    From NettyChat with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息
 * 重载
 *
 * @param msg
 * @param isJoinTimeoutManager 是否加入发送超时管理器
 */
@Override
public void sendMsg(MessageProtobuf.Msg msg, boolean isJoinTimeoutManager) {
    if (msg == null || msg.getHead() == null) {
        System.out.println("发送消息失败,消息为空\tmessage=" + msg);
        return;
    }

    if(!StringUtil.isNullOrEmpty(msg.getHead().getMsgId())) {
        if(isJoinTimeoutManager) {
            msgTimeoutTimerManager.add(msg);
        }
    }

    if (channel == null) {
        System.out.println("发送消息失败,channel为空\tmessage=" + msg);
    }

    try {
        channel.writeAndFlush(msg);
    } catch (Exception ex) {
        System.out.println("发送消息失败,reason:" + ex.getMessage() + "\tmessage=" + msg);
    }
}
 
Example 10
Source File: PortController.java    From alcor with Apache License 2.0 5 votes vote down vote up
/**
 * Create a port, and call the interfaces of each micro-service according to the
 * configuration of the port to create various required resources for the port.
 * If any exception occurs in the added process, we need to roll back
 * the resource allocated from each micro-service.
 * @param projectId Project the port belongs to
 * @param portWebJson Port configuration
 * @return PortWebJson
 * @throws Exception Various exceptions that may occur during the create process
 */
@PostMapping({"/project/{project_id}/ports", "v4/{project_id}/ports"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public PortWebJson createPort(@PathVariable("project_id") String projectId,
                                     @RequestBody PortWebJson portWebJson) throws Exception {
    PortEntity portEntity = portWebJson.getPortEntity();
    if (StringUtil.isNullOrEmpty(portEntity.getVpcId())) {
        throw new NetworkIdRequired();
    }

    checkPort(portEntity);

    return portService.createPort(projectId, portWebJson);
}
 
Example 11
Source File: DefaultMQProducerImpl.java    From elephant with Apache License 2.0 5 votes vote down vote up
private void checkConfig() throws MQClientException {
      if (StringUtil.isNullOrEmpty(this.defaultMQProducer.getProducerGroup())) {
          throw new MQClientException("producerGroup is null", null);
      }
      if(StringUtil.isNullOrEmpty(this.defaultMQProducer.getProducerGroup())){
      	throw new MQClientException("register center is null", null);
      }
      synchronized (this.mqProducerFactory) {
      	if(this.mqProducerFactory.getProducerMap().get(this.defaultMQProducer.getProducerGroup()) != null){
      		throw new MQClientException("Group can not be the same!", null);
      	}
      	this.mqProducerFactory.getProducerMap().put(this.defaultMQProducer.getProducerGroup(), this);
}
      
  }
 
Example 12
Source File: YouBianCodeUtil.java    From jeecg-boot-with-activiti with MIT License 5 votes vote down vote up
public static String[] cutYouBianCode(String code){
	if(code==null || StringUtil.isNullOrEmpty(code)){
		return null;
	}else{
		//获取标准长度为numLength+1,截取的数量为code.length/numLength+1
		int c = code.length()/(numLength+1);
		String[] cutcode = new String[c];
		for(int i =0 ; i <c;i++){
			cutcode[i] = code.substring(0,(i+1)*(numLength+1));
		}
		return cutcode;
	}
	
}
 
Example 13
Source File: ValidateTokenFilter.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public Object run() throws ZuulException {
	RequestContext requestContext = RequestContext.getCurrentContext();

	String token = requestContext.getRequest().getHeader("Authorization");
	if (StringUtil.isNullOrEmpty(token)) {
		throw new ZuulException("no token found", HttpStatus.SC_UNAUTHORIZED, "no token found");
	}

	token = token.replace("Bearer ", ""); // remove prefix

	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", "Basic " + config.getBase64Credentials());

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	map.add("token", token);
	map.add("token_type_hint", "access_token");

	HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

	String url = config.getTokenIntrospectEndpoint();
	@SuppressWarnings("unchecked")
	Map<String, Object> resultMap = restTemplate.postForEntity(url, request, Map.class)
			.getBody();

	Boolean active = (Boolean) resultMap.get("active");

	if (active == null || !active) {
		throw new ZuulException("token inactive", HttpStatus.SC_UNAUTHORIZED, "token inactive");
	}

	String username = (String) resultMap.get("username");
	if (StringUtil.isNullOrEmpty(username)) {
		throw new ZuulException("username empty", HttpStatus.SC_UNAUTHORIZED, "username empty");
	}

	requestContext.addZuulRequestHeader("X-S2G-USERNAME", username);

	return null;
}
 
Example 14
Source File: PoolConfiguration.java    From AsyncDao with MIT License 5 votes vote down vote up
private Map<String, String> buildSslConfig() {
    Map<String, String> sslConfig = Map$.MODULE$.empty();
    if (!StringUtil.isNullOrEmpty(sslMode)) {
        sslConfig = sslConfig.$plus(Tuple2.apply("sslmode", sslMode));
    }
    if (!StringUtil.isNullOrEmpty(sslRootCert)) {
        sslConfig = sslConfig.$plus(Tuple2.apply("sslrootcert", sslRootCert));
    }
    return sslConfig;
}
 
Example 15
Source File: TransactionCheckJob.java    From elephant with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ShardingContext shardingContext) {
	List<MessageEntity> findList = this.messageEntityMapper.queryTransactionNotComplete();
	log.info("查询没有完成的事务消息(查询1分钟之前的)记录数:{}",findList);
	if(findList.isEmpty()){
		return;
	}
	try {
		for(MessageEntity entity : findList){
			
			CheckTransactionStateRequestHeader requestHeader = new CheckTransactionStateRequestHeader();
			
			requestHeader.setMessageId(entity.getMessageId());
			requestHeader.setDestination(entity.getDestination());
			requestHeader.setProducerGroup(entity.getGroup());
			if(!StringUtil.isNullOrEmpty(entity.getProperties())){
				requestHeader.setProperties(entity.getProperties());
			}
			
			RemotingCommand request = RemotingCommand.buildRequestCmd(requestHeader,RequestCode.CHECK_TRANSACTION);
			request.setBody(entity.getBody());
			
			sentToClient(request);
		}
	} catch (Exception e) {
		log.error("回查发送异常:{}",e);
	}
}
 
Example 16
Source File: TriggerSmartContractServlet.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void validateParameter(String contract) {
    JSONObject jsonObject = JSONObject.parseObject(contract);
    if (!jsonObject.containsKey("owner_address")
            || StringUtil.isNullOrEmpty(jsonObject.getString("owner_address"))) {
        throw new InvalidParameterException("owner_address isn't set.");
    }
    if (!jsonObject.containsKey("contract_address")
            || StringUtil.isNullOrEmpty(jsonObject.getString("contract_address"))) {
        throw new InvalidParameterException("contract_address isn't set.");
    }
    if (!jsonObject.containsKey(functionSelector)
            || StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector))) {
        throw new InvalidParameterException("function_selector isn't set.");
    }
}
 
Example 17
Source File: YouBianCodeUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
public static String[] cutYouBianCode(String code){
	if(code==null || StringUtil.isNullOrEmpty(code)){
		return null;
	}else{
		//获取标准长度为numLength+1,截取的数量为code.length/numLength+1
		int c = code.length()/(numLength+1);
		String[] cutcode = new String[c];
		for(int i =0 ; i <c;i++){
			cutcode[i] = code.substring(0,(i+1)*(numLength+1));
		}
		return cutcode;
	}
	
}
 
Example 18
Source File: MinaSshdConfig.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public Optional<String> getHost() {
    return StringUtil.isNullOrEmpty(host) ? Optional.empty() : Optional.of(host);
}
 
Example 19
Source File: IntermediateUser.java    From fabric-net-server with Apache License 2.0 2 votes vote down vote up
/**
 * 确定这个名称是否已注册
 *
 * @return 与否
 */
boolean isRegistered() {
    return !StringUtil.isNullOrEmpty(enrollmentSecret);
}
 
Example 20
Source File: SampleUser.java    From fabric_sdk_java_study with Apache License 2.0 2 votes vote down vote up
/**
 * Determine if this name has been registered.
 *
 * @return {@code true} if registered; otherwise {@code false}.
 */
public boolean isRegistered() {
    return !StringUtil.isNullOrEmpty(enrollmentSecret);
}