org.codehaus.jackson.map.type.TypeFactory Java Examples

The following examples show how to use org.codehaus.jackson.map.type.TypeFactory. 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: UserManager.java    From query2report with GNU General Public License v3.0 6 votes vote down vote up
private void init(){
	logger.info("Initializing user manager from "+new File(fileName).getAbsolutePath());
    try {
    	ObjectMapper objectMapper = new ObjectMapper();
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(Set.class, User.class);
        users =  objectMapper.readValue(new File(fileName), collectionType);
    } catch (IOException e) {
    	logger.error("Unable to initialize user manager",e);
    }
	if(users == null || users.isEmpty()){
		logger.info("Adding default admin user");
		String encPassword = EncryptionUtil.encrypt("admin");
		User adminUser = new User("Administrator","admin",encPassword,"admin",DashboardConstants.HTML_GOOGLE);
		users.add(adminUser);
	}
}
 
Example #2
Source File: HttpMetricsIngestionHandler.java    From blueflood with Apache License 2.0 5 votes vote down vote up
public HttpMetricsIngestionHandler(HttpMetricsIngestionServer.Processor processor, TimeValue timeout, boolean enablePerTenantMetrics) {
    this.mapper = new ObjectMapper();
    this.typeFactory = TypeFactory.defaultInstance();
    this.timeout = timeout;
    this.processor = processor;
    this.enablePerTenantMetrics = enablePerTenantMetrics;
}
 
Example #3
Source File: ConnectionManager.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
private void init(){
	logger.info("Initializing connection manager from "+new File(fileName).getAbsolutePath());
    try {
    	ObjectMapper objectMapper = new ObjectMapper();
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(Set.class, ConnectionParams.class);
        connParams =  objectMapper.readValue(new File(fileName), collectionType);
    } catch (IOException e) {
    	logger.error("Unable to initialize connection manager",e);
    }
}
 
Example #4
Source File: WorkflowAccessor.java    From helix with Apache License 2.0 5 votes vote down vote up
private Map<String, JobConfig.Builder> getJobConfigs(ArrayNode root)
    throws HelixException, IOException {
  Map<String, JobConfig.Builder> jobConfigsMap = new HashMap<>();
  for (Iterator<JsonNode> it = root.getElements(); it.hasNext(); ) {
    JsonNode job = it.next();
    ZNRecord record = null;

    try {
      record = toZNRecord(job.toString());
    } catch (IOException e) {
      // Ignore the parse since it could be just simple fields
    }

    if (record == null || record.getSimpleFields().isEmpty()) {
      Map<String, String> cfgMap = OBJECT_MAPPER.readValue(job.toString(),
          TypeFactory.defaultInstance()
              .constructMapType(HashMap.class, String.class, String.class));
      jobConfigsMap
          .put(job.get(Properties.id.name()).getTextValue(), JobAccessor.getJobConfig(cfgMap));
    } else {
      jobConfigsMap
          .put(job.get(Properties.id.name()).getTextValue(), JobAccessor.getJobConfig(record));
    }
  }

  return jobConfigsMap;
}
 
Example #5
Source File: KafkaCheckpoint.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public static KafkaCheckpoint deserialize(InputStream inputStream)
    throws IOException {
  TypeFactory typeFactory = _mapper.getTypeFactory();
  MapType mapType = typeFactory.constructMapType(HashMap.class, Integer.class, Long.class);
  HashMap<Integer, Long> checkpoint = _mapper.readValue(inputStream, mapType);
  return new KafkaCheckpoint(checkpoint);
}
 
Example #6
Source File: JSONUtils.java    From TestRailSDK with MIT License 5 votes vote down vote up
/**
 * Returns a list of objects of the specified type. If you send "false" in the 3rd parameter, it will be 
 * forgiving of JSON properties that are not defined or inaccessible in the specified jsonObjectClass
 * @param jsonObjectClass The Class you wish to map the json to
 * @param json The JSON you wish to map to the given Class
 * @param failOnUnknownProperties Whether or not to throw an exception if an unknown JSON attribute is encountered
 * @return An instance of the given Class, based on the attributes of the given JSON
 */
public static <T> List<T> getMappedJsonObjectList(Class<T> jsonObjectClass, String json, boolean failOnUnknownProperties) {
    List<T> list;
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties);
    
    TypeFactory t = TypeFactory.defaultInstance();
    try {
        list = mapper.readValue(json, t.constructCollectionType(ArrayList.class, jsonObjectClass));
        return list;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    throw new RuntimeException("Could not process JSON");
}
 
Example #7
Source File: JSONUtils.java    From TestRailSDK with MIT License 5 votes vote down vote up
/**
 * Takes a JSON string and attempts to "map" it to the given class. It assumes the JSON 
 * string is valid, and that it maps to the object you've indicated. If you want to run outside of "strict" mode,
 * pass false for the failOnUnknownProperties flag
 * @param jsonObjectClass The Class you wish to map the contents to
 * @param json The JSON you wish to map to the given Class
 * @param failOnUnknownProperties Whether or not to throw an exception if an unknown JSON attribute is encountered
 * @return An instance of the given Class, based on the attributes of the given JSON
 */
public static <T> T getMappedJsonObject( Class<T> jsonObjectClass, String json, boolean failOnUnknownProperties ) {
    TypeFactory t = TypeFactory.defaultInstance();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure( DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties );

    T mappedObject;
    try {
        mappedObject = mapper.readValue( json, t.constructType( jsonObjectClass ) );
    } catch ( Exception e ) {
        throw new RuntimeException( "Could not instantiate object of class [" + jsonObjectClass.getName()+ "]: " + e );
    }
    return mappedObject;
}
 
Example #8
Source File: MetricRestServlet.java    From realtime-analytics with GNU General Public License v2.0 5 votes vote down vote up
public MetricRestServlet(MetricsService service) {
    super();
    metricService = service;
    stats = new ServletStats();
    counterResultWriter = new ObjectMapper().typedWriter(TypeFactory.collectionType(List.class, Counter.class));
    metricResultWriter = new ObjectMapper().typedWriter(TypeFactory.collectionType(List.class, RawNumericMetric.class));
}
 
Example #9
Source File: JsonUtil.java    From tac2015-event-detection with GNU General Public License v3.0 5 votes vote down vote up
public static <T> ArrayList<T> toList(JsonNode jsonNode, final Class<T> type) {
	try {
		return om.readValue(jsonNode, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, type));
	} catch (IOException e) {
		return null;
	}
}
 
Example #10
Source File: JsonUtil.java    From tac2015-event-detection with GNU General Public License v3.0 5 votes vote down vote up
public static <T> ArrayList<T> toList(String jsonString, final Class<T> type) {
	try {
		return om.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, type));
	} catch (IOException e) {
		return null;
	}
}
 
Example #11
Source File: ReportManager.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
private void init(String userName) {
	String dirName = DashboardConstants.PUBLIC_REPORT_DIR;
	if(!userName.equalsIgnoreCase(DashboardConstants.PUBLIC_USER))
		dirName = DashboardConstants.PRIVATE_REPORT_DIR+userName;
	logger.debug("Initializing report manager for user "+userName+" from "+new File(dirName).getAbsolutePath());
	Map<String,Report> reportMap = new LinkedHashMap<String,Report>();
	File dir = new File(dirName);
	dir.mkdirs();
	String reportFiles[] = dir.list();
	if(reportFiles == null || reportFiles.length==0){
		logger.warn("Got 0 reports for user "+userName);
		return;
	}
	logger.debug("Got "+reportFiles.length+" reports for user "+userName);
	for(String reportFile : reportFiles){
		File f = new File(reportFile);
		if(f.isDirectory() || reportFile.equalsIgnoreCase("schedule"))
			continue;
	    try {
	    	File fn = new File(dir.getAbsolutePath()+File.separatorChar+reportFile);
	    	logger.info("Loading report template from file '"+fn.getAbsolutePath()+"'");
	    	ObjectMapper objectMapper = new ObjectMapper();
	        TypeFactory typeFactory = objectMapper.getTypeFactory();
	        CollectionType collectionType = typeFactory.constructCollectionType(Set.class, Report.class);
	        Set<Report> reports =  objectMapper.readValue(fn, collectionType);
	        for (Report report : reports) 
	        	reportMap.put(report.getTitle(), report);
	    } catch (IOException e) {
	    	logger.error("Error while loading report from template "+dir.getAbsoluteFile(),e);
	    }
	}
	userReportMap.put(userName, reportMap);
}
 
Example #12
Source File: DriverManager.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
private void init(){
	logger.info("Initializing driver manager from "+new File(fileName).getAbsolutePath());
    try {
    	ObjectMapper objectMapper = new ObjectMapper();
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(Set.class, DriverParams.class);
        driverParams =  objectMapper.readValue(new File(fileName), collectionType);
    } catch (IOException e) {
    	logger.error("Unable to initialize driver manager",e);
    }
}
 
Example #13
Source File: GenericServiceAPIResponseEntityDeserializer.java    From Eagle with Apache License 2.0 4 votes vote down vote up
@Override
public GenericServiceAPIResponseEntity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    GenericServiceAPIResponseEntity entity = new GenericServiceAPIResponseEntity();
    ObjectCodec objectCodec = jp.getCodec();

    JsonNode rootNode = jp.getCodec().readTree(jp);
    if(rootNode.isObject()){
        Iterator<Map.Entry<String,JsonNode>> fields = rootNode.getFields();
        JsonNode objNode = null;
        while(fields.hasNext()){
            Map.Entry<String,JsonNode> field = fields.next();
            if (META_FIELD.equals(field.getKey()) && field.getValue() != null)
                entity.setMeta(objectCodec.readValue(field.getValue().traverse(), Map.class));
            else if(SUCCESS_FIELD.equals(field.getKey()) && field.getValue() != null){
                entity.setSuccess(field.getValue().getValueAsBoolean(false));
            }else if(EXCEPTION_FIELD.equals(field.getKey()) && field.getValue() != null){
                entity.setException(field.getValue().getTextValue());
            }else if(TYPE_FIELD.endsWith(field.getKey())  && field.getValue() != null){
                try {
                    entity.setType(Class.forName(field.getValue().getTextValue()));
                } catch (ClassNotFoundException e) {
                    throw new IOException(e);
                }
            }else if(OBJ_FIELD.equals(field.getKey()) && field.getValue() != null){
                objNode = field.getValue();
            }
        }

        if(objNode!=null) {
            JavaType collectionType=null;
            if (entity.getType() != null) {
                collectionType = TypeFactory.defaultInstance().constructCollectionType(LinkedList.class, entity.getType());
            }else{
                collectionType = TypeFactory.defaultInstance().constructCollectionType(LinkedList.class, Map.class);
            }
            List obj = objectCodec.readValue(objNode.traverse(), collectionType);
            entity.setObj(obj);
        }
    }else{
        throw new IOException("root node is not object");
    }
    return entity;
}
 
Example #14
Source File: CitationHelperAction.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected Map<String, Object> dragAndDrop(ParameterParser params, SessionState state) {

		String message = null;
		String errorMessage = null;
		Map<String, Object> results = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		List<CitationCollectionOrder> citationCollectionOrders;

		try {
			String citationCollectionId = params.getString("citationCollectionId");
			String nestedCitations = params.getString("data");
			if (nestedCitations!=null){

				// Java has a bug where it throws a stackoverflow error when pattern matching very long strings
				// http://bugs.java.com/view_bug.do?bug_id=5050507
				// For very big lists, we just split the string
				if (nestedCitations.length()>20000){
					String[] parts = nestedCitations.split("\"sectiontype\"");
					nestedCitations = "";
					for (String part : parts) {
						part = part.replaceAll("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)", "") + "\"sectiontype\"";  // replace whitespace (except between quotation marks) so can strip extra JSON arrays //  (it would be much better just to find a way of parsing the JSON without this string manipulation)
						nestedCitations = nestedCitations + part;
					}
				}
				else {
					nestedCitations = nestedCitations.replaceAll("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)", "");
				}

				nestedCitations = nestedCitations.replaceAll("\'", "&apos;"); // escape single quotes so they can be used in attributes

				// remove extra parentheses in json
				// needed because of the extra ol's for accordion effect
				nestedCitations = nestedCitations
						.replaceAll(",\"children\":\\[\\[\\]\\]", "")
						.replaceAll(",\"children\":\\[\\[\\],\\[\\]\\]", "")
						.replaceAll(",\\{\"children\":\\[\\[\\]\\]\\}", "")
						.replaceAll(",\"children\":\\[\\[\\],", ",\"children\":[")
						.replaceAll(",\"children\":\\[\\[", ",\"children\":[")
						.replaceAll(",\\{\"children\":\\[\\[", ",{\"children\":[")
						.replaceAll("\\{\"children\":\\[\\[", "{\"children\":[")
						.replaceAll("\\}\\],\\[\\{\"section", "},{\"section")
						.replaceAll("\\}\\]\\]", "}]")
						.replaceAll("\\}\\],\\[\\]\\]", "}]")
						.replaceAll("\\}\\],\\[\\{", "},{");

				citationCollectionOrders = mapper.readValue(nestedCitations,
						TypeFactory.collectionType(List.class, CitationCollectionOrder.class));

				CitationCollection collection = getCitationCollection(state, false);
				errorMessage = getCitationValidator().getDragAndDropErrorMessage(citationCollectionOrders, collection);
				if (errorMessage==null){
					getCitationService().save(citationCollectionOrders, citationCollectionId);
					message = rb.getString("resource.updated");
					state.setAttribute(STATE_CITATION_COLLECTION, null);
					log.debug("Reading list with collection id: {} successfully updated. Drag and drop successful", collection.getId());
				}
				else {
					message = errorMessage;
					log.warn("Invalid citation list with collection id: {} in dragAndDrop(). {}", collection.getId(), errorMessage);
				}
			}
		}
		catch (Exception e){
			message = e.getMessage();
			log.warn("Exception in dragandDrop() {}", e);
		}
		if(errorMessage==null && message != null && ! message.trim().equals("")) {
			results.put("message", message);
		}
		else {
			results.put("Error: ", new String[]{errorMessage});
		}
		return results;
	}
 
Example #15
Source File: GenericEntityServiceResource.java    From Eagle with Apache License 2.0 4 votes vote down vote up
private List<String> unmarshalAsStringlist(InputStream inputStream) throws IllegalAccessException, InstantiationException, IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(inputStream, TypeFactory.defaultInstance().constructCollectionType(LinkedList.class, String.class));
}
 
Example #16
Source File: GenericEntityServiceResource.java    From Eagle with Apache License 2.0 4 votes vote down vote up
private List<? extends TaggedLogAPIEntity> unmarshalEntitiesByServie(InputStream inputStream,EntityDefinition entityDefinition) throws IllegalAccessException, InstantiationException, IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(inputStream, TypeFactory.defaultInstance().constructCollectionType(LinkedList.class, entityDefinition.getEntityClass()));
}
 
Example #17
Source File: CitationHelperAction.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected Map<String, Object> dragAndDrop(ParameterParser params, SessionState state) {

		String message = null;
		String errorMessage = null;
		Map<String, Object> results = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		List<CitationCollectionOrder> citationCollectionOrders;

		try {
			String citationCollectionId = params.getString("citationCollectionId");
			String nestedCitations = params.getString("data");
			if (nestedCitations!=null){

				// Java has a bug where it throws a stackoverflow error when pattern matching very long strings
				// http://bugs.java.com/view_bug.do?bug_id=5050507
				// For very big lists, we just split the string
				if (nestedCitations.length()>20000){
					String[] parts = nestedCitations.split("\"sectiontype\"");
					nestedCitations = "";
					for (String part : parts) {
						part = part.replaceAll("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)", "") + "\"sectiontype\"";  // replace whitespace (except between quotation marks) so can strip extra JSON arrays //  (it would be much better just to find a way of parsing the JSON without this string manipulation)
						nestedCitations = nestedCitations + part;
					}
				}
				else {
					nestedCitations = nestedCitations.replaceAll("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)", "");
				}

				nestedCitations = nestedCitations.replaceAll("\'", "&apos;"); // escape single quotes so they can be used in attributes

				// remove extra parentheses in json
				// needed because of the extra ol's for accordion effect
				nestedCitations = nestedCitations
						.replaceAll(",\"children\":\\[\\[\\]\\]", "")
						.replaceAll(",\"children\":\\[\\[\\],\\[\\]\\]", "")
						.replaceAll(",\\{\"children\":\\[\\[\\]\\]\\}", "")
						.replaceAll(",\"children\":\\[\\[\\],", ",\"children\":[")
						.replaceAll(",\"children\":\\[\\[", ",\"children\":[")
						.replaceAll(",\\{\"children\":\\[\\[", ",{\"children\":[")
						.replaceAll("\\{\"children\":\\[\\[", "{\"children\":[")
						.replaceAll("\\}\\],\\[\\{\"section", "},{\"section")
						.replaceAll("\\}\\]\\]", "}]")
						.replaceAll("\\}\\],\\[\\]\\]", "}]")
						.replaceAll("\\}\\],\\[\\{", "},{");

				citationCollectionOrders = mapper.readValue(nestedCitations,
						TypeFactory.collectionType(List.class, CitationCollectionOrder.class));

				CitationCollection collection = getCitationCollection(state, false);
				errorMessage = getCitationValidator().getDragAndDropErrorMessage(citationCollectionOrders, collection);
				if (errorMessage==null){
					getCitationService().save(citationCollectionOrders, citationCollectionId);
					message = rb.getString("resource.updated");
					state.setAttribute(STATE_CITATION_COLLECTION, null);
					log.debug("Reading list with collection id: {} successfully updated. Drag and drop successful", collection.getId());
				}
				else {
					message = errorMessage;
					log.warn("Invalid citation list with collection id: {} in dragAndDrop(). {}", collection.getId(), errorMessage);
				}
			}
		}
		catch (Exception e){
			message = e.getMessage();
			log.warn("Exception in dragandDrop() {}", e);
		}
		if(errorMessage==null && message != null && ! message.trim().equals("")) {
			results.put("message", message);
		}
		else {
			results.put("Error: ", new String[]{errorMessage});
		}
		return results;
	}
 
Example #18
Source File: BackportedObjectReader.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
public static BackportedObjectReader create(ObjectMapper mapper, Class<?> type) {
    return new BackportedObjectReader(mapper, TypeFactory.type(type), null);
}
 
Example #19
Source File: TestClusterMaintenanceMode.java    From helix with Apache License 2.0 2 votes vote down vote up
/**
 * Convert a String representation of a Map into a Map object for verification purposes.
 * @param value
 * @return
 */
private static Map<String, String> convertStringToMap(String value) throws IOException {
  return new ObjectMapper().readValue(value,
      TypeFactory.mapType(HashMap.class, String.class, String.class));
}