org.apache.servicecomb.foundation.common.utils.JsonUtils Java Examples

The following examples show how to use org.apache.servicecomb.foundation.common.utils.JsonUtils. 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: TestRestClientInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetCseContext_failed() throws JsonProcessingException {
  LogCollector logCollector = new LogCollector();
  logCollector.setLogLevel(RestClientInvocation.class.getName(), Level.DEBUG);

  new Expectations(JsonUtils.class) {
    {
      JsonUtils.writeValueAsString(any);
      result = new RuntimeExceptionWithoutStackTrace();
    }
  };

  restClientInvocation.setCseContext();

  Assert.assertEquals("Failed to encode and set cseContext.", logCollector.getEvents().get(0).getMessage());
  logCollector.teardown();
}
 
Example #2
Source File: RouterServerListFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private Map<String, String> addHeaders(Invocation invocation) {
  Map<String, String> headers = new HashMap<>();
  if (invocation.getContext(ROUTER_HEADER) != null) {
    Map<String, String> canaryContext = null;
    try {
      canaryContext = JsonUtils.OBJ_MAPPER
          .readValue(invocation.getContext(ROUTER_HEADER),
              new TypeReference<Map<String, String>>() {
              });
    } catch (JsonProcessingException e) {
      LOGGER.error("canary context serialization failed");
    }
    if (canaryContext != null) {
      headers.putAll(canaryContext);
    }
  }
  invocation.getInvocationArguments().forEach((k, v) -> headers.put(k, v == null ? null : v.toString()));
  headers.putAll(invocation.getContext());
  return headers;
}
 
Example #3
Source File: TestWeakSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testGenericsModel() throws JsonProcessingException {
  GenericsModel model = new GenericsModel();
  model.setName("model");
  List<List<String>> namesList = new ArrayList<>();
  List<String> names = new ArrayList<>();
  names.add("hello");
  namesList.add(names);
  model.setNameList(namesList);
  List<List<List<Object>>> objectLists = new ArrayList<>();
  List<List<Object>> objectList = new ArrayList<>();
  List<Object> objects = new ArrayList<>();
  objects.add("object");
  objectList.add(objects);
  objectLists.add(objectList);
  model.setObjectLists(objectLists);
  GenericsModel result = genericsModelInf.genericParamsModel(100, model);
  TestMgr.check(JsonUtils.writeValueAsString(model), JsonUtils.writeValueAsString(result));
}
 
Example #4
Source File: RouterInvokeFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * pass through headers
 *
 * @param invocation
 * @param httpServletRequestEx
 * @return
 */
@Override
public Response afterReceiveRequest(Invocation invocation,
    HttpServletRequestEx httpServletRequestEx) {
  if (!isHaveHeadersRule()) {
    return null;
  }
  if (!RouterRuleCache.isServerContainRule(invocation.getMicroserviceName())) {
    return null;
  }
  if (loadHeaders()) {
    Map<String, String> headerMap = getHeaderMap(httpServletRequestEx);
    try {
      invocation.addContext(ROUTER_HEADER, JsonUtils.OBJ_MAPPER.writeValueAsString(headerMap));
    } catch (JsonProcessingException e) {
      LOGGER.error("canary context serialization failed");
    }
  }
  return null;
}
 
Example #5
Source File: TestWeakPojo.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testGenericsModel() throws JsonProcessingException {
  GenericsModel model = new GenericsModel();
  model.setName("model");
  List<List<String>> namesList = new ArrayList<>();
  List<String> names = new ArrayList<>();
  names.add("hello");
  namesList.add(names);
  model.setNameList(namesList);
  List<List<List<Object>>> objectLists = new ArrayList<>();
  List<List<Object>> objectList = new ArrayList<>();
  List<Object> objects = new ArrayList<>();
  objects.add("object");
  objectList.add(objects);
  objectLists.add(objectList);
  model.setObjectLists(objectLists);
  GenericsModel result = genericsModelInf.genericParamsModel(100, model);
  TestMgr.check(JsonUtils.writeValueAsString(model), JsonUtils.writeValueAsString(result));
}
 
Example #6
Source File: TestWeakPojo.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testObject() throws JsonProcessingException {
  GenericsModel model = new GenericsModel();
  model.setName("model");
  List<List<String>> namesList = new ArrayList<>();
  List<String> names = new ArrayList<>();
  names.add("hello");
  namesList.add(names);
  model.setNameList(namesList);
  List<List<List<Object>>> objectLists = new ArrayList<>();
  List<List<Object>> objectList = new ArrayList<>();
  List<Object> objects = new ArrayList<>();
  objects.add("object");
  objectList.add(objects);
  objectLists.add(objectList);
  model.setObjectLists(objectLists);
  GenericsModel result = objectInf.obj(model);
  TestMgr.check(JsonUtils.writeValueAsString(model), JsonUtils.writeValueAsString(result));
}
 
Example #7
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 #8
Source File: ParseConfigUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public void refreshConfigItemsIncremental(Map<String, Object> action) {
  try {
    configLock.lock();
    if ("UPDATE".equals(action.get("action"))) {
      try {
        multiDimensionItems.put((String) action.get("key"), JsonUtils.OBJ_MAPPER
            .readValue(action.get("value").toString(), new TypeReference<Map<String, Object>>() {
            }));
      } catch (IOException e) {
        LOGGER.error("parse config change action fail");
      }
      doRefreshItems();
    } else if ("DELETE".equals(action.get("action"))) {
      multiDimensionItems.remove(action.get("key"));
      doRefreshItems();
    }
  } finally {
    configLock.unlock();
  }
}
 
Example #9
Source File: FileServiceImpl.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
public boolean deleteFile(String id) {
    String session = ContextUtils.getInvocationContext().getContext("session-info");
    if (session == null) {
        throw new InvocationException(403, "", "not allowed");
    } else {
        SessionInfo sessionInfo = null;
        try {
            sessionInfo = JsonUtils.readValue(session.getBytes("UTF-8"), SessionInfo.class);
        } catch (Exception e) {
            throw new InvocationException(403, "", "session not allowed");
        }
        if (sessionInfo == null || !sessionInfo.getRoleName().equals("admin")) {
            throw new InvocationException(403, "", "not allowed");
        }
    }
    return fileService.deleteFile(id);
}
 
Example #10
Source File: FileServiceImpl.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
public boolean deleteFile(String id) {
    String session = ContextUtils.getInvocationContext().getContext("session-info");
    if (session == null) {
        throw new InvocationException(403, "", "not allowed");
    } else {
        SessionInfo sessionInfo = null;
        try {
            sessionInfo = JsonUtils.readValue(session.getBytes("UTF-8"), SessionInfo.class);
        } catch (Exception e) {
            throw new InvocationException(403, "", "session not allowed");
        }
        if (sessionInfo == null || !sessionInfo.getRoleName().equals("admin")) {
            throw new InvocationException(403, "", "not allowed");
        }
    }
    return fileService.deleteFile(id);
}
 
Example #11
Source File: ConfigObjectFactory.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void doCreate() {
  JavaType javaType = TypeFactory.defaultInstance().constructType(cls);
  BeanDescription beanDescription = JsonUtils.OBJ_MAPPER.getSerializationConfig().introspect(javaType);
  for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) {
    if (propertyDefinition.getField() == null) {
      continue;
    }

    if (propertyDefinition.getSetter() == null && !propertyDefinition.getField().isPublic()) {
      continue;
    }

    SetterWrapper setter = propertyDefinition.getSetter() == null ?
        new SetterWrapper(LambdaMetafactoryUtils.createSetter(propertyDefinition.getField().getAnnotated())) :
        new SetterWrapper(LambdaMetafactoryUtils.createSetter(propertyDefinition.getSetter().getAnnotated()));

    PriorityProperty<?> priorityProperty = createPriorityProperty(propertyDefinition.getField().getAnnotated());
    priorityProperty.setCallback((value, target) -> setter.set(target, value), instance);
    priorityProperties.add(priorityProperty);
  }
}
 
Example #12
Source File: CloudEyeFilePublisher.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
protected void logMeasurement(Measurement measurement, long now) {
  String metricKey = generateMetricKey(measurement);

  MDC.put("fileName", filePrefix + "." + metricKey + ".dat");

  CloudEyeMetricModel metricModel = new CloudEyeMetricModel();
  metricModel.setNode(hostName);
  metricModel.setTimestamp(now);
  metricModel.getDynamicValue().put(metricKey, String.valueOf(measurement.value()));

  CloudEyeModel model = new CloudEyeModel();
  model.setPlugin_id(filePrefix);
  model.setMetric(metricModel);

  try {
    CLOUD_EYE_LOGGER.info(JsonUtils.writeValueAsString(model));
  } catch (JsonProcessingException e) {
    LOGGER.error("Failed to write cloud eye log.", e);
  }
}
 
Example #13
Source File: HeaderPassUtil.java    From spring-cloud-huawei with Apache License 2.0 6 votes vote down vote up
public static String getPassHeaderString(Map<String, String> headers) {
  if (!isHaveHeadersRule()) {
    return null;
  }
  if (!RouterRuleCache.isServerContainRule(RouterTrackContext.getServiceName())) {
    return null;
  }
  if (loadHeaders()) {
    try {
      return JsonUtils.OBJ_MAPPER.writeValueAsString(getHeaderMap(headers));
    } catch (JsonProcessingException e) {
      LOGGER.error("canary context serialization failed : {}", e.getMessage());
    }
  }
  return null;
}
 
Example #14
Source File: ServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public String registerMicroserviceInstance(MicroserviceInstance instance) {
  Holder<RegisterInstanceResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  try {
    RegisterInstanceRequest request = new RegisterInstanceRequest();
    request.setInstance(instance);
    byte[] body = JsonUtils.writeValueAsBytes(request);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("register microservice: {}", new String(body, Charset.defaultCharset()));
    }

    CountDownLatch countDownLatch = new CountDownLatch(1);
    restClientUtil.post(ipPort,
        String.format(Const.REGISTRY_API.MICROSERVICE_INSTANCE_OPERATION_ALL, instance.getServiceId()),
        new RequestParam().setBody(body),
        syncHandler(countDownLatch, RegisterInstanceResponse.class, holder));
    countDownLatch.await();
    if (holder.value != null) {
      return holder.value.getInstanceId();
    }
  } catch (Exception e) {
    LOGGER.error("register microservice instance {} failed", instance.getServiceId(), e);
  }
  return null;
}
 
Example #15
Source File: ServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
    Map<String, String> instanceProperties) {
  Holder<HttpClientResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  try {
    UpdatePropertiesRequest request = new UpdatePropertiesRequest();
    request.setProperties(instanceProperties);
    byte[] body = JsonUtils.writeValueAsBytes(request);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("update properties of microservice instance: {}",
          new String(body, Charset.defaultCharset()));
    }

    CountDownLatch countDownLatch = new CountDownLatch(1);
    restClientUtil.put(ipPort,
        String.format(Const.REGISTRY_API.MICROSERVICE_INSTANCE_PROPERTIES, microserviceId, microserviceInstanceId),
        new RequestParam().setBody(body),
        syncHandler(countDownLatch, HttpClientResponse.class, holder));

    countDownLatch.await();
    if (holder.value != null) {
      if (holder.value.statusCode() == Status.OK.getStatusCode()) {
        return true;
      }
      LOGGER.warn(holder.value.statusMessage());
    }
  } catch (Exception e) {
    LOGGER.error("update properties of microservice instance {}/{} failed",
        microserviceId,
        microserviceInstanceId,
        e);
  }
  return false;
}
 
Example #16
Source File: ServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties) {
  Holder<HttpClientResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  try {
    UpdatePropertiesRequest request = new UpdatePropertiesRequest();
    request.setProperties(serviceProperties);
    byte[] body = JsonUtils.writeValueAsBytes(request);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("update properties of microservice: {}", new String(body, Charset.defaultCharset()));
    }

    CountDownLatch countDownLatch = new CountDownLatch(1);
    restClientUtil.put(ipPort,
        String.format(Const.REGISTRY_API.MICROSERVICE_PROPERTIES, microserviceId),
        new RequestParam().setBody(body),
        syncHandler(countDownLatch, HttpClientResponse.class, holder));

    countDownLatch.await();
    if (holder.value != null) {
      if (holder.value.statusCode() == Status.OK.getStatusCode()) {
        return true;
      }
      LOGGER.warn(holder.value.statusMessage());
    }
  } catch (Exception e) {
    LOGGER.error("update properties of microservice {} failed",
        microserviceId,
        e);
  }
  return false;
}
 
Example #17
Source File: ApolloClient.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
void refreshConfig() {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Content-Type", "application/json;charset=UTF-8");
  headers.add("Authorization", token);
  HttpEntity<String> entity = new HttpEntity<>(headers);
  ResponseEntity<String> exchange = rest.exchange(composeAPI(), HttpMethod.GET, entity, String.class);
  if (HttpResponseStatus.OK.code() == exchange.getStatusCode().value()) {
    try {
      Map<String, Object> body = JsonUtils.OBJ_MAPPER.readValue(exchange.getBody(),
          new TypeReference<Map<String, Object>>() {
          });
      refreshConfigItems((Map<String, Object>) body.get("configurations"));
    } catch (IOException e) {
      LOGGER.error("JsonObject parse config center response error: ", e);
    }
  } else {
    LOGGER.error("fetch configuration failed, error code:{} for {}",
        exchange.getStatusCodeValue(),
        exchange.getBody());
  }
}
 
Example #18
Source File: RestClientInvocation.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected void setCseContext() {
  try {
    String cseContext = JsonUtils.writeValueAsString(invocation.getContext());
    clientRequest.putHeader(org.apache.servicecomb.core.Const.CSE_CONTEXT, cseContext);
  } catch (Throwable e) {
    invocation.getTraceIdLogger().error(LOGGER, "Failed to encode and set cseContext.", e);
  }
}
 
Example #19
Source File: TestDefaultHttpClientFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAfterReceiveResponseNullProduceProcessor(@Mocked Invocation invocation,
    @Mocked HttpServletResponseEx responseEx,
    @Mocked OperationMeta operationMeta,
    @Mocked RestOperationMeta swaggerRestOperation) throws Exception {
  CommonExceptionData data = new CommonExceptionData("abcd");
  new Expectations() {
    {
      invocation.getOperationMeta();
      result = operationMeta;
      operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
      result = swaggerRestOperation;
      invocation.findResponseType(403);
      result = SimpleType.constructUnsafe(CommonExceptionData.class);
      responseEx.getStatus();
      result = 403;
      responseEx.getStatusType();
      result = Status.FORBIDDEN;
      responseEx.getBodyBuffer();
      result = Buffer.buffer(JsonUtils.writeValueAsString(data).getBytes());
    }
  };

  Response response = filter.afterReceiveResponse(invocation, responseEx);
  Assert.assertEquals(403, response.getStatusCode());
  Assert.assertEquals("Forbidden", response.getReasonPhrase());
  Assert.assertEquals(InvocationException.class, response.<InvocationException>getResult().getClass());
  InvocationException invocationException = response.getResult();
  Assert.assertEquals(
      403,
      invocationException.getStatusCode());
  Assert.assertEquals(
      "CommonExceptionData [message=abcd]",
      invocationException.getErrorData().toString());
}
 
Example #20
Source File: AbstractRestInvocation.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected void setContext() throws Exception {
  String strCseContext = requestEx.getHeader(Const.CSE_CONTEXT);
  if (StringUtils.isEmpty(strCseContext)) {
    return;
  }

  @SuppressWarnings("unchecked")
  Map<String, String> cseContext =
      JsonUtils.readValue(strCseContext.getBytes(StandardCharsets.UTF_8), Map.class);
  invocation.mergeContext(cseContext);
}
 
Example #21
Source File: TestAbstractRestInvocation.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void setContextNormal() throws Exception {
  Map<String, String> context = new HashMap<>();
  context.put("name", "value");
  new Expectations() {
    {
      requestEx.getHeader(Const.CSE_CONTEXT);
      result = JsonUtils.writeValueAsString(context);
    }
  };

  restInvocation.setContext();
  Assert.assertThat(invocation.getContext().size(), Matchers.is(1));
  Assert.assertThat(invocation.getContext(), Matchers.hasEntry("name", "value"));
}
 
Example #22
Source File: TestAbstractRestInvocation.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void setContextTraceId() throws Exception {
  Map<String, String> context = new HashMap<>();
  new Expectations() {
    {
      requestEx.getHeader(Const.CSE_CONTEXT);
      result = JsonUtils.writeValueAsString(context);
    }
  };
  invocation.addContext("X-B3-traceId", "value1");
  //if request has no traceId, use invocation's traceId
  restInvocation.setContext();
  Assert.assertThat(invocation.getContext().size(), Matchers.is(1));
  Assert.assertThat(invocation.getContext(), Matchers.hasEntry("X-B3-traceId", "value1"));

  context.put("X-B3-traceId", "value2");
  new Expectations() {
    {
      requestEx.getHeader(Const.CSE_CONTEXT);
      result = JsonUtils.writeValueAsString(context);
    }
  };
  //if request has traceId, use request's traceId
  restInvocation.setContext();
  Assert.assertThat(invocation.getContext().size(), Matchers.is(1));
  Assert.assertThat(invocation.getContext(), Matchers.hasEntry("X-B3-traceId", "value2"));
}
 
Example #23
Source File: ServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public String registerMicroservice(Microservice microservice) {
  Holder<CreateServiceResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();
  try {
    CreateServiceRequest request = new CreateServiceRequest();
    request.setService(microservice);
    byte[] body = JsonUtils.writeValueAsBytes(request);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("register microservice: {}", new String(body, Charset.defaultCharset()));
    }

    CountDownLatch countDownLatch = new CountDownLatch(1);
    restClientUtil.post(ipPort,
        Const.REGISTRY_API.MICROSERVICE_OPERATION_ALL,
        new RequestParam().setBody(body),
        syncHandler(countDownLatch, CreateServiceResponse.class, holder));
    countDownLatch.await();
    if (holder.value != null) {
      return holder.value.getServiceId();
    }
  } catch (Exception e) {
    LOGGER.error("register microservice {}/{}/{} failed",
        microservice.getAppId(),
        microservice.getServiceName(),
        microservice.getVersion(),
        e);
  }
  return null;
}
 
Example #24
Source File: AuthHeaderStrategyMount.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@Override
public void createAuthHeaders() {
  try {
    String content = new String(
        Files.readAllBytes(Paths.get(DEFAULT_SECRET_AUTH_PATH, DEFAULT_SECRET_AUTH_NAME)),
        "UTF-8");
    JsonNode data = JsonUtils.OBJ_MAPPER.readTree(content);
    JsonNode authNode = data.findValue("auth");
    decode(authNode);
  } catch (Exception e) {
    LOGGER.warn("read auth info from dockerconfigjson failed.", e);
  }
}
 
Example #25
Source File: TestThreadPoolPublishModelFactory.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void createDefaultPublishModel() throws JsonProcessingException {
  new Expectations() {
    {
      threadPoolExecutor.getQueue();
      result = queue;
      queue.size();
      result = 10d;
    }
  };
  new MockUp<ScheduledThreadPoolExecutor>() {
    @Mock
    void delayedExecute(RunnableScheduledFuture<?> task) {

    }
  };
  try {
    ThreadPoolMonitor.attach(registry, threadPoolExecutor, "test");

    PolledMeter.update(registry);
    PublishModelFactory factory = new PublishModelFactory(Lists.newArrayList(registry.iterator()));
    DefaultPublishModel model = factory.createDefaultPublishModel();

    Assert.assertEquals(
        "{\"test\":{\"avgTaskCount\":0.0,\"avgCompletedTaskCount\":0.0,\"currentThreadsBusy\":0,\"maxThreads\":0,\"poolSize\":0,\"corePoolSize\":0,\"queueSize\":10,\"rejected\":\"NaN\"}}",
        JsonUtils.writeValueAsString(model.getThreadPools()));
  } catch (Throwable e) {
    e.printStackTrace();
    Assert.fail("unexpected error happen. " + e.getMessage());
  }
}
 
Example #26
Source File: User.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public String jsonString() {
  try {
    return JsonUtils.writeValueAsString(this);
  } catch (JsonProcessingException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #27
Source File: User.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public String jsonString() {
  try {
    return JsonUtils.writeValueAsString(this);
  } catch (JsonProcessingException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #28
Source File: CommandReceiver.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void doRun() throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  String line;
  while ((line = reader.readLine()) != null) {
    try {
      JsonNode cmd = JsonUtils.OBJ_MAPPER.readTree(line);
      dispatchCommand(cmd);
    } catch (Throwable e) {
      LOGGER.error("Failed to execute command: {}", line, e);
    }
  }
  reader.close();
}
 
Example #29
Source File: NormalDeploy.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public void sendCommand(Object command) {
  String strCmd = null;
  try {
    strCmd = JsonUtils.writeValueAsString(command);
    subProcessCommandWriter.write(strCmd + "\n");
    subProcessCommandWriter.flush();
  } catch (Throwable e) {
    LOGGER.error("Failed to send command, displayName={}, command={}", deployDefinition.getDisplayName(), strCmd, e);
  }
}
 
Example #30
Source File: ServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Override
public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) {
  Holder<ResponseWrapper> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  try {
    CreateSchemaRequest request = new CreateSchemaRequest();
    request.setSchema(schemaContent);
    request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent));
    byte[] body = JsonUtils.writeValueAsBytes(request);

    CountDownLatch countDownLatch = new CountDownLatch(1);
    restClientUtil.put(ipPort,
        String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId),
        new RequestParam().setBody(body),
        syncHandlerEx(countDownLatch, holder));
    countDownLatch.await();

    if (holder.value == null) {
      LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId);
      return false;
    }

    if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) {
      LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.",
          microserviceId,
          schemaId,
          holder.value.response.statusCode(),
          holder.value.response.statusMessage(),
          holder.value.bodyBuffer.toString());
      return false;
    }

    LOGGER.info("register schema {}/{} success.",
        microserviceId,
        schemaId);
    return true;
  } catch (Exception e) {
    LOGGER.error("register schema {}/{} fail.",
        microserviceId,
        schemaId,
        e);
  }
  return false;
}