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

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
}
}

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

TestNG Unit Testing Tar and 7z

folder structure is here
console output is here
I'd like to write a test class for the 2 methods below
package jfe;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
public class JThreadFile {
/**
* uncompresses .tar file
* #param in
* #param out
* #throws IOException
*/
public static void decompressTar(String in, File out) throws IOException {
try (TarArchiveInputStream tin = new TarArchiveInputStream(new FileInputStream(in))){
TarArchiveEntry entry;
while ((entry = tin.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curfile = new File(out, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
IOUtils.copy(tin, new FileOutputStream(curfile));
}
}
}
/**
* uncompresses .7z file
* #param in
* #param destination
* #throws IOException
*/
public static void decompressSevenz(String in, File destination) throws IOException {
//#SuppressWarnings("resource")
SevenZFile sevenZFile = new SevenZFile(new File(in));
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null){
if (entry.isDirectory()){
continue;
}
File curfile = new File(destination, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
FileOutputStream out = new FileOutputStream(curfile);
byte[] content = new byte[(int) entry.getSize()];
sevenZFile.read(content, 0, content.length);
out.write(content);
out.close();
}
sevenZFile.close();
}
}
I use testNG and try to read from a folder, filter the folder for certain extensions (.tar and .7z) feed those files to the uncompress methods and compare the result to the actualOutput folder with AssertEquals. I manage to read the file names from the folder (see console output) but can't feed them to decompressTar(String in, File out). Is this because "result" is a String array and I need a String? I have no clue how DataProvider of TestNG handles data. Any help would be appreciated :) Thank you :)
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class JThreadFileTest {
protected static final File ACT_INPUT = new File("c:\\Test\\TestInput\\"); //input directory
protected static final File EXP_OUTPUT = new File("c:\\Test\\ExpectedOutput\\"); //expected output directory
protected static final File TEST_OUTPUT = new File("c:\\Test\\TestOutput\\");
#DataProvider(name = "tarJobs")
public Object[] getTarJobs() {
//1
String[] tarFiles = ACT_INPUT.list(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".tar");
}
});
//2
Object[] result = new Object[tarFiles.length];
int i = 0;
for (String filename : tarFiles) {
result[i] = filename;
i++;
}
return result;
}
#Test(dataProvider = "tarJobs")
public void testTar(String result) throws IOException {
System.out.println("Running test" + result);
--> JThreadFile.decompressTar(result, TEST_OUTPUT);
Assert.assertEquals(TEST_OUTPUT, EXP_OUTPUT);
}
}

Cannot read file from abstract class

I am trying to make a base file plugin which other threads will inherit. But I am stuck at a point where the file exists and can be read from a normal thread but when I try to read that file from an abstract Base file, it says File not found. Here's my base class :-
package com.evol.fp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public abstract class BaseFilePlugin extends Thread implements BaseFileReader{
String filename = "";
File file = null;
boolean fileStarted = false;
boolean fileEnded = false;
public BaseFilePlugin() {
file = new File(filename);
}
public void readFile() {
BufferedReader br = null;
System.out.println("Base call: " + filename);
try {
System.out.println("inbside ");
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
if(br.readLine().trim().isEmpty()) {
endFile();
return;
} else {
startFile(filename);
String record;
while((record = br.readLine().trim()) != null) {
parseRecord(record);
}
endFile();
}
} catch(Exception ioe) {
ioe.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public abstract void parseRecord(String record);
public void startFile(String filename) {
this.fileStarted = true;
this.fileEnded = false;
}
public void endFile() {
file.delete();
this.fileEnded = true;
this.fileStarted = false;
}
public void run() {
while(true) {
System.out.println("Inside run, fileName: " + filename);
System.out.println("Filestarted: " + fileStarted + ", file exists: " + file.exists());
if(!fileStarted) {
readFile();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* #return the filename
*/
public String getFilename() {
return filename;
}
/**
* #param filename the filename to set
*/
public void setFilename(String filename) {
this.filename = filename;
}
}
I am aware of multithreading but never implemented with base class to parse records from a file, if someone tells me what's the problem that will be great. I know that the file exists for sure. Here's my child class: -
package com.evol.fp;
public class FileReaderThread extends BaseFilePlugin {
public FileReaderThread() {
super.setFilename("E:\\soham\\soham.txt");
}
#Override
public void parseRecord(String record) {
System.out.println(record);
}
}
But its not calling the child's parseRecord method, using a simple main method:-
package com.evol.fp;
public class StartProcess {
public static void main(String[] args) {
FileReaderThread thd = new FileReaderThread();
thd.start();
}
}
I think it's because the parent constructor (BaseFilePlugin.class) is called first before you set your filename in super.setFile("E:\\soham\\soham.txt");
If you can remove the parent constructor instead and replace your setFileName into setFile where file is iniatilize .e.g
// public BaseFilePlugin() {
// file = new File(filename);
// }
....
....
/**
* #return the file
*/
public String getFile() {
return file
}
/**
* #param file the file to set
*/
public void setFile(String file) {
file = new File(file);
}
and in your subclass
public FileReaderThread() {
super.setFile("E:\\soham\\soham.txt");
}
BaseFilePlugin's constructor creates its file with an empty string since initially String filename = "";.
The client calls setFilename(...) which updates filename. However, file is still the same instance when the object was first created (which is using an empty string as the file name).
I would suggest to pass the file name as part of the constructor so file is properly initialized:
public BaseFilePlugin(String filename) {
this.filename = filename;
file = new File(filename);
}
Optionally, if it makes sense that an instance can read only 1 file, then make those class attributes final, and remove the setFilename() method.

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

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.

file upload in FileNet?

I'm writing code to upload a file in FileNet.
A standalone java program to take the some inputs, and upload it in FileNet. I'm new to FileNet. Can you help me out, How to do it?
You can use Document.java provided by IBM for your activities and many other Java classes
package fbis.apitocasemanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.user.DocumentUtil;
public class Addfilescasemanager {
/**
* #param args
*/
public static void addfiles_toicm(String directory, String lFolderPath)
{
try {
DocumentUtil.initialize();
String path = directory;
System.out.println("This is the path:..............................."
+ path);
String file_name;
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
file_name = listOfFiles[i].getName();
System.out.println(file_name);
String filePaths = directory + file_name;
// File file = new File("C:\\FNB\\att.jpg");
File file = new File(filePaths);
InputStream attStream = null;
attStream = new FileInputStream(file);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name, "Document");
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}//end of method
public static void addfile_toicm(File file_name, String lFolderPath)
{
try {
DocumentUtil.initialize();
InputStream attStream = null;
attStream = new FileInputStream(file_name);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name.getName(), "Document");
System.out.println("File added successfully");
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}//end of method
public static void main(String nag[])
{
addfiles_toicm("E:\\FSPATH1\\BLR_14122012_001F1A\\","/IBM Case Manager/Solution Deployments/Surakshate Solution for form 2/Case Types/FISB_FactoriesRegistration/Cases/2012/12/06/16/000000100103");
}
}
and my DocumentUtil class is
package com.user;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.security.auth.Subject;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ReferentialContainmentRelationship;
import com.filenet.api.util.UserContext;
public class DocumentUtil {
public static ObjectStore objectStore = null;
public static Domain domain = null;
public static Connection connection = null;
public static void main(String[] args)
{
initialize();
/*
addDocumentWithPath("/FNB", "C:\\Users\\Administrator\\Desktop\\Sample.txt.txt",
"text/plain", "NNN", "Document");
*/
File file = new File("E:\\Users\\Administrator\\Desktop\\TT.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addDocumentWithStream("/FNB", fis, "text/plain", "My New Doc", "Document");
}
public static void initialize()
{
System.setProperty("WASP.LOCATION", "C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear \\cews.war\\WEB-INF\\classes\\com\\filenet\\engine\\wsi");
System.setProperty("SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty(":SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty("java.security.auth.login.config","C:\\Progra~1\\IBM\\WebSphere\\AppServer\\java\\jre");
connection = Factory.Connection.getConnection(CEConnection.uri);
Subject sub = UserContext.createSubject(connection,
com.user.CEConnection.username, CEConnection.password,
CEConnection.stanza);
UserContext.get().pushSubject(sub);
domain = Factory.Domain.getInstance(connection, null);
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET", null);
System.out.println("\n\n objectStore--> " + objectStore.get_DisplayName());
}
public static void addDocumentWithPath(String folderPath, String filePath,
String mimeType, String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = CEUtil.createDocWithContent(new File(filePath), mimeType,
objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
}
public static void addDocumentWithStream(String folderPath,
InputStream inputStream, String mimeType,
String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = Factory.Document.createInstance(objectStore, null);
ContentElementList contEleList = Factory.ContentElement.createList();
ContentTransfer ct = Factory.ContentTransfer.createInstance();
ct.setCaptureSource(inputStream);
ct.set_ContentType(mimeType);
ct.set_RetrievalName(docName);
contEleList.add(ct);
doc.set_ContentElements(contEleList);
doc.getProperties().putValue("DocumentTitle", docName);
doc.set_MimeType(mimeType);
doc.checkin(AutoClassify.AUTO_CLASSIFY, CheckinType.MAJOR_VERSION);
doc.save(RefreshMode.REFRESH);
ReferentialContainmentRelationship rcr = folder.file(doc,
AutoUniqueName.AUTO_UNIQUE, docName,
DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE);
rcr.save(RefreshMode.REFRESH);
/*
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
*/
}
public static ObjectStore getObjecctStore()
{
if (objectStore != null) {
return objectStore;
}
// Make connection.
com.filenet.api.core.Connection conn = Factory.Connection
.getConnection(CEConnection.uri);
Subject subject = UserContext.createSubject(conn,
CEConnection.username, CEConnection.password, null);
UserContext.get().pushSubject(subject);
try {
// Get default domain.
Domain domain = Factory.Domain.getInstance(conn, null);
// Get object stores for domain.
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET",
null);
System.out.println("\n\n Connection to Content Engine successful !!");
} finally {
UserContext.get().popSubject();
}
return objectStore;
}
}
The above answer is extremely good. Just wanted to save people some time but I don't have the points to comment so am adding this as an answer.
Eclipse wasted a lot of my time getting the above to work because it suggested the wrong classes to import. Here's the list of correct ones:
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Document;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Folder;
import com.filenet.api.core.Factory;
import com.filenet.api.core.ReferentialContainmentRelationship;

Categories

Resources