How to resolve config from file and also few config programmatically? - java

In my use case, I have a scenario where I want to populate some of the configs from the typesafe config file itself and some of those, I want to set programmatically. For example, for below myconfig.conf file
env=staging
topic=${env}_${event}
In above, snippet, topic should be resolved as staging_someevent event where someevent is set in one of the method which resolves this value based on argument in the job using args.
I am able to resolve one of those but not both. Below code resolves ${event}
String event = "someevent";
File file = new File("myconfig.conf");
InputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream);
String configText = ConfigFactory.parseReader(reader)
.resolveWith(ConfigFactory.parseString("event=" + event))
.root
.render(ConfigRenderOptions.concise().setJson(false));
System.out.println(configText);
Similarly, below code resolves ${env} but how can I resolve both?
String configText = ConfigFactory.parseReader(reader)
.resolve()
.root
.render(ConfigRenderOptions.concise().setJson(false));
System.out.println(configText);

Related

reuse parameters defined within config.parmeters file in java

I have a config properties file in a java project created in eclipse.
Below are the contents in the properties file.
adminApp= testAdminDemo
customerApp = testCustDemo
appHostIP = 172.22.XX.XX
adminAppURL = http://appHostIP:9049/adminApp
customerAppURL = http://appHostIP:9049/customerApp
When the appURL parameter is read from a Java class,
Properties prop = new Properties();
FileInputStream f = new FileInputStream(System.getProperty("user.dir") + "\\config.properties");
prop.load(f);
String url = prop.getProperty("appURL");
System.out.println("URL: " + url);
the output is the same value mentioned for parameter 'url' in config.parameters file:
http://appHostIP:9049/adminApp
Actually, I expected the output to be like:
http://172.22.XX.XX:9049/testAdminDemo
Is there anything wrong in this approach?
I don't want to read host ip and app name in the java class file and then form a string. Instead, the required URl should get formed in the properties file as need to deal with different apps - admin, customer, etc.
You cannot perform concatination in the property file, You have to handle the concatination in code where you are using it like below.
appHostIP = 172.22.XX.XX
adminAppURL = :9049/adminApp
String url = "http://" + "prop.getProperty("appHostIP")+ prop.getProperty("appURL");

Get value from application-lcl.properties in an xml configuration Spring

i have in some spring application , in application-lcl.properties a line with :
key1=value1
I want to use the value of key1 in another xml like this :
<appender name="ELASTIC" class="com.internetitem.logback.elasticsearch.ElasticsearchAppender">
<url>${key1}</url>
${key1} doesn't work. Do you know how to do it ? (the .xml already exists )
Thanks
Its a 2 step process
Load properties file into java.util.java.util.Properties class object.
Use Properties.storeToXML() method to write the content as XML
String inPropertiesFile = "application.properties";
String outXmlFile = "applicationProperties.xml";
InputStream is = new FileInputStream(inPropertiesFile); //Input file
OutputStream os = new FileOutputStream(outXmlFile); //Output file
Properties props = new Properties();
props.load(is);
props.storeToXML(os, "application.properties","UTF-8");
in the xml , put
<springProperty name="value1" source="key1"/>
and then use it by calling
<url>${value1}</url>

Merging two pdf documents with PDFMergerUtility throws: IOException("Page tree root must be a dictionary")

I have a spring boot application and I am trying to merge two pdf files. The one I am getting as a byte array from another service and the one I have it locally in my resources file: /static/documents/my-file.pdf. This is the code of how I am getting byte array from my file from resources:
public static byte[] getMyPdfContentForLocale(final Locale locale) {
byte[] result = new byte[0];
try {
final File myFile = new ClassPathResource(TEMPLATES.get(locale)).getFile();
final Path filePath = Paths.get(myFile.getPath());
result = Files.readAllBytes(filePath);
} catch (IOException e) {
LOGGER.error(format("Failed to get document for local %s", locale), e);
}
return result;
}
I am getting the file and getting the byte array. Later I am trying to merge this two files with the following code:
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
pdfMergerUtility.addSource(new ByteArrayInputStream(offerDocument));
pdfMergerUtility.addSource(new ByteArrayInputStream(merkblattDocument));
ByteArrayOutputStream os = new ByteArrayOutputStream();
pdfMergerUtility.setDestinationStream(os);
pdfMergerUtility.mergeDocuments(null);
os.toByteArray();
But unfortunately it throws an error:
throw new IOException("Page tree root must be a dictionary");
I have checked and it makes this validation before it throws it:
if (!(root.getDictionaryObject(COSName.PAGES) instanceof COSDictionary))
{
throw new IOException("Page tree root must be a dictionary");
}
And I really have no idea what does this mean and how to fix it.
The strangest thing is that I have created totally new project and tried the same code to merge two documents (the same documents) and it works!
Additionally what I have tried is:
Change the spring boot version if it is ok
Set the mergeDocuments method like this: pdfMergerUtility.mergeDocuments(setupMainMemoryOnly())
Set the mergeDocuments method like this: pdfMergerUtility.mergeDocuments(setupTempFileOnly())
Get the bytes with a different method not using the Files from java.nio:
And also executed this in a different thread
Merging files only locally stored (in resources)
Merging the file that I am getting from another service - this works btw and that is why I am sure he is ok
Can anyone help with this?
The issue as Tilman Hausherr said is in that resource filtering that you can find in your pom file. If you have a case where you are not allowed to modify this then this approach will help you:
final String path = new
ClassPathResource(TEMPLATES.get(locale)).getFile().getAbsolutePath();
final File file = new File(path);
final Path filePath = Paths.get(file.getPath());
result = Files.readAllBytes(filePath);
and then just pass the bytes to the pdfMergerUtility object (or even the whole file instead of the list of bytes).

To get the content from .properties file into selenium framework

# Compulsory Dimension to create port
xOffset=-3
yOffset=50
How to get these xOffset and YOffset in java file.I tried with inputstream but not getting.These variable should get loaded in java file.
You can use Properties class from Java library
Properties prop = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
The you can get the values as
prop.getProperty("propertyname");
Try the following code:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("your_config.properties");
prop.load(input);
System.out.println(prop.getProperty("xOffset"));
System.out.println(prop.getProperty("yOffset"));
} catch (IOException e) {
// ...
}
As above explained Create a Function to read the property File During or Before Selenium Driver Constructor . So you can use them in test ( Help in Desire Capability Impl).
Store the values in Public Static final ( If you don not want to change them in Selenium and use as Default Property input)
As the values are read by Java Propertie file or .config file before selenium Driver so you can use them in Driver constructor or if you don't want you can use those properties stored as Static anywhere in the project. These values act as GLOBAL param.

Access file in WebContent folder from a servlet

I'm trying to generate a PDF document using FOP. The pdf generation code is kept in a servlet and the xsl is in a specific folder in the WebContent folder.
How can I access this xsl file by giving a relative path? It works only if I give the complete path in the File object.
I need to generate the xml content dynamically. How can I give this dynamically generated xml as the source instead of a File object?
Please provide your suggestions.
To get the path you can just do:
String path = s.getServletContext().getRealPath("/WEB-INF/somedir/hdfeeh");
s is the class that implements HTTPServlet.You can also use this.getServletContext() if its your servlet class.
Then pass this as a parameter.
As far as using dynamically generated XML, the library you're using should support using an input stream, write your XML, convert it to a byte array, then wrap it in a ByteArrayInputStream and use this.
For a direct and independent container implementation, you can access the resourcewith the following method getResource() inside your servlet:
/start servlet/
public InputStream getResource(String resourcePath) {
ServletContext servletContext = getServletContext();
InputStream openStream = servletContext.getResourceAsStream( resourcePath );
return openStream;
}
public void testConsume() {
String path = "WEB-INF/teste.log";
InputStream openStream = getResource( path );
int c = -1;
byte[] bb = new byte[1024];
while ( -1 != ( c = openStream.read( bb ) ) ) {
/* consume stream */
}
openStream.close();
}
/end servlet/
I used the following method to read the file under web content
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getSession().getServletContext().getResourceAsStream("/json/sampleJson.json")));
Now all the file content is available in the reader object.

Categories