예제 #1
0
 public static Map<String, String> convertSubscribe(Map<String, String> subscribe) {
   Map<String, String> newSubscribe = new HashMap<String, String>();
   for (Map.Entry<String, String> entry : subscribe.entrySet()) {
     String serviceName = entry.getKey();
     String serviceQuery = entry.getValue();
     if (!serviceName.contains(":") && !serviceName.contains("/")) {
       Map<String, String> params = StringUtils.parseQueryString(serviceQuery);
       String group = params.get("group");
       String version = params.get("version");
       params.remove("group");
       params.remove("version");
       String name = serviceName;
       if (group != null && group.length() > 0) {
         name = group + "/" + name;
       }
       if (version != null && version.length() > 0 && !"0.0.0".equals(version)) {
         name = name + ":" + version;
       }
       newSubscribe.put(name, StringUtils.toQueryString(params));
     } else {
       newSubscribe.put(serviceName, serviceQuery);
     }
   }
   return newSubscribe;
 }
예제 #2
0
  public static Map<String, String> serviceName2Map(String serviceName) {
    String group = null;
    String version = null;
    int i = serviceName.indexOf("/");
    if (i > 0) {
      group = serviceName.substring(0, i);
      serviceName = serviceName.substring(i + 1);
    }
    i = serviceName.lastIndexOf(":");
    if (i > 0) {
      version = serviceName.substring(i + 1);
      serviceName = serviceName.substring(0, i);
    }

    Map<String, String> ret = new HashMap<String, String>();
    if (!StringUtils.isEmpty(serviceName)) {
      ret.put(Constants.INTERFACE_KEY, serviceName);
    }
    if (!StringUtils.isEmpty(version)) {
      ret.put(Constants.VERSION_KEY, version);
    }
    if (!StringUtils.isEmpty(group)) {
      ret.put(Constants.GROUP_KEY, group);
    }

    return ret;
  }
예제 #3
0
 public static Map<String, Map<String, String>> convertRegister(
     Map<String, Map<String, String>> register) {
   Map<String, Map<String, String>> newRegister = new HashMap<String, Map<String, String>>();
   for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) {
     String serviceName = entry.getKey();
     Map<String, String> serviceUrls = entry.getValue();
     if (!serviceName.contains(":") && !serviceName.contains("/")) {
       for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) {
         String serviceUrl = entry2.getKey();
         String serviceQuery = entry2.getValue();
         Map<String, String> params = StringUtils.parseQueryString(serviceQuery);
         String group = params.get("group");
         String version = params.get("version");
         params.remove("group");
         params.remove("version");
         String name = serviceName;
         if (group != null && group.length() > 0) {
           name = group + "/" + name;
         }
         if (version != null && version.length() > 0 && !"0.0.0".equals(version)) {
           name = name + ":" + version;
         }
         Map<String, String> newUrls = newRegister.get(name);
         if (newUrls == null) {
           newUrls = new HashMap<String, String>();
           newRegister.put(name, newUrls);
         }
         newUrls.put(serviceUrl, StringUtils.toQueryString(params));
       }
     } else {
       newRegister.put(serviceName, serviceUrls);
     }
   }
   return newRegister;
 }
예제 #4
0
 public void saveOwner(Owner owner) {
   List<Override> overrides =
       overrideService.findByServiceAndAddress(owner.getService(), Constants.ANYHOST_VALUE);
   if (overrides == null || overrides.size() == 0) {
     Override override = new Override();
     override.setAddress(Constants.ANYHOST_VALUE);
     override.setService(owner.getService());
     override.setEnabled(true);
     override.setParams("owner=" + owner.getUsername());
     overrideService.saveOverride(override);
   } else {
     for (Override override : overrides) {
       Map<String, String> params = StringUtils.parseQueryString(override.getParams());
       String usernames = params.get("owner");
       if (usernames == null || usernames.length() == 0) {
         usernames = owner.getUsername();
       } else {
         usernames = usernames + "," + owner.getUsername();
       }
       params.put("owner", usernames);
       override.setParams(StringUtils.toQueryString(params));
       overrideService.updateOverride(override);
     }
   }
 }
예제 #5
0
  static Map<String, MatchPair> parseNameAndValueListString2Condition(
      Map<String, String> params, Map<String, String> notParams) {
    Map<String, MatchPair> condition = new HashMap<String, RouteRule.MatchPair>();

    for (Entry<String, String> entry : params.entrySet()) {
      String valueListString = entry.getValue();
      if (StringUtils.isBlank(valueListString)) {
        continue;
      }
      String[] list = VALUE_LIST_SEPARATOR.split(valueListString);
      Set<String> set = new HashSet<String>();
      for (String item : list) {
        if (StringUtils.isBlank(item)) {
          continue;
        }
        set.add(item.trim());
      }
      if (set.isEmpty()) {
        continue;
      }

      String key = entry.getKey();
      MatchPair matchPair = condition.get(key);
      if (null == matchPair) {
        matchPair = new MatchPair();
        condition.put(key, matchPair);
      }

      matchPair.matches = set;
    }
    for (Entry<String, String> entry : notParams.entrySet()) {
      String valueListString = entry.getValue();
      if (StringUtils.isBlank(valueListString)) {
        continue;
      }
      String[] list = VALUE_LIST_SEPARATOR.split(valueListString);
      Set<String> set = new HashSet<String>();
      for (String item : list) {
        if (StringUtils.isBlank(item)) {
          continue;
        }
        set.add(item.trim());
      }
      if (set.isEmpty()) {
        continue;
      }

      String key = entry.getKey();
      MatchPair matchPair = condition.get(key);
      if (null == matchPair) {
        matchPair = new MatchPair();
        condition.put(key, matchPair);
      }

      matchPair.unmatches = set;
    }

    return condition;
  }
예제 #6
0
 protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException {
   byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK);
   Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto);
   ObjectInput in = s.deserialize(channel.getUrl(), is);
   // get request id.
   long id = Bytes.bytes2long(header, 4);
   if ((flag & FLAG_REQUEST) == 0) {
     // decode response.
     Response res = new Response(id);
     if ((flag & FLAG_EVENT) != 0) {
       res.setEvent(Response.HEARTBEAT_EVENT);
     }
     // get status.
     byte status = header[3];
     res.setStatus(status);
     if (status == Response.OK) {
       try {
         Object data;
         if (res.isHeartbeat()) {
           data = decodeHeartbeatData(channel, in);
         } else if (res.isEvent()) {
           data = decodeEventData(channel, in);
         } else {
           data = decodeResponseData(channel, in, getRequestData(id));
         }
         res.setResult(data);
       } catch (Throwable t) {
         res.setStatus(Response.CLIENT_ERROR);
         res.setErrorMessage(StringUtils.toString(t));
       }
     } else {
       res.setErrorMessage(in.readUTF());
     }
     return res;
   } else {
     // decode request.
     Request req = new Request(id);
     req.setVersion("2.0.0");
     req.setTwoWay((flag & FLAG_TWOWAY) != 0);
     if ((flag & FLAG_EVENT) != 0) {
       req.setEvent(Request.HEARTBEAT_EVENT);
     }
     try {
       Object data;
       if (req.isHeartbeat()) {
         data = decodeHeartbeatData(channel, in);
       } else if (req.isEvent()) {
         data = decodeEventData(channel, in);
       } else {
         data = decodeRequestData(channel, in);
       }
       req.setData(data);
     } catch (Throwable t) {
       // bad request
       req.setBroken(true);
       req.setData(t);
     }
     return req;
   }
 }
예제 #7
0
 private List<Owner> toOverrideLiset(List<Provider> pList, List<Override> cList) {
   Map<String, Owner> oList = new HashMap<String, Owner>();
   for (Provider p : pList) {
     if (p.getUsername() != null) {
       for (String username : Constants.COMMA_SPLIT_PATTERN.split(p.getUsername())) {
         Owner o = new Owner();
         o.setService(p.getService());
         o.setUsername(username);
         oList.put(o.getService() + "/" + o.getUsername(), o);
       }
     }
   }
   for (Override c : cList) {
     Map<String, String> params = StringUtils.parseQueryString(c.getParams());
     String usernames = params.get("owner");
     if (usernames != null && usernames.length() > 0) {
       for (String username : Constants.COMMA_SPLIT_PATTERN.split(usernames)) {
         Owner o = new Owner();
         o.setService(c.getService());
         o.setUsername(username);
         oList.put(o.getService() + "/" + o.getUsername(), o);
       }
     }
   }
   return new ArrayList<Owner>(oList.values());
 }
예제 #8
0
 protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException {
   try {
     return in.readObject();
   } catch (ClassNotFoundException e) {
     throw new IOException(StringUtils.toString("Read object failed.", e));
   }
 }
예제 #9
0
 @Override
 public UserTradeBaseVo getUserWholeInfoByToken(String token) {
   if (StringUtils.isBlank(token)) {
     return null;
   }
   return cacheService.getUserWholeInfoByToken(token);
 }
예제 #10
0
 @Deprecated
 protected Object decodeHeartbeatData(ObjectInput in) throws IOException {
   try {
     return in.readObject();
   } catch (ClassNotFoundException e) {
     throw new IOException(StringUtils.toString("Read object failed.", e));
   }
 }
예제 #11
0
 /** 在spring启动时加载一遍 */
 @PostConstruct
 @Transactional
 private void loadLdapOrgData() {
   // 负数表示不启用
   if (StringUtils.isNotEmpty(orgSynctime) && Long.parseLong(orgSynctime) > 0) {
     freshOrgData(orgSynctime);
   }
 }
예제 #12
0
  public static RouteRule parse(String rule) throws ParseException {
    if (StringUtils.isBlank(rule)) {
      throw new ParseException("Illegal blank route rule", 0);
    }

    final Matcher matcher = CONDITION_SEPERATOR.matcher(rule);
    if (!matcher.matches()) throw new ParseException("condition seperator => not found!", 0);

    return parse(matcher.group(1), matcher.group(2));
  }
예제 #13
0
 private AccountOrg convertldapOrgToEntity(LdapOrg ldapOrg) {
   // 含有部门编码则不是组织
   if (StringUtils.isNotEmpty(ldapOrg.getDeptcode())) {
     return null;
   }
   AccountOrg accountOrg = new AccountOrg();
   accountOrg.setFatherorg(ldapOrg.getFatherorg());
   accountOrg.setOrgcode(ldapOrg.getOrgcode());
   accountOrg.setOrgname(ldapOrg.getOrgname());
   accountOrg.setPkfatherorg(ldapOrg.getPkfatherorg());
   accountOrg.setPkorg(ldapOrg.getPkorg());
   return accountOrg;
 }
예제 #14
0
 private AccountDept convertldapOrgToDeptEntity(LdapOrg ldapOrg) {
   // 部门编码必填
   if (StringUtils.isBlank(ldapOrg.getDeptcode())) {
     return null;
   }
   AccountDept accountDept = new AccountDept();
   accountDept.setDeptcode(ldapOrg.getDeptcode());
   accountDept.setDeptname(ldapOrg.getDeptname());
   accountDept.setFatherdept(ldapOrg.getFatherdept());
   accountDept.setOrgcode(ldapOrg.getOrgcode());
   accountDept.setOrgname(ldapOrg.getOrgname());
   accountDept.setPkdept(ldapOrg.getPkdept());
   accountDept.setPkfatherdept(ldapOrg.getPkfatherdept());
   accountDept.setPkorg(ldapOrg.getPkorg());
   return accountDept;
 }
예제 #15
0
  static Map<String, String> appendMethodsToUrls(
      Map<String, String> serviceUrls, Map<String, Set<String>> url2Methods) {
    // 为URL上加上方法参数
    Map<String, String> results = new HashMap<String, String>();
    for (Map.Entry<String, Set<String>> entry : url2Methods.entrySet()) {
      String url = entry.getKey();
      String query = serviceUrls.get(url);

      Set<String> methodNames = entry.getValue();
      if (methodNames != null && methodNames.size() > 0) {
        String ms = StringUtils.join(methodNames.toArray(new String[0]), ParseUtils.METHOD_SPLIT);
        query = ParseUtils.replaceParameter(query, "methods", ms);
      }
      results.put(url, query);
    }
    return results;
  }
예제 #16
0
  public static com.dubbo.domain.Override url2Override(Pair<Long, URL> pair) {
    if (pair == null) {
      return null;
    }

    Long id = pair.getKey();
    URL url = pair.getValue();

    if (null == url) return null;

    Override o = new Override();
    o.setId(id);

    Map<String, String> parameters = new HashMap<String, String>(url.getParameters());

    o.setService(url.getServiceKey());
    parameters.remove(Constants.INTERFACE_KEY);
    parameters.remove(Constants.GROUP_KEY);
    parameters.remove(Constants.VERSION_KEY);
    parameters.remove(Constants.APPLICATION_KEY);
    parameters.remove(Constants.CATEGORY_KEY);
    parameters.remove(Constants.DYNAMIC_KEY);
    parameters.remove(Constants.ENABLED_KEY);

    o.setEnabled(url.getParameter(Constants.ENABLED_KEY, true));

    String host = url.getHost();
    boolean anyhost = url.getParameter(Constants.ANYHOST_VALUE, false);
    if (!anyhost || !"0.0.0.0".equals(host)) {
      o.setAddress(url.getAddress());
    }

    o.setApplication(url.getParameter(Constants.APPLICATION_KEY, url.getUsername()));
    parameters.remove(Constants.VERSION_KEY);

    o.setParams(StringUtils.toQueryString(parameters));

    return o;
  }
  /** 创建新连接. */
  private ExchangeClient initClient(URL url) {
    // 指定自己的exchanger
    url = url.addParameterIfAbsent(Constants.EXCHANGER_KEY, HeaderExchanger2.NAME);
    // client type setting.
    url =
        url.addParameterIfAbsent(
            Constants.CLIENT_KEY, url.getParameter(Constants.SERVER_KEY, NettyTransporter2.NAME));
    // check client type
    String str =
        url.getParameter(
            Constants.CLIENT_KEY, url.getParameter(Constants.SERVER_KEY, NettyTransporter2.NAME));
    // BIO存在严重性能问题,暂时不允许使用
    if (str != null
        && str.length() > 0
        && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
      throw new RpcException(
          "Unsupported client type: "
              + str
              + ","
              + " supported client type is "
              + StringUtils.join(
                  ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(),
                  " "));
    }

    ExchangeClient client;
    try {
      // 设置连接应该是lazy的
      if (url.getParameter(Constants.LAZY_CONNECT_KEY, false)) {
        client = new LazyConnectExchangeClient(url, requestHandler);
      } else {
        client = Exchangers.connect(url, requestHandler);
      }
    } catch (RemotingException e) {
      throw new RpcException(
          "Fail to create remoting client for service(" + url + "): " + e.getMessage(), e);
    }
    return client;
  }
예제 #18
0
  public void disableProvider(Long id) {
    if (id == null) {
      throw new IllegalStateException("no provider id");
    }

    Provider oldProvider = findProvider(id);
    if (oldProvider == null) {
      throw new IllegalStateException("Provider was changed!");
    }

    if (oldProvider.isDynamic()) {
      // 保证disable的override唯一
      if (oldProvider.isEnabled()) {
        Override override = new Override();
        override.setAddress(oldProvider.getAddress());
        override.setService(oldProvider.getService());
        override.setEnabled(true);
        override.setParams(Constants.DISABLED_KEY + "=true");
        overrideService.saveOverride(override);
        return;
      }
      List<Override> oList =
          overrideService.findByServiceAndAddress(
              oldProvider.getService(), oldProvider.getAddress());

      for (Override o : oList) {
        Map<String, String> params = StringUtils.parseQueryString(o.getParams());
        if (params.containsKey(Constants.DISABLED_KEY)) {
          if (params.get(Constants.DISABLED_KEY).equals("false")) {
            overrideService.deleteOverride(o.getId());
          }
        }
      }
    } else {
      oldProvider.setEnabled(false);
      updateProvider(oldProvider);
    }
  }
예제 #19
0
  protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res)
      throws IOException {
    try {
      Serialization serialization = getSerialization(channel);
      // header.
      byte[] header = new byte[HEADER_LENGTH];
      // set magic number.
      Bytes.short2bytes(MAGIC, header);
      // set request and serialization flag.
      header[2] = serialization.getContentTypeId();
      if (res.isHeartbeat()) header[2] |= FLAG_EVENT;
      // set response status.
      byte status = res.getStatus();
      header[3] = status;
      // set request id.
      Bytes.long2bytes(res.getId(), header, 4);

      int savedWriteIndex = buffer.writerIndex();
      buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
      ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
      ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
      try {
        // encode response data or error message.
        if (status == Response.OK) {
          if (res.isHeartbeat()) {
            encodeHeartbeatData(channel, out, res.getResult());
          } else {
            encodeResponseData(channel, out, res.getResult());
          }
        } else out.writeUTF(res.getErrorMessage());
        out.flushBuffer();
      } finally {
        // modified by lishen
        if (out instanceof Cleanable) {
          ((Cleanable) out).cleanup();
        }
      }

      bos.flush();
      bos.close();

      int len = bos.writtenBytes();
      checkPayload(channel, len);
      Bytes.int2bytes(len, header, 12);
      // write
      buffer.writerIndex(savedWriteIndex);
      buffer.writeBytes(header); // write header.
      buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
    } catch (Throwable t) {
      // 发送失败信息给Consumer,否则Consumer只能等超时了
      if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
        try {
          // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理?
          logger.warn(
              "Fail to encode response: "
                  + res
                  + ", send bad_response info instead, cause: "
                  + t.getMessage(),
              t);

          Response r = new Response(res.getId(), res.getVersion());
          r.setStatus(Response.BAD_RESPONSE);
          r.setErrorMessage(
              "Failed to send response: " + res + ", cause: " + StringUtils.toString(t));
          channel.send(r);

          return;
        } catch (RemotingException e) {
          logger.warn(
              "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e);
        }
      }

      // 重新抛出收到的异常
      if (t instanceof IOException) {
        throw (IOException) t;
      } else if (t instanceof RuntimeException) {
        throw (RuntimeException) t;
      } else if (t instanceof Error) {
        throw (Error) t;
      } else {
        throw new RuntimeException(t.getMessage(), t);
      }
    }
  }
예제 #20
0
  public static Map<String, MatchPair> parseRule(String rule) throws ParseException {
    Map<String, MatchPair> condition = new HashMap<String, RouteRule.MatchPair>();
    if (StringUtils.isBlank(rule)) {
      return condition;
    }
    // 匹配或不匹配Key-Value对
    MatchPair pair = null;
    // 多个Value值
    Set<String> values = null;
    final Matcher matcher = ROUTE_PATTERN.matcher(rule);
    while (matcher.find()) { // 逐个匹配
      String separator = matcher.group(1);
      String content = matcher.group(2);
      // 表达式开始
      if (separator == null || separator.length() == 0) {
        pair = new MatchPair();
        condition.put(content, pair);
      }
      // KV开始
      else if ("&".equals(separator)) {
        if (condition.get(content) == null) {
          pair = new MatchPair();
          condition.put(content, pair);
        } else {
          condition.put(content, pair);
        }

      }
      // KV的Value部分开始
      else if ("=".equals(separator)) {
        if (pair == null)
          throw new ParseException(
              "Illegal route rule \""
                  + rule
                  + "\", The error char '"
                  + separator
                  + "' at index "
                  + matcher.start()
                  + " before \""
                  + content
                  + "\".",
              matcher.start());

        values = pair.matches;
        values.add(content);
      }
      // KV的Value部分开始
      else if ("!=".equals(separator)) {
        if (pair == null)
          throw new ParseException(
              "Illegal route rule \""
                  + rule
                  + "\", The error char '"
                  + separator
                  + "' at index "
                  + matcher.start()
                  + " before \""
                  + content
                  + "\".",
              matcher.start());

        values = pair.unmatches;
        values.add(content);
      }
      // KV的Value部分的多个条目
      else if (",".equals(separator)) { // 如果为逗号表示
        if (values == null || values.size() == 0)
          throw new ParseException(
              "Illegal route rule \""
                  + rule
                  + "\", The error char '"
                  + separator
                  + "' at index "
                  + matcher.start()
                  + " before \""
                  + content
                  + "\".",
              matcher.start());
        values.add(content);
      } else {
        throw new ParseException(
            "Illegal route rule \""
                + rule
                + "\", The error char '"
                + separator
                + "' at index "
                + matcher.start()
                + " before \""
                + content
                + "\".",
            matcher.start());
      }
    }
    return condition;
  }
예제 #21
0
파일: URL.java 프로젝트: rainsongsky/dubbo
 public URL addParameterString(String query) {
   if (query == null || query.length() == 0) {
     return this;
   }
   return addParameters(StringUtils.parseQueryString(query));
 }