org.codehaus.jackson.map.ObjectMapper Java Examples

The following examples show how to use org.codehaus.jackson.map.ObjectMapper. 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: TestJsonUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testToAclStatus() throws IOException {
  String jsonString =
      "{\"AclStatus\":{\"entries\":[\"user::rwx\",\"user:user1:rw-\",\"group::rw-\",\"other::r-x\"],\"group\":\"supergroup\",\"owner\":\"testuser\",\"stickyBit\":false}}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  List<AclEntry> aclSpec =
      Lists.newArrayList(aclEntry(ACCESS, USER, ALL),
          aclEntry(ACCESS, USER, "user1", READ_WRITE),
          aclEntry(ACCESS, GROUP, READ_WRITE),
          aclEntry(ACCESS, OTHER, READ_EXECUTE));

  AclStatus.Builder aclStatusBuilder = new AclStatus.Builder();
  aclStatusBuilder.owner("testuser");
  aclStatusBuilder.group("supergroup");
  aclStatusBuilder.addEntries(aclSpec);
  aclStatusBuilder.stickyBit(false);

  Assert.assertEquals("Should be equal", aclStatusBuilder.build(),
      JsonUtil.toAclStatus(json));
}
 
Example #2
Source File: JsonDataValidator.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean isEmptySON(String json) {
    boolean isEmpty = true;
    try {
        final JsonParser parser = new ObjectMapper().getJsonFactory()
                .createJsonParser(json);
        while (parser.nextToken() != null) {
            String fieldname = parser.getCurrentName();
            if(fieldname != null){
                isEmpty = false;
                break;
            }

        }

    } catch (JsonParseException jpe) {
        System.out.println("isEmptySON: " + jpe.getMessage());
        jpe.printStackTrace();
    } catch (IOException ioe) {
        System.out.println("isEmptySON: " + ioe.getMessage());
        ioe.printStackTrace();
    }

    return isEmpty;
}
 
Example #3
Source File: JSONManifestTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * manifest_jsonのschemaの指定がない場合falseが返却されること.
 * @throws IOException IOException
 */
@SuppressWarnings("unchecked")
@Test
public void manifest_jsonのschemaの指定がない場合falseが返却されること() throws IOException {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("DefaultPath", "boxName");
    JsonParser jp = f.createJsonParser(json.toJSONString());
    ObjectMapper mapper = new ObjectMapper();
    jp.nextToken();

    JSONManifest manifest = mapper.readValue(jp, JSONManifest.class);

    assertFalse(manifest.checkSchema());
}
 
Example #4
Source File: VespaDocumentOperationTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private JsonNode setupSimpleArrayOperation(String name, String[] array, String... params) throws IOException {
    Schema schema = new Schema();
    Tuple tuple = TupleFactory.getInstance().newTuple();

    DataBag bag = new SortedDataBag(null);
    for (String s : array) {
        Tuple stringTuple = TupleFactory.getInstance().newTuple();
        stringTuple.append(s);
        bag.add(stringTuple);
    }
    addToTuple(name, DataType.BAG, bag, schema, tuple);

    VespaDocumentOperation docOp = new VespaDocumentOperation(params);
    docOp.setInputSchema(schema);
    String json = docOp.exec(tuple);

    ObjectMapper m = new ObjectMapper();
    JsonNode root = m.readTree(json);
    JsonNode fields = root.get("fields");
    return fields.get(name);
}
 
Example #5
Source File: StramWebServices.java    From Bats with Apache License 2.0 6 votes vote down vote up
@GET
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId:\\d+}/properties")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getPhysicalOperatorProperties(@PathParam("operatorId") int operatorId, @QueryParam("propertyName") String propertyName, @QueryParam("waitTime") long waitTime)
{
  init();
  if (waitTime == 0) {
    waitTime = WAIT_TIME;
  }

  Future<?> future = dagManager.getPhysicalOperatorProperty(operatorId, propertyName, waitTime);

  try {
    Object object = future.get(waitTime, TimeUnit.MILLISECONDS);
    if (object != null) {
      return new JSONObject(new ObjectMapper().writeValueAsString(object));
    }
  } catch (Exception ex) {
    LOG.warn("Caught exception", ex);
    throw new RuntimeException(ex);
  }
  return new JSONObject();
}
 
Example #6
Source File: JsonObjectMapperWriter.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public JsonObjectMapperWriter(OutputStream output, boolean prettyPrint) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(
      SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);

  // define a module
  SimpleModule module = new SimpleModule("Default Serializer",  
                                         new Version(0, 1, 1, "FINAL"));
  // add various serializers to the module
  //   add default (all-pass) serializer for all rumen specific data types
  module.addSerializer(DataType.class, new DefaultRumenSerializer());
  //   add a serializer to use object.toString() while serializing
  module.addSerializer(ID.class, new ObjectStringSerializer<ID>());
  
  // register the module with the object-mapper
  mapper.registerModule(module);

  mapper.getJsonFactory();
  writer = mapper.getJsonFactory().createJsonGenerator(
      output, JsonEncoding.UTF8);
  if (prettyPrint) {
    writer.useDefaultPrettyPrinter();
  }
}
 
Example #7
Source File: ListMetadataType.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String toString(List<T> metadataValues)
{
	try
	{
		List<String> stringValues = new ArrayList<String>();

		if (metadataValues != null && !metadataValues.isEmpty())
		{
			for (T metadataValue : metadataValues)
			{
				String stringValue = metadataConverter.toString(metadataValue);
				if (stringValue != null)
					stringValues.add(stringValue);
			}
		}
		return new ObjectMapper().writeValueAsString(stringValues);
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
}
 
Example #8
Source File: AvroInOutFormatsTest.java    From iow-hadoop-streaming with Apache License 2.0 6 votes vote down vote up
@Test
public void testAvroAsJsonFmt() throws IOException {

    AvroAsJsonOutputFormat outfmt = new AvroAsJsonOutputFormat();
    FileOutputFormat.setOutputPath(defaultConf, file2);
            RecordWriter<Text, NullWritable> writer = outfmt.getRecordWriter(file2.getFileSystem(defaultConf),
            defaultConf, fname2, new dummyReporter());

    writer.write(new Text(json), NullWritable.get());
    writer.close(null);

    FileInputFormat.setInputPaths(defaultConf, FileOutputFormat.getTaskOutputPath(defaultConf, fname2 +
        AvroOutputFormat.EXT));
    AvroAsJsonInputFormat informat = new AvroAsJsonInputFormat();
    RecordReader<Text, Text> reader = informat.getRecordReader(informat.getSplits(defaultConf, 1)[0],
            defaultConf, new dummyReporter());

    Text k = new Text();
    Text v = new Text();

    reader.next(k, v);
    ObjectMapper mapper = new ObjectMapper();
    JsonNode n0 = mapper.readTree(k.toString());
    JsonNode n1 = mapper.readTree(json);
    Assert.assertEquals("read back json", n0, n1);
}
 
Example #9
Source File: JenkinsBuildService.java    From seppb with MIT License 6 votes vote down vote up
private void retryBuild(BuildHistory buildHistory) {
	List<String> repeatBuildInstance = Lists.newArrayList();
	buildHistory.setBuildStatus(START);
	String buildParams = buildHistory.getBuildParams();
	ObjectMapper mapper = new ObjectMapper();
	try {
		List<BuildFile> buildFiles = mapper.readValue(buildParams, new TypeReference<List<BuildFile>>() {
		});
		BuildInstance buildInstance = buildInstanceDAO.findInstance(buildHistory.getInstance(), ParameterThreadLocal.getProductId());
		buildHistory.setType(buildInstance.getType());
		build(repeatBuildInstance, buildHistory, buildFilesToParamsMap(buildFiles));
	} catch (IOException e) {
		log.error("构建id为:{}的buildParams序列化失败{}", buildHistory.getId(), e);
		throw new SeppServerException(1001, "服务器异常");
	}
}
 
Example #10
Source File: JsonCreateJvmDeserializerTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeJsonCreateJvm() throws Exception {
    final InputStream in = this.getClass().getResourceAsStream("/json-create-jvm-data.json");
    final String jsonData = IOUtils.toString(in, Charset.defaultCharset());

    final ObjectMapper mapper = new ObjectMapper();

    final JsonCreateJvm jsonCreateJvm = mapper.readValue(jsonData, JsonCreateJvm.class);
    assertEquals("my-jvm", jsonCreateJvm.getJvmName());
    assertEquals("some-host", jsonCreateJvm.getHostName());
    assertEquals("jwala", jsonCreateJvm.getUserName());
    assertEquals("/manager", jsonCreateJvm.getStatusPath());
    assertEquals("1", jsonCreateJvm.getJdkMediaId());
    assertTrue(StringUtils.isNotEmpty(jsonCreateJvm.getEncryptedPassword()));
    assertNotEquals("password", jsonCreateJvm.getEncryptedPassword());
    assertEquals("8893", jsonCreateJvm.getAjpPort());
    assertEquals("8889", jsonCreateJvm.getHttpPort());
    assertEquals("8890", jsonCreateJvm.getHttpsPort());
    assertEquals("8891", jsonCreateJvm.getRedirectPort());
    assertEquals("8892", jsonCreateJvm.getShutdownPort());
    assertEquals("1", jsonCreateJvm.getGroupIds().get(0).getGroupId());
}
 
Example #11
Source File: JsonDataValidator.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean isValidJSON(String json) {
    boolean valid = false;
    try {
        final JsonParser parser = new ObjectMapper().getJsonFactory()
                .createJsonParser(json);
        while (parser.nextToken() != null) {
            String fieldname = parser.getCurrentName();
            System.out.println("fieldname: " + fieldname);
        }
        valid = true;
    } catch (JsonParseException jpe) {
        jpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return valid;
}
 
Example #12
Source File: AbstractSiteToSiteReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
public JsonRecordReader(final InputStream in, RecordSchema recordSchema) throws IOException, MalformedRecordException {
    this.recordSchema = recordSchema;
    try {
        jsonParser = new JsonFactory().createJsonParser(in);
        jsonParser.setCodec(new ObjectMapper());
        JsonToken token = jsonParser.nextToken();
        if (token == JsonToken.START_ARRAY) {
            array = true;
            token = jsonParser.nextToken();
        } else {
            array = false;
        }
        if (token == JsonToken.START_OBJECT) {
            firstJsonNode = jsonParser.readValueAsTree();
        } else {
            firstJsonNode = null;
        }
    } catch (final JsonParseException e) {
        throw new MalformedRecordException("Could not parse data as JSON", e);
    }
}
 
Example #13
Source File: OpenApiService.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public HashMap<String, Object> execute(String operation, String content) 
		throws JsonGenerationException, JsonMappingException, IOException, UserSysException
{	
	HashMap<String, Object> res = callOpenAPI(operation, content);
	
	
	//try {
		//int status = (Integer)res.get("status");
		String body = (String)res.get("body");
		ObjectMapper mapper = new ObjectMapper();
		Object json = mapper.readValue(body, Object.class);
		res.put("json", json);
	//} catch (JsonGenerationException ex) {
	//	res.put("exception", ex);
	//} catch (JsonMappingException ex) {
	//	res.put("exception", ex);
	//} catch (IOException ex) {
	//	res.put("exception", ex);
	//} catch (UserSysException ex) {
		
	//}
	
	return res;
}
 
Example #14
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public void setup(com.datatorrent.api.Context context)
{
  ObjectMapper om = new ObjectMapper();
  instanceSerializerFactory = new InstanceSerializerFactory(om.reader(), om.writer());

  curatorFramework = CuratorFrameworkFactory.builder()
          .connectionTimeoutMs(connectionTimeoutMillis)
          .retryPolicy(new RetryNTimes(connectionRetryCount, conntectionRetrySleepMillis))
          .connectString(connectionString)
          .build();
  curatorFramework.start();

  discovery = getDiscovery(curatorFramework);
  try {
    discovery.start();
  } catch (Exception ex) {
    Throwables.propagate(ex);
  }
}
 
Example #15
Source File: WebHdfsFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
    ) throws IOException {
  if (c.getContentLength() == 0) {
    return null;
  }
  final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
  if (in == null) {
    throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
  }
  try {
    final String contentType = c.getContentType();
    if (contentType != null) {
      final MediaType parsed = MediaType.valueOf(contentType);
      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
        throw new IOException("Content-Type \"" + contentType
            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
            + "\" (parsed=\"" + parsed + "\")");
      }
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.reader(Map.class).readValue(in);
  } finally {
    in.close();
  }
}
 
Example #16
Source File: TestJsonUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testToXAttrMap() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);
  XAttr xAttr1 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a1").setValue(XAttrCodec.decodeValue("0x313233")).build();
  XAttr xAttr2 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a2").setValue(XAttrCodec.decodeValue("0x313131")).build();
  List<XAttr> xAttrs = Lists.newArrayList();
  xAttrs.add(xAttr1);
  xAttrs.add(xAttr2);
  Map<String, byte[]> xAttrMap = XAttrHelper.buildXAttrMap(xAttrs);
  Map<String, byte[]> parsedXAttrMap = JsonUtil.toXAttrs(json);
  
  Assert.assertEquals(xAttrMap.size(), parsedXAttrMap.size());
  Iterator<Entry<String, byte[]>> iter = xAttrMap.entrySet().iterator();
  while(iter.hasNext()) {
    Entry<String, byte[]> entry = iter.next();
    Assert.assertArrayEquals(entry.getValue(), 
        parsedXAttrMap.get(entry.getKey()));
  }
}
 
Example #17
Source File: JsonUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public static List<String> toXAttrNames(final Map<?, ?> json)
    throws IOException {
  if (json == null) {
    return null;
  }

  final String namesInJson = (String) json.get("XAttrNames");
  ObjectReader reader = new ObjectMapper().reader(List.class);
  final List<Object> xattrs = reader.readValue(namesInJson);
  final List<String> names =
    Lists.newArrayListWithCapacity(json.keySet().size());

  for (Object xattr : xattrs) {
    names.add((String) xattr);
  }
  return names;
}
 
Example #18
Source File: StatsSnapshotTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Serialization unit test of {@link StatsSnapshot}.
 * Test if subMap and null fields are removed from serialized result.
 */
@Test
public void serializeStatsSnapshotTest() throws IOException {
  Long val = 100L;
  Map<String, StatsSnapshot> subMap = new HashMap<>();
  subMap.put("first", new StatsSnapshot(40L, null));
  subMap.put("second", new StatsSnapshot(60L, null));
  StatsSnapshot snapshot = new StatsSnapshot(val, subMap);

  String result = new ObjectMapper().writeValueAsString(snapshot);

  assertThat("Result should contain \"first\" keyword and associated entry", result, containsString("first"));
  assertThat("Result should contain \"second\" keyword and associated entry", result, containsString("second"));
  assertThat("Result should not contain \"subMap\" keyword", result, not(containsString("subMap")));
  assertThat("Result should ignore any null fields", result, not(containsString("null")));
}
 
Example #19
Source File: TaskManagerEntityMapper.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Deprecated
public <E> String serializeTask(E task) {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	String jsonString = null;
	try {
		if (task != null) jsonString = mapper.writeValueAsString(task);
	} catch (IOException e) {
		logger.error("JSON serialization exception",e);
	}
	return jsonString;
}
 
Example #20
Source File: JacksonUtils.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
public static <T> T toObject(String json, Class<T> valueType) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(json, valueType);
    } catch (IOException e) {
        logger.error(e);
    }
    return null;
}
 
Example #21
Source File: JsonSerDeser.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Create an instance bound to a specific type
 * @param classType class to marshall
 */
public JsonSerDeser(Class<T> classType) {
  Preconditions.checkArgument(classType != null, "null classType");
  this.classType = classType;
  this.mapper = new ObjectMapper();
  mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
      false);
}
 
Example #22
Source File: Attribute.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
/**
 * Produces a json from a list of attributes
 *
 * @param attributeDetails List of attributes to serialize
 * @return A string representing the json
 * @throws IOException
 */
@JsonIgnore
public static String getJsonFromAttributeList(List<Attribute> attributeDetails) throws IOException {
    ObjectMapper mapper = ObjectMapperHelper.get();
    String jsonContent;
    try {
        jsonContent = mapper.writeValueAsString(attributeDetails);
    } catch (IOException e) {
        log.error("Can't process the json file: " + e.getMessage());
        throw e;
    }
    return jsonContent;
}
 
Example #23
Source File: Criteria.java    From searchbox-core with Apache License 2.0 5 votes vote down vote up
public String createParmsMapToJson(){
	
	Map<String, Object> m = new HashMap<>();
	m.put(lua_input_parm_key, key);
	m.put(lua_input_parm_value, value);
	
	ObjectMapper objectMapper = new ObjectMapper();
	try{
		return objectMapper.writeValueAsString(m);
	}catch(Exception e){
		return null;
	}
	
}
 
Example #24
Source File: MockTask.java    From helix with Apache License 2.0 5 votes vote down vote up
public static String serializeTargetPartitionConfig(Map<String, Map<String, String>> config) {
  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.writeValueAsString(config);
  } catch (IOException e) {
    throw new HelixException(e);
  }
}
 
Example #25
Source File: RowkeyQueryAPIResponseConvertHelper.java    From Eagle with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
public static RowkeyQueryAPIResponseEntity convert(Class<? extends TaggedLogAPIEntity> clazz, RowkeyQueryAPIResponseEntity response) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, JsonGenerationException, JsonMappingException, IOException {
	if (response == null || response.getObj() == null) {
		return response;
	}		
	final Object obj = response.getObj();
	final Map<String, Method> settings = getOrCreateSetterMap(clazz);
	final Map<String, Object> map = (Map<String, Object>) obj;
	final TaggedLogAPIEntity entity = clazz.newInstance();
	for (Map.Entry<String, Object> entry : map.entrySet()) {
		final String propertyName = entry.getKey();
		Object value = entry.getValue();
		final Method method = settings.get(propertyName);
		final Type type = method.getGenericParameterTypes()[0];
		if ((type == double.class || type == Double.class || type == long.class || type == Long.class)
			&& (value.equals("NaN"))) {
			value = 0;
		}					
		
		final Class<?> parameterClass = method.getParameterTypes()[0];
		if (value instanceof Number || value instanceof String || parameterClass.isInstance(value)) {
			try {
				method.invoke(entity, value);
			}
			catch (Exception e){
				e.printStackTrace();
			}
		} else {
			ObjectMapper om = new ObjectMapper();
			String objJson = om.writeValueAsString(value);
			value = om.readValue(objJson, parameterClass);
			method.invoke(entity, value);
		}
	}
	response.setObj(entity);
	return response;
}
 
Example #26
Source File: CoincheckExchangeTest.java    From libdynticker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testParseTicker() {
	try {
		Pair pair = new Pair("BTC", "JPY");
		JsonNode node;
		node = (new ObjectMapper().readTree(new File("src/test/json/coincheck-ticker.json")));
		String lastValue = testExchange.parseTicker(node, pair);
		Assert.assertEquals("61498", lastValue);
	}
	catch(IOException e) {
		Assert.fail();
	}
}
 
Example #27
Source File: TestContainerPlacementObjectMapper.java    From samza with Apache License 2.0 5 votes vote down vote up
private void testContainerPlacementResponseMessage(ContainerPlacementResponseMessage responseMessage)
    throws IOException {
  ObjectMapper objectMapper = ContainerPlacementMessageObjectMapper.getObjectMapper();
  ContainerPlacementMessage message =
      objectMapper.readValue(objectMapper.writeValueAsString(responseMessage), ContainerPlacementMessage.class);
  assertTrue(message instanceof ContainerPlacementResponseMessage);
  ContainerPlacementResponseMessage deserializedResponse = (ContainerPlacementResponseMessage) message;
  assertEquals(responseMessage, deserializedResponse);
}
 
Example #28
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<CatalogEntryVO> parseEntryArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<CatalogEntryVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #29
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 5 votes vote down vote up
public static String ObjectToJson(Object object) throws JsonGenerationException,
    JsonMappingException, IOException {
  ObjectMapper mapper = new ObjectMapper();
  SerializationConfig serializationConfig = mapper.getSerializationConfig();
  serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true);

  StringWriter sw = new StringWriter();
  mapper.writeValue(sw, object);

  return sw.toString();
}
 
Example #30
Source File: ImportRecord.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
public int createRecords(String json, String dataSource, Long groupId)
		throws IOException, JsonParseException, JsonMappingException {
	
       int count = 0;
   	Map<Long, Long> idMapping = new HashMap<Long, Long>();
   	
   	List<?> list = new ObjectMapper().readValue(json, List.class);
       for (int i = 0; i < list.size(); i++) {
       	Object obj = list.get(i);  // Map
           Record record = new ObjectMapper().readValue(EasyUtils.obj2Json(obj), Record.class);
           Long oldId = record.getId();
           
           record.setId(null);
           if ( i == 0 ) {
               record.setParentId(groupId);
           } else {
               Long parentId = idMapping.get(record.getParentId());
               parentId = (Long) EasyUtils.checkNull(parentId, groupId);
			record.setParentId(parentId);
           }
           
           if( Record.TYPE1 == record.getType() ) {
           	count ++;
           	record.setDatasource(dataSource);
           	
           	String table = record.getTable();
               record.setTable( table.substring(table.indexOf(".") + 1) ); // 去掉表空间|schema
           }
           
           Integer status = record.getDisabled();
           recordService.createRecord(record);
           
           record.setDisabled(status);
           recordService.updateRecord(record);
           
           idMapping.put(oldId, record.getId());
       }
	return count;
}