Java Code Examples for com.alibaba.fastjson.serializer.SerializerFeature

The following examples show how to use com.alibaba.fastjson.serializer.SerializerFeature. These examples are extracted from open source projects. 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
@Override
public String getCluster() {
    try {
        Map<String, Object> result = Maps.newHashMap();
        ClusterConfiguration clusterConfiguration = sqlClient.getAdminClient().getClusterConfiguration().get();

        for (URI voter : clusterConfiguration.getVoters()) {
            if (voter.getHost().equals(IpUtil.getLocalIp())) {
                ServerStatus serverStatus = sqlClient.getAdminClient().getServerStatus(voter).get();
                result.put("status", serverStatus);
            }
        }

        result.put("cluster", clusterConfiguration);
        return JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
    } catch (Exception e) {
        throw new NsrException(e);
    }
}
 
Example 2
Source Project: java-unified-sdk   Source File: ArchivedRequestsTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testOperationSerialize() {
  List<BaseOperation> ops = new ArrayList<>();
  SetOperation setOp = new SetOperation("age", 3);
  ops.add(setOp);
  AddOperation addOp = new AddOperation("course", "Computer Science");
  ops.add(addOp);
  BitAndOperation bitAndOp = new BitAndOperation("score", 0x002);
  ops.add(bitAndOp);
  String opString = JSON.toJSONString(ops, ObjectValueFilter.instance, /*SerializerFeature.WriteClassName, */SerializerFeature.QuoteFieldNames,
          SerializerFeature.DisableCircularReferenceDetect);

  System.out.println(opString);

  List<BaseOperation> parsedOps = JSON.parseObject(opString,
          new TypeReference<List<BaseOperation>>() {}, IgnoreNotMatch);
  assertEquals(ops.size(), parsedOps.size());
}
 
Example 3
Source Project: littleca   Source File: WebMvcConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //1.需要定义一个convert转换消息的对象;
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
    //2.添加fastJson的配置信息,比如:是否要格式化返回的json数据;
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    //3处理中文乱码问题
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON);
    fastJsonConfig.setCharset(Charset.forName("UTF-8"));
    //4.在convert中添加配置信息.
    fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
    fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
    //5.将convert添加到converters当中.
    converters.add(1,fastJsonHttpMessageConverter);
}
 
Example 4
Source Project: xipki   Source File: CaconfDbExporter.java    License: Apache License 2.0 6 votes vote down vote up
public void export() throws Exception {
  CaCertstore.Caconf caconf = new CaCertstore.Caconf();
  caconf.setVersion(VERSION);

  System.out.println("exporting CA configuration from database");

  exportSigner(caconf);
  exportRequestor(caconf);
  exportUser(caconf);
  exportPublisher(caconf);
  exportCa(caconf);
  exportProfile(caconf);
  exportCaalias(caconf);
  exportCaHasRequestor(caconf);
  exportCaHasUser(caconf);
  exportCaHasPublisher(caconf);
  exportCaHasProfile(caconf);

  caconf.validate();
  try (OutputStream os = Files.newOutputStream(Paths.get(baseDir, FILENAME_CA_CONFIGURATION))) {
    JSON.writeJSONString(os, caconf, SerializerFeature.PrettyFormat);
  }
  System.out.println(" exported CA configuration from database");
}
 
Example 5
Source Project: sophia_scaffolding   Source File: RedisConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  使用@Bean注入fastJsonHttpMessageConvert,fastJson序列化
 */
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
    // 1、需要先定义一个 convert 转换消息的对象;
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

    //2-1 处理中文乱码问题
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConverter.setSupportedMediaTypes(fastMediaTypes);

    //3、在convert中添加配置信息.
    fastConverter.setFastJsonConfig(fastJsonConfig);
    HttpMessageConverter<?> converter = fastConverter;
    return new HttpMessageConverters(converter);
}
 
Example 6
Source Project: sophia_scaffolding   Source File: RedisConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  使用@Bean注入fastJsonHttpMessageConvert,fastJson序列化
 */
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
    // 1、需要先定义一个 convert 转换消息的对象;
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

    //2-1 处理中文乱码问题
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConverter.setSupportedMediaTypes(fastMediaTypes);

    //3、在convert中添加配置信息.
    fastConverter.setFastJsonConfig(fastJsonConfig);
    HttpMessageConverter<?> converter = fastConverter;
    return new HttpMessageConverters(converter);
}
 
Example 7
Source Project: addrparser   Source File: JSONFileRegionDataOutput.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws IOException {

    if (initialized) {
        return;
    }

    synchronized (this) {
        if (initialized) {
            return;
        }

        if (this.filename == null) {
            this.writer = new JSONWriter(_writer);
        } else {
            this.writer = new JSONWriter(new FileWriter(filename));
        }

        this.writer.config(SerializerFeature.WriteEnumUsingName, false);
        this.writer.config(SerializerFeature.SortField, false);
        this.writer.startArray();

        this.initialized = true;
    }
}
 
Example 8
Source Project: hsweb-framework   Source File: TermExpressionParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNest() {
    String expression = "name = 测试 and (age > 10 or age <= 20) and test like test2 and (age gt age2 or age btw age3,age4 or (age > 10 or age <= 20))";
    System.out.println(expression);
    List<Term> terms = TermExpressionParser.parse(expression);
    System.out.println(JSON.toJSONString(terms, SerializerFeature.PrettyFormat));
    Assert.assertNotNull(terms);
    Assert.assertEquals(terms.size(), 4);
    Assert.assertEquals(terms.get(1).getTerms().size(),2);
    Assert.assertEquals(terms.get(0).getColumn(), "name");
    Assert.assertEquals(terms.get(0).getValue(), "测试");

    Assert.assertEquals(terms.get(1).getTerms().get(0).getColumn(), "age");
    Assert.assertEquals(terms.get(1).getTerms().get(0).getTermType(), "gt");
    Assert.assertEquals(terms.get(1).getTerms().get(0).getValue(), "10");
    Assert.assertEquals(terms.get(1).getTerms().get(1).getColumn(), "age");
    Assert.assertEquals(terms.get(1).getTerms().get(1).getTermType(), "lte");
    Assert.assertEquals(terms.get(1).getTerms().get(1).getValue(), "20");
    Assert.assertEquals(terms.get(1).getTerms().get(1).getType(), Term.Type.or);

    Assert.assertEquals(terms.get(2).getColumn(), "test");
    Assert.assertEquals(terms.get(2).getValue(), "test2");
    Assert.assertEquals(terms.get(2).getTermType(), "like");

}
 
Example 9
Source Project: java-magento-client   Source File: MagentoMyCartManager.java    License: MIT License 6 votes vote down vote up
public boolean transferGuestCartToMyCart(String guestCartId) {
   if(customerId == -1L) {
      Account account = client.getMyAccount();
      customerId = account.getId();
      storeId = account.getStore_id();
   }
   Map<String, Object> request = new HashMap<>();
   request.put("customerId", customerId);
   request.put("storeId", storeId);
   String json = JSON.toJSONString(request, SerializerFeature.BrowserCompatible);
   json = putSecure(baseUri() + "/rest/V1/guest-carts/" + guestCartId, json);

   if(!validate(json)){
      return false;
   }

   

   return true;
}
 
Example 10
Source Project: s2g-zuul   Source File: HttpUtil.java    License: MIT License 6 votes vote down vote up
public static <T> T postData(CloseableHttpClient httpClient,String url, Object par, Map<String, String> header, Class<T> clazz)
		throws ClientProtocolException, IOException {
	HttpPost method = new HttpPost(url);
	method.setHeader("Content-type", "application/json; charset=utf-8");
	method.setHeader("Accept", "application/json");
	if (header != null) {
		for (String key : header.keySet()) {
			method.setHeader(key, header.get(key));
		}
	}
	if (par != null) {
		String parameters = JSON.toJSONString(par, SerializerFeature.DisableCircularReferenceDetect);
		HttpEntity entity = new StringEntity(parameters, Charset.forName("UTF-8"));
		method.setEntity(entity);
	}
	CloseableHttpResponse response = httpClient.execute(method);
	String body = EntityUtils.toString(response.getEntity());
	return JSON.parseObject(body, clazz);
}
 
Example 11
@Override
public void sendWarning(String category, String name, String description) {
   AuditEvent auditEvent = new AuditEvent();
   auditEvent.setCategory(category);
   auditEvent.setDescription(description);
   auditEvent.setName(name);
   auditEvent.setTime(new Date());
   auditEvent.setCount(counter++);
   auditEvent.setLevel("Warning");

   enqueue(auditEvent);

   histogram.put(category, histogram.getOrDefault(category, 0L) + 1);

   lastEvent = auditEvent;

   brokerMessagingTemplate.convertAndSend("/topics/event", JSON.toJSONString(auditEvent, SerializerFeature.BrowserCompatible));
}
 
Example 12
Source Project: java-magento-client   Source File: MagentoCategoryManager.java    License: MIT License 6 votes vote down vote up
public long addCategory(Category category) {
   Map<String, Object> cat = new HashMap<>();
   cat.put("id", category.getId());
   cat.put("parent_id", category.getParent_id());
  cat.put("name", category.getName());
  cat.put("is_active", category.is_active());
  cat.put("position", category.getPosition());
  cat.put("level", category.getLevel());
  cat.put("children", "string");
   cat.put("include_in_menu", true);
   cat.put("available_sort_by", new ArrayList<>());
   cat.put("extension_attributes", new ArrayList<>());
   cat.put("custom_attributes", new ArrayList<>());
   Map<String, Object> req = new HashMap<>();
   req.put("category", cat);
   String url = baseUri() + "/" + relativePath4Categories;

   String body = JSON.toJSONString(req, SerializerFeature.BrowserCompatible);
   String json = postSecure(url, body);

   if(!validate(json)){
      return -1;
   }
   return Long.parseLong(json);
}
 
Example 13
Source Project: chronus   Source File: TestCaseUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String object2JsonString(Object object,Class clazz,String... ignoreField){
    Field[] fields = clazz.getDeclaredFields();
    String[] fieldName = new String[fields.length-ignoreField.length];
    int i = 0;
    for(Field field:fields) {
        List<String> ignoreFields = Arrays.asList(ignoreField);
        if(!ignoreFields.contains(field.getName())) {
            fieldName[i++] = field.getName();
        }
    }
    SimplePropertyPreFilter filter = new SimplePropertyPreFilter(clazz, fieldName);
    return JSON.toJSONString(object,filter,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.PrettyFormat,
            SerializerFeature.WriteNullStringAsEmpty,
            SerializerFeature.WriteNullListAsEmpty);
}
 
Example 14
Source Project: nano-framework   Source File: JdbcAdapter.java    License: Apache License 2.0 6 votes vote down vote up
public Result executeQuery(final String sql, final List<Object> values, final Connection conn) throws SQLException {
    Assert.notNull(conn);
    final long start = System.currentTimeMillis();
    Result result = null;
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    try {
        pstmt = getPreparedStmt(conn, sql, values);
        pstmt.setQueryTimeout(60);
        rs = pstmt.executeQuery();
        rs.setFetchSize(rs.getRow());
        result = ResultSupport.toResult(rs);
    } finally {
        close(rs, pstmt);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[ Execute Query SQL ]: {} [cost {}ms ]", sql, System.currentTimeMillis() - start);
            LOGGER.debug("[ Execute Parameter ]: {}", JSON.toJSONString(values, SerializerFeature.WriteDateUseDateFormat));
        }
    }

    return result;
}
 
Example 15
public void addMonitorLog(String sessionId,AlbianMonitorData data) {
   String json =  JSON.toJSONString(data,
            SerializerFeature.SkipTransientField,
            SerializerFeature.WriteDateUseDateFormat,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullBooleanAsFalse,
            SerializerFeature.WriteNullListAsEmpty,
            SerializerFeature.WriteNullNumberAsZero,
            SerializerFeature.WriteNullStringAsEmpty,
            SerializerFeature.DisableCircularReferenceDetect);
    try {
        mlog.info(json);
    }catch (Exception e){
        throw new RuntimeException(e);
    }
}
 
Example 16
Source Project: canal-1.1.3   Source File: RdbSyncService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 单条 dml 同步
 *
 * @param batchExecutor 批量事务执行器
 * @param config 对应配置对象
 * @param dml DML
 */
public void sync(BatchExecutor batchExecutor, MappingConfig config, SingleDml dml) {
    if (config != null) {
        try {
            String type = dml.getType();
            if (type != null && type.equalsIgnoreCase("INSERT")) {
                insert(batchExecutor, config, dml);
            } else if (type != null && type.equalsIgnoreCase("UPDATE")) {
                update(batchExecutor, config, dml);
            } else if (type != null && type.equalsIgnoreCase("DELETE")) {
                delete(batchExecutor, config, dml);
            } else if (type != null && type.equalsIgnoreCase("TRUNCATE")) {
                truncate(batchExecutor, config);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("DML: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 17
Source Project: java-magento-client   Source File: MagentoClientMyCartUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void test_addItemToCart(){
   MagentoClient client = new MagentoClient(Mediator.url);
   client.loginAsClient(Mediator.customerUsername, Mediator.customerPassword);
   String quoteId = client.myCart().newQuote();

   CartItem item = new CartItem();
   item.setQty(1);
   item.setSku("product_dynamic_758");

   System.out.println(quoteId);

   item = client.myCart().addItemToCart(quoteId, item);

   Cart cart = client.myCart().getCart();
   CartTotal cartTotal = client.myCart().getCartTotal();

   logger.info("cartItem: \r\n{}", JSON.toJSONString(item, SerializerFeature.PrettyFormat));
   logger.info("cart: \r\n{}", JSON.toJSONString(cart, SerializerFeature.PrettyFormat));
   logger.info("cartTotal: \r\n{}", JSON.toJSONString(cartTotal, SerializerFeature.PrettyFormat));
}
 
Example 18
Source Project: canal   Source File: RdbSyncService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 单条 dml 同步
 *
 * @param batchExecutor 批量事务执行器
 * @param config 对应配置对象
 * @param dml DML
 */
public void sync(BatchExecutor batchExecutor, MappingConfig config, SingleDml dml) {
    if (config != null) {
        try {
            String type = dml.getType();
            if (type != null && type.equalsIgnoreCase("INSERT")) {
                insert(batchExecutor, config, dml);
            } else if (type != null && type.equalsIgnoreCase("UPDATE")) {
                update(batchExecutor, config, dml);
            } else if (type != null && type.equalsIgnoreCase("DELETE")) {
                delete(batchExecutor, config, dml);
            } else if (type != null && type.equalsIgnoreCase("TRUNCATE")) {
                truncate(batchExecutor, config);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("DML: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 19
@Override
public void set(String cachedName, String k, Object v, int tto) {
    // TODO Auto-generated method stub
    String body = JSON.toJSONString(v, SerializerFeature.WriteClassName);
    if (isCluster) {
        jc.set(k, body);
        jc.expire(k, tto);
    } else {
        ShardedJedis sj = null;
        try {
            sj = sjp.getResource();
            sj.set(k, body);
            sj.expire(k, tto);
        } catch (Exception e) {
            AlbianServiceRouter.getLogger().error(
                    IAlbianLoggerService.AlbianRunningLoggerName, e,
                    "set object:%s is fail.", k);
        } finally {
            if (null != sj)
                sjp.returnResourceObject(sj);
        }
    }
}
 
Example 20
Source Project: SpringBootLearn   Source File: FastJsonRedisSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize(T t) throws SerializationException {
    if (null == t) {
        return new byte[0];
    }
    return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
 
Example 21
Source Project: AthenaServing   Source File: SecurityInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 输出
 *
 * @param httpServletResponse
 * @param code
 * @param msg
 * @throws Exception
 */
private void output(HttpServletResponse httpServletResponse, int code, String msg) throws Exception {
	Response<String> response = new Response<>(code, msg);
	httpServletResponse.setCharacterEncoding("UTF-8");
	httpServletResponse.setContentType("application/json");
	PrintWriter out = httpServletResponse.getWriter();
	out.print(JSON.toJSONString(response, SerializerFeature.WriteMapNullValue));
	out.flush();
}
 
Example 22
Source Project: springBoot-study   Source File: Application.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将JSON序列化换成FastJson
 */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
	super.configureMessageConverters(converters);
	FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
	FastJsonConfig fastJsonConfig = new FastJsonConfig();
	fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
	fastConverter.setFastJsonConfig(fastJsonConfig);

	converters.add(fastConverter);
}
 
Example 23
@Test
public void test_delete_product_media() {
   String productSku = "B202-SKU";
   MagentoClient client = new MagentoClient(Mediator.url);
   client.loginAsAdmin(Mediator.adminUsername, Mediator.adminPassword);
   long entryId = 2L;
   logger.info("media deleted: \r\n{}", JSON.toJSONString(client.media().deleteProductMedia(productSku, entryId), SerializerFeature.PrettyFormat));
}
 
Example 24
Source Project: hsweb-framework   Source File: HswebAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "fastjson")
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    converter.setFeatures(
            SerializerFeature.WriteNullListAsEmpty,
            SerializerFeature.WriteNullNumberAsZero,
            SerializerFeature.WriteNullBooleanAsFalse
    );
    converter.setConverters(converters);
    return converter;
}
 
Example 25
Source Project: java-reinforcement-learning   Source File: MatrixUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testJsonSerialization() {
    Matrix matrix = new Matrix(10, 10);
    matrix.set(0, 0, 10);
    matrix.set(4, 2, 2);
    matrix.set(3, 3, 2);

    assertThat(matrix.get(0, 0)).isEqualTo(10);
    assertThat(matrix.get(4, 2)).isEqualTo(2);
    assertThat(matrix.get(3, 3)).isEqualTo(2);
    assertThat(matrix.get(4, 4)).isEqualTo(0);

    assertThat(matrix.getRowCount()).isEqualTo(10);
    assertThat(matrix.getColumnCount()).isEqualTo(10);

    String json = JSON.toJSONString(matrix, SerializerFeature.PrettyFormat);

    System.out.println(json);
    Matrix matrix2 = JSON.parseObject(json, Matrix.class);
    assertThat(matrix).isEqualTo(matrix2);

    for(int i=0; i < matrix.getRowCount(); ++i){
        for(int j=0; j < matrix.getColumnCount(); ++j) {
            assertThat(matrix.get(i, j)).isEqualTo(matrix2.get(i, j));
        }
    }
}
 
Example 26
Source Project: java-unified-sdk   Source File: BaseOperationAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType,
                  int features) throws IOException {
  BaseOperation op = (BaseOperation)object;
  SerializeWriter writer = serializer.getWriter();
  writer.write('{');
  writer.writeFieldValue(' ', ATTR_OP, op.getOperation());
  writer.writeFieldValue(' ', ATTR_FIELD, op.getField());
  writer.writeFieldValue(',', ATTR_FINAL, op.isFinal);
  if (AVOSCloud.isEnableCircularReferenceDetect()) {
    writer.writeFieldValue(',', ATTR_OBJECT,
            JSON.toJSONString(op.getValue(), ObjectValueFilter.instance,
                    SerializerFeature.WriteClassName));
  } else {
    writer.writeFieldValue(',', ATTR_OBJECT,
            JSON.toJSONString(op.getValue(), ObjectValueFilter.instance,
                    SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect));
  }

  if (object instanceof CompoundOperation) {
    if (AVOSCloud.isEnableCircularReferenceDetect()) {
      writer.writeFieldValue(',', ATTR_SUBOPS,
              JSON.toJSONString(((CompoundOperation)op).getSubOperations(), ObjectValueFilter.instance,
                      SerializerFeature.WriteClassName));
    } else {
      writer.writeFieldValue(',', ATTR_SUBOPS,
              JSON.toJSONString(((CompoundOperation)op).getSubOperations(), ObjectValueFilter.instance,
                      SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect));
    }
  }
  writer.write('}');
}
 
Example 27
Source Project: FimiX8-RE   Source File: DataJsonFactory.java    License: MIT License 5 votes vote down vote up
public static String appValueSensityChange(String tag, ValueSensity oldV, ValueSensity newV) {
    Object dataObject = new JSONObject();
    String json = "";
    Object object = new JSONObject();
    object.put(tag, new SensityJsonChange(oldV, newV));
    dataObject.put("data", object);
    dataObject.put("startupTime", "" + X8AppSettingLog.STARTUPTIME);
    dataObject.put(BlockInfo.KEY_TIME_COST, DateUtil.getStringByFormat(System.currentTimeMillis(), HostConstants.FORMATDATE));
    return JSON.toJSONString(dataObject, SerializerFeature.PrettyFormat);
}
 
Example 28
Source Project: hsweb-framework   Source File: AuthorizeTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 测试数据权限控制s
 */
@Test
public void testGetDataAccessHandler() {

    DefaultAuthorizingHandler handler = new DefaultAuthorizingHandler();
    DefaultDataAccessController controller = new DefaultDataAccessController();
    handler.setDataAccessController(controller);


    AuthorizeDefinition definition = parser.parse(queryById.getTarget().getClass(), queryById.getMethod());

    //响应结果
    Object response = queryById.getInvokeResult();

    System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat));

    AuthorizingContext authorizingContext = new AuthorizingContext();
    authorizingContext.setAuthentication(authentication);
    authorizingContext.setDefinition(definition);
    authorizingContext.setParamContext(queryById);

    handler.handleDataAccess(authorizingContext);

    System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat));
    Assert.assertTrue(response instanceof ResponseMessage);
    Assert.assertTrue(((User) ((ResponseMessage) response).getResult()).getPassword() == null);
    Assert.assertTrue(((User) ((ResponseMessage) response).getResult()).getSalt() == null);
}
 
Example 29
@Override
public byte[] serialize(T t) throws SerializationException {
    if (t == null) {
        return new byte[0];
    }
    return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
 
Example 30
@Test
public void test_get_category_by_id(){
   long id = 15;

   MagentoClient client = new MagentoClient(Mediator.url);
   client.loginAsAdmin(Mediator.adminUsername, Mediator.adminPassword);
   Category category = client.categories().getCategoryByIdClean(id);
   logger.info("category:\r\n{}", JSON.toJSONString(category, SerializerFeature.PrettyFormat));

   category = client.categories().getCategoryByIdWithChildren(id);
   logger.info("category:\r\n{}", JSON.toJSONString(category, SerializerFeature.PrettyFormat));
}