I am getting Exception in thread "main" org.yaml.snakeyaml.error.YAMLException: java.io.IOException: Stream closed when reading yaml file in my code:
Below is my project structure:
-rc
- main
- java
- MyMainClass
- resources
- application.yaml
Here is the sample code:
public class LoadYaml {
private static final Logger LOGGER = LoggerFactory.getLogger(LoadYaml.class);
public void loadYaml() {
Yaml yaml = new Yaml(new Constructor(Config.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("resources/application.yaml");
Config config = yaml.load(inputStream);
LOGGER.info(config.toString());
}
Below is my custom class for yaml:
package org.finra.dapi.parttioncleanup;
import java.util.List;
public class Config {
private String url;
private String userName;
private String pwsKey;
private List<Tables> tables;
....getters and setters
Error stack:
Exception in thread "main" org.yaml.snakeyaml.error.YAMLException: java.io.IOException: Stream closed
at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218)
at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:176)
at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:171)
at org.yaml.snakeyaml.reader.StreamReader.peek(StreamReader.java:126)
at org.yaml.snakeyaml.scanner.ScannerImpl.scanToNextToken(ScannerImpl.java:1177)
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:287)
at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:227)
at org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:195)
at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158)
at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:148)
at org.yaml.snakeyaml.composer.Composer.getSingleNode(Composer.java:107)
at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:139)
at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:524)
at org.yaml.snakeyaml.Yaml.load(Yaml.java:452)
at org.finra.dapi.parttioncleanup.LoadYaml.loadYaml(LoadYaml.java:23)
at org.finra.dapi.parttioncleanup.LambdaHandler.main(LambdaHandler.java:25)
Caused by: java.io.IOException: Stream closed
at java.io.PushbackInputStream.ensureOpen(PushbackInputStream.java:74)
at java.io.PushbackInputStream.read(PushbackInputStream.java:166)
at org.yaml.snakeyaml.reader.UnicodeReader.init(UnicodeReader.java:92)
at org.yaml.snakeyaml.reader.UnicodeReader.read(UnicodeReader.java:124)
at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:183)
... 15 more
Any help would be appreciated, thank you
Related
I have a class with a function as follows
`
private static Path compileNamedModuleTest() throws IOException {
Path base = Paths.get(".", "named");
Path src = base.resolve("src");
Path classes = base.resolve("classes");
ModuleInfoMaker maker = new ModuleInfoMaker(src);
maker.writeJavaFiles("test",
"module test {}",
"package test; public sealed interface Base permits test.a.ImplA1, test.a.ImplA2, test.b.ImplB, test.c.ImplC {}",
"package test.a; public final class ImplA1 implements test.Base {}",
"package test.a; public final class ImplA2 implements test.Base {}",
"package test.b; public final class ImplB implements test.Base {}",
"package test.c; public final class ImplC implements test.Base {}"
);
System.out.println("Default Charset: "
+ Charset.defaultCharset());
if (!CompilerUtils.compile(src, classes.resolve("test"), "--enable-preview", "-source", System.getProperty("java.specification.version"))) {
throw new AssertionError("Compilation didn't succeed!");
}
Files.delete(classes.resolve("test").resolve("test").resolve("c").resolve("ImplC.class"));
return classes;
}
`
and WriteJavaFiles function as
/**
* Create java source files of the given module
*/
public void writeJavaFiles(String module, String moduleInfoJava, String... contents)
throws IOException
{
Path msrc = dir.resolve(module);
new JavaSource(moduleInfoJava).write(msrc);
for (String c : contents) {
new JavaSource(c).write(msrc);
}
}
I am getting error as Error:
Java files created during execution have encoding issues due to which
compilation fails.
./named/src/test/test/a/ImplA1.java:1: error: illegal character: '\u009b'
/named/src/test/test/a/ImplA2.java:1: error: illegal character: '\u0080'
Which I believe is an encoding issue and need to add charset.defaultCharset() somewhere. But I am unsure where to put it?
JavaSource class
static class JavaSource {
final String source;
JavaSource(String source) {
this.source = source;
}
/**
* Writes the source code to a file in a specified directory.
* #param dir the directory
* #throws IOException if there is a problem writing the file
*/
public void write(Path dir) throws IOException {
Path file = dir.resolve(getJavaFileNameFromSource(source));
Files.createDirectories(file.getParent());
try (BufferedWriter out = Files.newBufferedWriter(file)) {
out.write(source.replace("\n", System.lineSeparator()));
}
}
I tried adding Charset as argument in WriteJavaFiles but did not help.
I am trying to create my first Spring app. It is showing the following error:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:73)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:61)
at com.spring1.FirstSpring1.main(FirstSpring1.java:20)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
... 4 more
GetterSetter.java
package com.spring1;
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public void displayInfo()
{
System.out.println("hello "+name);
}
FirstSpring1.java
package com.spring1;
public static void main(String[] args)
{
GetterSetter gt=new GetterSetter();
gt.setName("Google");
gt.displayInfo();
Resource resource = new ClassPathResource("applicationContext");
BeanFactory factory = new XmlBeanFactory(resource);
GetterSetter gt1 = (GetterSetter)factory.getBean("name1");
gt1.displayInfo();
}
The XML file is in the src folder.
Instead of:
Resource resource = new ClassPathResource("applicationContext");
Use:
Resource resource = new ClassPathResource("applicationContext.xml");
I'm trying to run im4java to compare the images but I'm getting the below exception message.
I have followed the steps to add ImageMagick as in this link: https://www.imagemagick.org/script/download.php#macosx
I was getting the same error so, I added the environmental variable in the run configurations of my eclipse as:
DYLD_LIBRARY_PATH=/Users/siva/Downloads/ImageMagick-7.0.5/lib and started running but still i'm getting the same error message:
I also tried:
System.setProperty("java.library.path", "/Users/siva/Downloads/ImageMagick-7.0.5/bin/magick");
If anyone has tried using imageMagick on Mac please suggest me what are the steps I have to do.
I was able to run the below command from the terminal successfully:
compare imageone.png imagetwo.png diffimage.png
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.ImageMagickCmd;
import org.im4java.core.Info;
import org.im4java.process.ArrayListOutputConsumer;
public class UseImageM {
private static final String COMPARE_COMMAND = "compare";
private static final String ABSOLUTE_ERROR = "AE";
private static String imageOnePath = "/Users/siva/Documents/imageEclipse/UsingImagemagick/screenshot.png";
private static String imageTwoPath = "/Users/siva/Documents/imageEclipse/UsingImagemagick/screenshotfinal.png";
private static String outputImageName = "outputoftheimageCompare";
private static final int COUNT_OF_DECIMAL = 10;
public static void main(String[] args) {
IMOperation imOperation = new IMOperation();
imOperation.metric(ABSOLUTE_ERROR);
imOperation.addImage(imageOnePath);
imOperation.addImage(imageTwoPath);
imOperation.addImage(outputImageName);
ImageMagickCmd compare = new ImageMagickCmd(COMPARE_COMMAND);
ArrayListOutputConsumer outputConsumer = new ArrayListOutputConsumer();
compare.setOutputConsumer(outputConsumer);
BigDecimal diffPercentage = BigDecimal.ZERO;
Info imageInfo;
long imageSize = 0;
try {
imageInfo = new Info(imageTwoPath, true);
imageSize = imageInfo.getImageWidth() * imageInfo.getImageHeight();
compare.run(imOperation);
final ArrayList<String> errorText = compare.getErrorText();
if (errorText.size() == 1) {
final BigDecimal diffCount = new BigDecimal(errorText.get(0));
if (!BigDecimal.ZERO.equals(diffCount)) {
diffPercentage = diffCount.divide(
new BigDecimal(imageSize), COUNT_OF_DECIMAL,
BigDecimal.ROUND_DOWN);
}
}
} catch (final IOException | InterruptedException e) {
System.out.println((String.format(
"Exception happened in comparison between %s and %s.",
imageOnePath, imageTwoPath) + e));
} catch (final IM4JavaException e) {
e.printStackTrace();
// error message
if (!StringUtils.isNumeric(compare.getErrorText().get(0))) {
final String errorMsg = String.format(
"Exception happened in comparison between %s and %s.",
imageOnePath, imageTwoPath);
System.out.println(errorMsg + e);
}
final BigDecimal diffCount = new BigDecimal(compare.getErrorText()
.get(0));
diffPercentage = diffCount.divide(new BigDecimal(imageSize),
COUNT_OF_DECIMAL, BigDecimal.ROUND_DOWN);
}
System.out.println(diffPercentage);
}
}
Console Logs:
org.im4java.core.InfoException: org.im4java.core.CommandException: java.io.IOException: Cannot run program "identify": error=2, No such file or directory
at org.im4java.core.Info.getBaseInfo(Info.java:360)
at org.im4java.core.Info.<init>(Info.java:151)
at UseImageM.main(UseImageM.java:36)
Caused by: org.im4java.core.CommandException: java.io.IOException: Cannot run program "identify": error=2, No such file or directory
at org.im4java.core.ImageCommand.run(ImageCommand.java:219)
at org.im4java.core.Info.getBaseInfo(Info.java:342)
... 2 more
Caused by: java.io.IOException: Cannot run program "identify": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at org.im4java.process.ProcessStarter.startProcess(ProcessStarter.java:407)
at org.im4java.process.ProcessStarter.run(ProcessStarter.java:312)
at org.im4java.core.ImageCommand.run(ImageCommand.java:215)
... 3 more
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 6 more
Exception in thread "main" java.lang.NullPointerException
at UseImageM.main(UseImageM.java:60)
In my Spring Boot 1.5 application I use ClassPathResource to read a static file the application JAR:
// ...
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
#Slf4j
#Service
public class MyService {
private Resource resource = new ClassPathResource("a.txt");
private List<String> myStrings;
public MyService() {
myStrings = load(resource);
}
private List<String> load(Resource resource) {
try(Stream<String> stream = Files.lines(Paths.get(resource.getURI()))) {
myStrings = stream.filter(/* my filter */)
.collect(Collectors.toList());
} catch (IOException x) {
log.error("Failed to read '{}'.", resource.getFilename());
}
}
}
but this fails with:
Caused by: java.nio.file.FileSystemNotFoundException: null
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) ~[zipfs.jar:1.8.0_121]
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) ~[zipfs.jar:1.8.0_121]
at java.nio.file.Paths.get(Paths.java:143) ~[na:1.8.0_121]
at MyService.load(MyService.java:53) ~[classes!/:2.0.0-SNAPSHOT]
//...
How can I read a ClassPathResource embedded in my application JAR?
The JDK's Paths.get cannot resolve resources within JAR files so replace:
Files.lines(Paths.get(resource.getURI()))
with:
new BufferedReader(new InputStreamReader(resource.getInputStream())).lines();
I've tried to build a route to copy files from one directory to an other directory. But instead of using:
from(file://source-directory).to(file://destination-directory)
I want to do something like this:
from(direct:start)
.to(direct:doStuff)
.to(direct:readDirectory)
.to(file://destination-folder)
I've done the following stuff:
Route
#Component
public class Route extends AbstractRouteBuilder {
#Override
public void configure() throws Exception {
from("direct:start")
.bean(lookup(ReadDirectory.class))
.split(body())
.setHeader("FILENAME", method(lookup(CreateFilename.class)))
.to("file:///path/to/my/output/directory/?fileName=${header.FILENAME}");
}
Processor
#Component
public class ReadDirectory implements CamelProcessorBean {
#Handler
public ImmutableList<File> apply(#Header("SOURCE_DIR") final String sourceDir) {
final File directory = new File(sourceDir);
final File[] files = directory.listFiles();
if (files == null) {
return ImmutableList.copyOf(Lists.<File>newArrayList());
}
return ImmutableList.copyOf(files);
}
}
I can start my route by using the following pseudo-Test (The point is I can manually start my route by producer.sendBodyAndHeader(..))
public class RouteIT extends StandardIT {
#Produce
private ProducerTemplate producer;
#Test
public void testRoute() throws Exception {
final String uri = "direct:start";
producer.sendBodyAndHeaders(uri, InOut, null, header());
}
private Map<String, Object> header() {
final Map<String, Object> header = Maps.newHashMap();
header.put("SOURCE_DIR", "/path/to/my/input/directory/");
return header;
}
}
AbstractRouteBuilderextends SpringRouteBuilder
CamelProcessorBean is only a Marker-Interface
StandardIT loads SpringContext and stuff
The problem is, that I must set the filename. I've read some stuff that camel sets the header CamelFileNameProduced (during the file endpoint). It is a generic string with timestamp and if I don't set the filename - the written files will get this generic string as the filename.
My Question is: Is there a more beautiful solution to copy files (but starting with a direct-endpoint and read the directory in the middle of the route) and keep the filename for the destination? (I don't have to set the filename when I use from("file:source").to("file:destination"), why must I do it now?)
You can set the file name when you send using the producer template, as long as the header is propagated during the routing between the routes you are all fine, which Camel does by default.
For example
#Test
public void testRoute() throws Exception {
final String uri = "direct:start";
Map headers = ...
headers.put(Exchange.FILE_NAME, "myfile.txt");
producer.sendBodyAndHeaders(uri, InOut, null, headers);
}
The file component talks more about how to control the file name
http://camel.apache.org/file2