org.yaml.snakeyaml.error.YAMLException Java Examples

The following examples show how to use org.yaml.snakeyaml.error.YAMLException. 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: Constructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #2
Source File: FormulaFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
private static Optional<Map<String, Object>> getFormulaLayoutByClusterProviderAndName(String provider,
                                                                                      String name) {
    Path layoutFile = Paths.get(METADATA_DIR_CLUSTER_PROVIDERS, provider, name + ".yml");
    try {
        if (Files.exists(layoutFile)) {
            return Optional.of((Map<String, Object>) YAML.load(new FileInputStream(layoutFile.toFile())));
        }
        else {
            return Optional.empty();
        }
    }
    catch (FileNotFoundException | YAMLException e) {
        LOG.error("Error loading layout for formula '" + name +
                "' from cluster provider '" + provider + "'", e);
        return Optional.empty();
    }
}
 
Example #3
Source File: YamlParser.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
public Map<String, Object> load(InputStream is) throws IOException {
  checkNotNull(is);
  String data = IOUtils.toString(new UnicodeReader(is));

  Map<String, Object> map;

  try {
    Yaml yaml = new Yaml(new Constructor(), new Representer(),
        new DumperOptions(), new Resolver());
    map = yaml.load(data);
  }
  catch (YAMLException e) {
    map = (Map<String, Object>) mapper.readValue(data, Map.class);
  }
  return map;
}
 
Example #4
Source File: YamlConstructor.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: YamlUtils.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
public static Node read(YamlSource source, Reader reader, ConfigurationContext context) throws IOException {
    LoaderOptions loaderOptions = new LoaderOptions();
    loaderOptions.setMaxAliasesForCollections(context.getYamlMaxAliasesForCollections());
    Composer composer = new Composer(
        new ParserImpl(new StreamReaderWithSource(source, reader)),
        new Resolver(),
        loaderOptions);
    try {
        return composer.getSingleNode();
    } catch (YAMLException e) {
        if (e.getMessage().startsWith("Number of aliases for non-scalar nodes exceeds the specified max")) {
            throw new ConfiguratorException(String.format(
                "%s%nYou can increase the maximum by setting an environment variable or property%n  ENV: %s=\"100\"%n  PROPERTY: -D%s=\"100\"",
                e.getMessage(), ConfigurationContext.CASC_YAML_MAX_ALIASES_ENV,
                ConfigurationContext.CASC_YAML_MAX_ALIASES_PROPERTY));
        }
        throw e;
    }
}
 
Example #6
Source File: Yaml.java    From Diorite with MIT License 6 votes vote down vote up
/**
 * Serialize a Java object into a YAML stream.
 *
 * @param data
 *         Java object to be serialized to YAML
 * @param output
 *         output for yaml.
 * @param comments
 *         comments node.
 */
public void toYamlWithComments(Object data, Writer output, DocumentComments comments)
{
    Serializer serializer =
            new Serializer(this.serialization, new Emitter(this.serialization, output, this.dumperOptions), this.resolver, this.dumperOptions, null);
    serializer.setComments(comments);
    try
    {
        serializer.open();
        Node node = this.representer.represent(data);
        serializer.serialize(node);
        serializer.close();
    }
    catch (IOException e)
    {
        throw new YAMLException(e);
    }
}
 
Example #7
Source File: Security1446Test.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@Issue("SECURITY-1446")
public void testExportWithEnvVar() throws Exception {
    final String message = "Hello, world! PATH=${PATH} JAVA_HOME=^${JAVA_HOME}";
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);

    DataBoundConfigurator<UsernamePasswordCredentialsImpl> configurator = new DataBoundConfigurator<>(UsernamePasswordCredentialsImpl.class);
    UsernamePasswordCredentialsImpl creds = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test",
            message, "foo", "bar");
    final CNode config = configurator.describe(creds, context);
    final Node valueNode = ConfigurationAsCode.get().toYaml(config);
    final String exported;
    try (StringWriter writer = new StringWriter()) {
        ConfigurationAsCode.serializeYamlNode(valueNode, writer);
        exported = writer.toString();
    } catch (IOException e) {
        throw new YAMLException(e);
    }

    assertThat("Message was not escaped", exported, not(containsString(message)));
    assertThat("Improper masking for PATH", exported, containsString("^${PATH}"));
    assertThat("Improper masking for JAVA_HOME", exported, containsString("^^${JAVA_HOME}"));
}
 
Example #8
Source File: SafeRepresenter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: SafeRepresenter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
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() + "'");
}
 
Example #10
Source File: IgnoreTagsExampleTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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");
        }
    }
}
 
Example #11
Source File: BaseConstructor.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@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;

}
 
Example #12
Source File: YamlConstructor.java    From Simple-YAML with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: OutdatedConfigurationPropertyUtils.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Property getProperty(Class<?> type, String name, BeanAccess bAccess) {
    if (bAccess != BeanAccess.FIELD) return super.getProperty(type, name, bAccess);
    Map<String, Property> properties = getPropertiesMap(type, bAccess);
    Property property = properties.get(Helper.toLowerCase(name));

    if (property == null) { // Check if property was missing and notify user if necessary
        if (type != UnknownConf.class)
            core.getLogger().log(WARN, "Unknown configuration property: %s @ %s", name, type.getSimpleName());
        return new OutdatedMissingProperty(name);
    }

    if (!property.isWritable()) // Throw exception from super method
        throw new YAMLException("Unable to find writable property '" + name + "' on class: " + type.getName());

    return property;
}
 
Example #14
Source File: DumperOptions.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #15
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #16
Source File: BaseConstructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
@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;

}
 
Example #17
Source File: Constructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #18
Source File: StreamReader.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #19
Source File: SafeRepresenter.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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() + "'");
}
 
Example #20
Source File: V3Reader.java    From cdep with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #21
Source File: StressProfile.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public static StressProfile load(URI file) throws IOError
{
    try
    {
        Constructor constructor = new Constructor(StressYaml.class);

        Yaml yaml = new Yaml(constructor);

        InputStream yamlStream = file.toURL().openStream();

        if (yamlStream.available() == 0)
            throw new IOException("Unable to load yaml file from: "+file);

        StressYaml profileYaml = yaml.loadAs(yamlStream, StressYaml.class);

        StressProfile profile = new StressProfile();
        profile.init(profileYaml);

        return profile;
    }
    catch (YAMLException | IOException | RequestValidationException e)
    {
        throw new IOError(e);
    }
}
 
Example #22
Source File: YamlConstructMapping.java    From Diorite with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #23
Source File: FieldProperty.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Override
public Object get(Object object) {
    try {
        return field.get(object);
    } catch (Exception e) {
        throw new YAMLException("Unable to access field " + field.getName() + " on object "
                + object + " : " + e);
    }
}
 
Example #24
Source File: ExportTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
public <T> String export(DataBoundConfigurator<T> configurator, T object) throws Exception {
    ConfigurationAsCode casc = ConfigurationAsCode.get();
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);

    final CNode config = configurator.describe(object, context);
    final Node valueNode = casc.toYaml(config);

    try (StringWriter writer = new StringWriter()) {
        ConfigurationAsCode.serializeYamlNode(valueNode, writer);
        return writer.toString();
    } catch (IOException e) {
        throw new YAMLException(e);
    }
}
 
Example #25
Source File: Yaml.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Serialize the representation tree into Events.
 *
 * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a>
 * @param data
 *            representation tree
 * @return Event list
 */
public List<Event> serialize(Node data) {
    SilentEmitter emitter = new SilentEmitter();
    Serializer serializer = new Serializer(emitter, resolver, dumperOptions, null);
    try {
        serializer.open();
        serializer.serialize(data);
        serializer.close();
    } catch (IOException e) {
        throw new YAMLException(e);
    }
    return emitter.getEvents();
}
 
Example #26
Source File: DumperOptionsTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testCreateUnknownStyle() {
    try {
        DumperOptions.ScalarStyle.createStyle(' ');
        fail("Negative indent must not be accepted.");
    } catch (YAMLException e) {
        assertEquals("Unknown scalar style character:  ", e.getMessage());
    }
}
 
Example #27
Source File: API.java    From cdep with Apache License 2.0 5 votes vote down vote up
@NotNull
private static List<String> callCDep(@NotNull GeneratorEnvironment environment) throws MalformedURLException {
  List<String> result = new ArrayList<>();
  if (PlatformUtils.isWindows()) {
    result.add("\"" + getJvmLocation() + "\"");
  } else {
    result.add(platformQuote(getJvmLocation()));
  }
  result.add("-classpath");
  File cdepLocation = ReflectionUtils.getLocation(API.class);
  String classPath = cdepLocation.getAbsolutePath().replace("\\", "/");
  if (!classPath.endsWith(".jar")) {
    String separator = PlatformUtils.isWindows() ? ";" : ":";
    // In a test environment need to include SnakeYAML since it isn't part of the unit test
    File yamlLocation = ReflectionUtils.getLocation(YAMLException.class);
    classPath = yamlLocation.getAbsolutePath().replace("\\", "/")
        + separator + classPath;
    File jansiLocation = ReflectionUtils.getLocation(AnsiConsole.class);
    classPath = jansiLocation.getAbsolutePath().replace("\\", "/")
        + separator + classPath;
  }
  result.add(platformQuote(classPath));
  result.add("io.cdep.CDep");
  result.add("--working-folder");
  result.add(platformQuote(environment.workingFolder.getAbsolutePath().replace("\\", "/")));

  return result;
}
 
Example #28
Source File: DumperOptions.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public void setIndent(int indent) {
    if (indent < Emitter.MIN_INDENT) {
        throw new YAMLException("Indent must be at least " + Emitter.MIN_INDENT);
    }
    if (indent > Emitter.MAX_INDENT) {
        throw new YAMLException("Indent must be at most " + Emitter.MAX_INDENT);
    }
    this.indent = indent;
}
 
Example #29
Source File: UnknownConfigurationConstructor.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Class<?> getClassForNode(Node node) {
    try {
        return super.getClassForNode(node);
    } catch (YAMLException e) {
        core.getLogger().log(WARN, "Unknown configuration: {} -> {}", node.getTag().getValue(),
                Throwables.getRootCause(e).getMessage());
        return UnknownConf.class;
    }
}
 
Example #30
Source File: YAMLProcessor.java    From skript-yaml with MIT License 5 votes vote down vote up
/**
 * Sets the indentation amount used when the yaml file is saved
 * 
 * @param indent
 *            an amount from 1 to 10
 */
public void setIndent(int indent) {
	try {
		Field dumperOptions = yaml.getClass().getDeclaredField("dumperOptions");
		dumperOptions.setAccessible(true);
		DumperOptions dump = (DumperOptions) dumperOptions.get(yaml);
		try {
			dump.setIndent(indent);
		} catch (YAMLException ex) {
			SkriptYaml.warn(ex.getMessage());
		}
	} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
		e.printStackTrace();
	}
}