How to read properties file from meta-inf folder from a POJO - java

How to read properties file from meta-inf folder in a web application from plain java class.

The simplest you can do is :-
InputStream propertiesIs = this.getClass().getClassLoader().getResourceAsStream("META-INF/your.properties");
Properties prop = new Properties();
prop.load(propertiesIs);
System.out.println(prop.getProperty(YourPropertyHere));
OR
you can try loading your properties using FileInputStream also :-
input = new FileInputStream("META-INF/your.properties");

When reading resources, one should take care of closing them properly.
InputStream streamOrNull = getClass().getClassLoader().getResourceAsStream(
"META-INF/your.properties");
if (streamOrNull == null) {
// handle no such file
}
else {
try (InputStream stream = streamOrNull) { // close stream eventually
Properties properties = new Properties();
properties.load(stream);
// access properties
}
}

package net.bounceme.doge.json;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PropertiesReader {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(PropertiesReader.class.getName());
public Properties tryGetProps(String propertiesFileName) {
log.fine(propertiesFileName);
Properties properties = new Properties();
try {
properties = getProps(propertiesFileName);
} catch (IOException ex) {
Logger.getLogger(PropertiesReader.class.getName()).log(Level.SEVERE, null, ex);
}
log.info(properties.toString());
return properties;
}
private Properties getProps(String propertiesFileName) throws IOException {
log.fine(propertiesFileName);
Properties properties = new Properties();
properties.load(PropertiesReader.class.getResourceAsStream("/META-INF/" + propertiesFileName + ".properties"));
log.fine(properties.toString());
return properties;
}
}
this works for me.

Related

Got an error that attribute value is missing

I have base class that have an Url url without instantiation, than I have and class that inherit it and in the before method of it (TestNG) I have statement :
url = new URL(props.getProperty(“appiumURL”));
the URL is 127.0.0.0
afterwards I have :
desiredCapabilities.setCapability(“automationName”, props.getProperty(“iOSAutomationName”));
String iOSAppUrl = getClass().getResource(props.getProperty(“iOSAppLocation”)).getFile();
utils.log().info(“appUrl is” + iOSAppUrl);
desiredCapabilities.setCapability(“bundleId”, props.getProperty(“iOSBundleId”));
desiredCapabilities.setCapability(“wdaLocalPort”, wdaLocalPort);
desiredCapabilities.setCapability(“webkitDebugProxyPort”, webkitDebugProxyPort);
//desiredCapabilities.setCapability(“app”, iOSAppUrl);
driver = new IOSDriver(url, desiredCapabilities);
the value of the url is : http://0.0.0.0:4723/wd/hub
than after the line of the “driver = new IOSDriver(url, desiredCapabilities);” I get an exception that the url is null,
than BuildInfo class is opened :
package org.openqa.selenium;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
/**
* Reads information about how the current application was built from the Build-Info section of
the
* manifest in the jar file, which contains this class.
*/
public class BuildInfo {
private static final Properties BUILD_PROPERTIES = loadBuildProperties();
private static Properties loadBuildProperties() {
Properties properties = new Properties();
Manifest manifest = null;
JarFile jar = null;
try {
URL url = BuildInfo.class.getProtectionDomain().getCodeSource().getLocation();
File file = new File(url.toURI());
jar = new JarFile(file);
ZipEntry entry = jar.getEntry("META-INF/build-stamp.properties");
if (entry != null) {
try (InputStream stream = jar.getInputStream(entry)) {
properties.load(stream);
}
}
manifest = jar.getManifest();
} catch (
IllegalArgumentException |
IOException |
NullPointerException |
URISyntaxException ignored) {
} finally {
if (jar != null) {
try {
jar.close();
} catch (IOException e) {
// ignore
}
}
}
if (manifest == null) {
return properties;
}
try {
Attributes attributes = manifest.getAttributes("Build-Info");
Set<Entry<Object, Object>> entries = attributes.entrySet();
for (Entry<Object, Object> e : entries) {
properties.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
attributes = manifest.getAttributes("Selenium");
entries = attributes.entrySet();
for (Entry<Object, Object> e : entries) {
properties.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
} catch (NullPointerException e) {
// Fall through
}
return properties;
}
/** #return The embedded release label or "unknown". */
public String getReleaseLabel() {
return BUILD_PROPERTIES.getProperty("Selenium-Version", "unknown").trim();
}
/** #return The embedded build revision or "unknown". */
public String getBuildRevision() {
return BUILD_PROPERTIES.getProperty("Build-Revision", "unknown");
}
/** #return The embedded build time or "unknown". */
public String getBuildTime() {
return BUILD_PROPERTIES.getProperty("Build-Time", "unknown");
}
#Override
public String toString() {
return String.format("Build info: version: '%s', revision: '%s', time: '%s'",
getReleaseLabel(), getBuildRevision(), getBuildTime());
}
the thing is that :
attributes = manifest.getAttributes("Selenium");
entries = attributes.entrySet();
the attribute is null .
what I’m doing wrong?
Thank you

How to read properties file in java, which has value in key-value pair

if properties file contains below type values how to read it directly into map
user={'name':'test','age':'23','place':'london'}.
Thanks in advance!
You can inject values into a Map from the properties file using the #Value annotation like this.
#Value("#{${user}}")
private Map<String, String> user;
Entry in your application.properties must be:
user = {"name":"test","age":"23","place":"London"}
test.properties file
name=test
age=23
place=london
code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
public class ReadPropertiesFile {
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
System.out.println(key + ": " + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope, this would help.. :)
This will read a property file and put it in Properties object.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesConfig {
private Properties prop;
private PropertiesConfig() {
super();
init();
}
private static class PropertiesInstance {
private static PropertiesConfig instance = null;
public static PropertiesConfig getInstance() {
if (null == instance) {
instance = new PropertiesConfig();
}
return instance;
}
}
public static PropertiesConfig getInstance() {
return PropertiesInstance.getInstance();
}
private void init() {
prop = new Properties();
try (InputStream input = getClass().getResourceAsStream("/sample_config.properties")) {
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getProperty(String key) {
return prop.getProperty(key);
}
}
Now you can use any library to convert a value to Map as your value looks like a JSON.
Code example to achieve this through Jackson:
public static Map < String, Object > covertFromJsonToMap(String json) throws JsonTransformException {
try {
return mapper.readValue(json, new TypeReference < HashMap < String, Object >> () {});
} catch (Exception e) {
LOGGER.error("Error " + json, e);
throw new JsonTransformException("Error in json parse", e);
}
}
So something like this will do:
covertFromJsonToMap(PropertiesConfig.getInstance().get("user"));
Looks like you have a JSON representation of your map as a value. Once you read the value as a String in Java you can use Gson to convert it to map
Gson gson = new Gson();
String json = <YOUR_STRING>
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());

Retrieving properties from the Classpath rather than from resources/config.properties

I currently have the following method which allows me to pick properties that have been defined in my resources/config.properties file
private final Properties properties = new Properties();
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("Resources/config.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
But I now want to pick my properties from the classpath so I have moved my config.properties from resources and placed it directly under src. But I'm struggling to know what changes I now need to make to my method to enable me to read from classpath.
Check example here
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReaderProp {
public final Properties properties = new Properties();
public ReaderProp()
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("error.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ReaderProp readerProp = new ReaderProp();
System.out.println(readerProp.properties.get("E1000_SE_ERROR-CODE"));// output E1000
}
}
Check error.properties
======================
E1000_SE_ERROR-CODE = E1000
//Find another answer
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReaderProp {
private final Properties configProp = new Properties();
/**
* read property file
*
* #param propertyName
* #param path
*
* #throws IOException
*/
public ReaderProp(String propertyName, String path) {
try {
InputStream in;
File file;
if (path.equals("")) {
in = this.getClass().getClassLoader().getResourceAsStream(propertyName);
}
else {
file = new File(path + propertyName);
in = new FileInputStream(file);
}
configProp.load(in);
}
catch (IOException e) {
}
}
public static void main(String[] args) {
ReaderProp readerProp = new ReaderProp("error.properties",new File("").getAbsolutePath()+"\\src\\");
System.out.println(readerProp.configProp.get("E1000_SE_ERROR-CODE"));// output E1000
}
}

Properties file reset when modifying or adding value

What I need is a simple way to read and write certain values to a XML file? I want it to be simple something like this:
Configuration config = new Configuration();
config.setValue("WIDTH", 1000);
int WIDTH = config.getValue("WIDTH");
It needs to be writable and readable at all times. This is what I have so far:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class Configuration {
Properties config;
public Configuration() {
config = new Properties();
}
public void setValue(String name, String value) {
try {
config.setProperty(name, value);
config.storeToXML(new FileOutputStream("MyXmlConfig.xml"), null);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValue(String name) {
try {
config.loadFromXML(new FileInputStream("MyXmlConfig.xml"));
} catch (Exception e) {
e.printStackTrace();
}
return config.getProperty(name);
}
}
The problem with what I have is that it resets the created file when a variable is updated or added.
The built-in class java.util.Properties supports this use case:
Properties config = new Properties();
config.loadFromXML(new FileInputStream("c:/MyXmlConfig.xml"));
config.setProperty("WIDTH", "1000");
int WIDTH = Integer.parseInt(config.getProperty("WIDTH"));
config.storeToXML(new FileOutputStream("c:/MyXmlConfig.xml"), "My config file");

Vaadin Upload component - directly upload to mongo repository

I want to use a vaadin upload component in my webapplication and directly upload files to mongo db in gridfs format.
My current implementation use a temporary storage location to first upload file and then store in mongo converting to gridfs.
here is my upload component code: I have implement Receiver interface method recieveUpload
private File file;
private String tempFilePath;
public class HandleUploadImpl extends CustomComponent
implements Upload.SucceededListener,
Upload.FailedListener,
Upload.ProgressListener,
Upload.Receiver { ........
public OutputStream receiveUpload(String filename, String MIMEType) {
logger.debug("File information {} {}", filename, MIMEType);
this.filename = filename;
FileOutputStream fos;
file = new File(tempFilePath + filename);
try {
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
logger.error("Error occurred while opening the file {}", e);
return null;
}
return fos;
}
Here is my code to store in mongo repository
private void saveBuildFile(Map<String, Object> buildFileInfo, String key) {
if (buildFileInfo.containsKey(key)) {
GridFS gridFS = new GridFS(mongoTemplate.getDb(), COLLECTION_NAME);
File file = (File) buildFileInfo.get(key);
buildFileInfo.remove(key);
try {
GridFSInputFile savedFile = gridFS.createFile(file);
savedFile.put(idK, buildFileInfo.get(key + "-id"));
savedFile.save();
} catch (Exception e) {
logger.error("Something went wrong when saving the file in the db {}", e);
}
}
}
Is there a way I can omit the use of temporary storage and set the output stream of upload component to mongo repository gridfs file.
This works for me:
package ch.domain.vaadin;
import ch.domain.vaadin.mongo.MongoItem;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
/**
*
* #author eric
*/
class ImageUploader implements Receiver, SucceededListener {
private String filename;
private DB db;
private ByteArrayOutputStream fos;
private FieldGroup fieldGroup;
public void setFieldGroup(FieldGroup fieldGroup) {
this.fieldGroup = fieldGroup;
}
public ImageUploader(DB db)
{
this.db = db;
}
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
this.fos = new ByteArrayOutputStream();
this.filename = filename;
return this.fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(this.fos.toByteArray());
MongoItem parentId = (MongoItem) fieldGroup.getItemDataSource();
gfsFile.setMetaData(new BasicDBObject().append("parentId", parentId.getItemProperty("_id").getValue().toString()));
gfsFile.setFilename(this.filename);
gfsFile.save();
this.fos = null;
gfsFile = null;
// Show the uploaded file in the image viewer
// image.setVisible(true);
// image.setSource(new FileResource(file));
}
}

Categories

Resources