@NotNull public static io.cdep.cdep.yml.cdepmanifest.CDepManifestYml convertStringToManifest(@NotNull String content) { Yaml yaml = new Yaml(new Constructor(io.cdep.cdep.yml.cdepmanifest.v3.CDepManifestYml.class)); io.cdep.cdep.yml.cdepmanifest.CDepManifestYml manifest; try { CDepManifestYml prior = (CDepManifestYml) yaml.load( new ByteArrayInputStream(content.getBytes(StandardCharsets .UTF_8))); prior.sourceVersion = CDepManifestYmlVersion.v3; manifest = convert(prior); require(manifest.sourceVersion == CDepManifestYmlVersion.v3); } catch (YAMLException e) { manifest = convert(V2Reader.convertStringToManifest(content)); } return manifest; }
public Node representData(Object data) { Tag tag = Tag.STR; Character style = null; String value = data.toString(); if (StreamReader.NON_PRINTABLE.matcher(value).find()) { tag = Tag.BINARY; char[] binary; try { binary = Base64Coder.encode(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new YAMLException(e); } value = String.valueOf(binary); style = '|'; } // if no other scalar style is explicitly set, use literal style for // multiline scalars if (defaultScalarStyle == null && MULTILINE_PATTERN.matcher(value).find()) { style = '|'; } return representScalar(tag, value, style); }
public Node representData(Object data) { Class<?> type = data.getClass().getComponentType(); if (byte.class == type) { return representSequence(Tag.SEQ, asByteList(data), null); } else if (short.class == type) { return representSequence(Tag.SEQ, asShortList(data), null); } else if (int.class == type) { return representSequence(Tag.SEQ, asIntList(data), null); } else if (long.class == type) { return representSequence(Tag.SEQ, asLongList(data), null); } else if (float.class == type) { return representSequence(Tag.SEQ, asFloatList(data), null); } else if (double.class == type) { return representSequence(Tag.SEQ, asDoubleList(data), null); } else if (char.class == type) { return representSequence(Tag.SEQ, asCharList(data), null); } else if (boolean.class == type) { return representSequence(Tag.SEQ, asBooleanList(data), null); } throw new YAMLException("Unexpected primitive '" + type.getCanonicalName() + "'"); }
private void update() { if (!this.eof) { this.buffer = buffer.substring(this.pointer); this.pointer = 0; try { int converted = this.stream.read(data); if (converted > 0) { /* * Let's create StringBuilder manually. Anyway str1 + str2 * generates new StringBuilder(str1).append(str2).toSting() * Giving correct capacity to the constructor prevents * unnecessary operations in appends. */ checkPrintable(data, 0, converted); this.buffer = new StringBuilder(buffer.length() + converted).append(buffer) .append(data, 0, converted).toString(); } else { this.eof = true; this.buffer += "\0"; } } catch (IOException ioe) { throw new YAMLException(ioe); } } }
/** * Provide the name of the property which is used when the entries form a * sequence. The property must be a List. * */ protected String getSequencePropertyName(Class<?> bean) { Set<Property> properties = getPropertyUtils().getProperties(bean); for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) { Property property = iterator.next(); if (!List.class.isAssignableFrom(property.getType())) { iterator.remove(); } } if (properties.size() == 0) { throw new YAMLException("No list property found in " + bean); } else if (properties.size() > 1) { throw new YAMLException( "Many list properties found in " + bean + "; Please override getSequencePropertyName() to specify which property to use."); } return properties.iterator().next().getName(); }
protected Object createEmptyJavaBean(MappingNode node) { try { /** * Using only default constructor. Everything else will be * initialized on 2nd step. If we do here some partial * initialization, how do we then track what need to be done on * 2nd step? I think it is better to get only object here (to * have it as reference for recursion) and do all other thing on * 2nd step. */ java.lang.reflect.Constructor<?> c = node.getType().getDeclaredConstructor(); c.setAccessible(true); return c.newInstance(); } catch (Exception e) { throw new YAMLException(e); } }
protected Class<?> getClassForNode(Node node) { Class<? extends Object> classForTag = typeTags.get(node.getTag()); if (classForTag == null) { String name = node.getTag().getClassName(); Class<?> cl; try { cl = getClassForName(name); } catch (ClassNotFoundException e) { throw new YAMLException("Class not found: " + name); } typeTags.put(node.getTag(), cl); return cl; } else { return classForTag; } }
@SuppressWarnings("unchecked") protected List<? extends Object> constructSequence(SequenceNode node) { List<Object> result; if (List.class.isAssignableFrom(node.getType()) && !node.getType().isInterface()) { // the root class may be defined (Vector for instance) try { result = (List<Object>) node.getType().newInstance(); } catch (Exception e) { throw new YAMLException(e); } } else { result = createDefaultList(node.getValue().size()); } constructSequenceStep2(node, result); return result; }
@SuppressWarnings("unchecked") protected Set<? extends Object> constructSet(SequenceNode node) { Set<Object> result; if (!node.getType().isInterface()) { // the root class may be defined try { result = (Set<Object>) node.getType().newInstance(); } catch (Exception e) { throw new YAMLException(e); } } else { result = createDefaultSet(node.getValue().size()); } constructSequenceStep2(node, result); return result; }
public static ScalarStyle createStyle(Character style) { if (style == null) { return PLAIN; } else { switch (style) { case '"': return DOUBLE_QUOTED; case '\'': return SINGLE_QUOTED; case '|': return LITERAL; case '>': return FOLDED; default: throw new YAMLException("Unknown scalar style character: " + style); } } }
/** * Provide the name of the property which is used when the entries form a * sequence. The property must be a List. * @param bean the class to provide exactly one List property * @return name of the List property * @throws IntrospectionException if the bean cannot be introspected */ protected String getSequencePropertyName(Class<?> bean) throws IntrospectionException { Set<Property> properties = getPropertyUtils().getProperties(bean); for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) { Property property = iterator.next(); if (!List.class.isAssignableFrom(property.getType())) { iterator.remove(); } } if (properties.size() == 0) { throw new YAMLException("No list property found in " + bean); } else if (properties.size() > 1) { throw new YAMLException( "Many list properties found in " + bean + "; Please override getSequencePropertyName() to specify which property to use."); } return properties.iterator().next().getName(); }
/** * Create Yaml instance. It is safe to create a few instances and use them * in different Threads. * * @param constructor * BaseConstructor to construct incoming documents * @param representer * Representer to emit outgoing objects * @param dumperOptions * DumperOptions to configure outgoing objects * @param loadingConfig * LoadingConfig to control load behavior * @param resolver * Resolver to detect implicit type */ public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions, LoaderOptions loadingConfig, Resolver resolver) { if (!constructor.isExplicitPropertyUtils()) { constructor.setPropertyUtils(representer.getPropertyUtils()); } else if (!representer.isExplicitPropertyUtils()) { representer.setPropertyUtils(constructor.getPropertyUtils()); } this.constructor = constructor; this.constructor.setAllowDuplicateKeys(loadingConfig.isAllowDuplicateKeys()); if (dumperOptions.getIndent() <= dumperOptions.getIndicatorIndent()) { throw new YAMLException("Indicator indent must be smaller then indent."); } representer.setDefaultFlowStyle(dumperOptions.getDefaultFlowStyle()); representer.setDefaultScalarStyle(dumperOptions.getDefaultScalarStyle()); representer.getPropertyUtils() .setAllowReadOnlyProperties(dumperOptions.isAllowReadOnlyProperties()); representer.setTimeZone(dumperOptions.getTimeZone()); this.representer = representer; this.dumperOptions = dumperOptions; this.loadingConfig = loadingConfig; this.resolver = resolver; this.name = "Yaml:" + System.identityHashCode(this); }
@Override public Object construct(Node node) { if (node.isTwoStepsConstruction()) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } Map<?, ?> raw = (Map<?, ?>) super.construct(node); if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { Map<String, Object> typed = new LinkedHashMap<String, Object>(raw.size()); for (Map.Entry<?, ?> entry : raw.entrySet()) { typed.put(entry.getKey().toString(), entry.getValue()); } try { return ConfigurationSerialization.deserializeObject(typed); } catch (IllegalArgumentException ex) { throw new YAMLException("Could not deserialize object", ex); } } return raw; }
@Override public Object construct( Node node ) { if ( node.isTwoStepsConstruction() ) { throw new YAMLException( "Unexpected referential mapping structure. Node: " + node ); } Map<?, ?> raw = (Map<?, ?>) super.construct( node ); if ( raw.containsKey( ConfigurationSerialization.SERIALIZED_TYPE_KEY ) ) { Map<String, Object> typed = new LinkedHashMap<String, Object>( raw.size() ); for ( Map.Entry<?, ?> entry : raw.entrySet() ) { typed.put( entry.getKey().toString(), entry.getValue() ); } try { return ConfigurationSerialization.deserializeObject( typed ); } catch ( IllegalArgumentException ex ) { throw new YAMLException( "Could not deserialize object", ex ); } } return raw; }
protected Object createEmptyJavaBean(MappingNode node) { try { /* * Using only default constructor. Everything else will be * initialized on 2nd step. If we do here some partial * initialization, how do we then track what need to be done on * 2nd step? I think it is better to get only object here (to * have it as reference for recursion) and do all other thing on * 2nd step. */ java.lang.reflect.Constructor<?> c = node.getType().getDeclaredConstructor(); c.setAccessible(true); return c.newInstance(); } catch (Exception e) { throw new YAMLException(e); } }
/** * Serialize the representation tree into Events. * * @param data * representation tree * * @return Event list * * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> */ public List<Event> serialize(Node data) { YamlSilentEmitter emitter = new YamlSilentEmitter(); Serializer serializer = new Serializer(this.serialization, emitter, this.resolver, this.dumperOptions, null); try { serializer.open(); serializer.serialize(data); serializer.close(); } catch (IOException e) { throw new YAMLException(e); } return emitter.getEvents(); }
@Override @SuppressWarnings("unchecked") public void construct2ndStep(Node node, Object object) { SequenceNode snode = (SequenceNode) node; if (List.class.isAssignableFrom(node.getType())) { List<Object> list = (List<Object>) object; this.yamlConstructor.constructSequenceStep2(snode, list); } else if (node.getType().isArray()) { this.yamlConstructor.constructArrayStep2(snode, object); } else { throw new YAMLException("Immutable objects cannot be recursive."); } }
public Object construct(Node node) { if (node.getTag().startsWith("!KnownTag")) { return original.construct(node); } else { switch (node.getNodeId()) { case scalar: return yamlConstructors.get(Tag.STR).construct(node); case sequence: return yamlConstructors.get(Tag.SEQ).construct(node); case mapping: return yamlConstructors.get(Tag.MAP).construct(node); default: throw new YAMLException("Unexpected node"); } } }
public void testInvalidConstructors() { // Loading a character as any primitive other than 'char' is a // NumberFormatException tryInvalid(pkg + ".ByteArr [ [ 'a' ] ]", NumberFormatException.class); tryInvalid(pkg + ".ShortArr [ [ 'a' ] ]", NumberFormatException.class); tryInvalid(pkg + ".IntArr [ [ 'a' ] ]", NumberFormatException.class); tryInvalid(pkg + ".LongArr [ [ 'a' ] ]", NumberFormatException.class); tryInvalid(pkg + ".FloatArr [ [ 'a' ] ]", NumberFormatException.class); tryInvalid(pkg + ".DoubleArr [ [ 'a' ] ]", NumberFormatException.class); // Exception: because of how boolean construction works, constructing a // boolean from 'a' // results in null. tryInvalid(pkg + ".BooleanArr [ [ 'a' ] ]", NullPointerException.class); // Loading a floating-point number as a character is a YAMLException tryInvalid(pkg + ".CharArr [ [ 1.2 ] ]", YAMLException.class); // Loading a String as a Character is a YAMLException tryInvalid(pkg + ".CharArr [ [ 'abcd' ] ]", YAMLException.class); }
@Override public Object load(Reader yaml) { try { int ch = yaml.read(); StringBuilder buffer = new StringBuilder(); while (ch != -1) { buffer.append((char) ch); ch = yaml.read(); } Composer composer = new Composer(new CanonicalParser(buffer.toString()), resolver); constructor.setComposer(composer); return constructor.getSingleData(Object.class); } catch (IOException e) { throw new YAMLException(e); } }
Map<String, Object> readYamlFile(String yamlfile) throws FileNotFoundException { File file = new File(yamlfile); if (file.exists()) { InputStream input = new FileInputStream(file); Yaml yaml = new Yaml(); Object data; try { data = yaml.load(input); } catch (YAMLException ye) { throw new PivioYamlParserException("Data in " + yamlfile + " is not valid: "+ye.getMessage()); } if (data instanceof Map) { return makeLowerCaseKeys((Map<String, Object>) data); } else { throw new PivioYamlParserException("Data in " + yamlfile + " is not valid."); } } else { throw new FileNotFoundException("Could not find " + yamlfile + "."); } }
@Override public Object construct(Node node) { if (node.isTwoStepsConstruction()) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } Map<?, ?> raw = (Map<?, ?>) construct1(node); if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { Map<String, Object> typed = new LinkedHashMap<String, Object>(raw.size()); for (Map.Entry<?, ?> entry : raw.entrySet()) { typed.put(entry.getKey().toString(), entry.getValue()); } try { return ConfigurationSerialization.deserializeObject(typed); } catch (IllegalArgumentException ex) { throw new YAMLException("Could not deserialize object", ex); } } return raw; }