I am unable to configure log4j2 with java.util.properties. I always get this message "tatusLogger No Log4j 2 configuration file found". Please see my logger class. I am reading the log4j2 properties from two files.
I will be attaching my code to this post.
package my.common.logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
import org.apache.logging.log4j.util.PropertiesUtil;
public class MyLogger {
private static boolean configured = false;
private static Logger logger;
static {
System.setProperty("log4j.configurationFactory", "my.common.logger.JCFLog4JConfigurationFactory");
}
private static void readConfiguration() throws Exception {
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(context, createConfigurationSource());
configuration.start();
Configurator.reconfigure();
configured = true;
}
public static Logger getLogger(String className) {
try {
if (!configured) readConfiguration();
return org.apache.log4j.LogManager.getLogger(className);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static ConfigurationSource createConfigurationSource()
{ Properties p = new Properties();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = null;
try {
p.putAll(<Read from File 1>);
p.putAll(<Read from File 2>);
p.store(out, null);
} catch (IOException e) {
e.printStackTrace();
}
in = new ByteArrayInputStream(out.toByteArray());
ConfigurationSource configSrc = null;
try {
configSrc = new ConfigurationSource(in);
}
catch (IOException i)
{
i.printStackTrace();
}
return configSrc;
}
}
Here is Config Factory Code:
package nj.aoc.ito.cmfw.common.logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
public class MyLog4JConfigurationFactory extends ConfigurationFactory {
public MyLog4JConfigurationFactory() {
}
#Override
public Configuration getConfiguration(LoggerContext ctx, ConfigurationSource source) {
PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory();
return factory.getConfiguration(ctx, source);
}
#Override
protected String[] getSupportedTypes() {
return new String[]{".properties", "*"};
}
}
Any idea what I might be doing wrong?
Thanks
Nags
Related
Scope(This is what i want to do): Hey looking for to attached screenshot in my extent report file.
Problem: so now i have used the ExtentTest class in BaseClass file. but when i run my testsuit from testNG.xml file, it give me an below error.
java.lang.NullPointerException: Cannot invoke "org.testng.ITestResult.getStatus()" because "com.example.PageClass.BaseClass.result" is null
Here is my Code in BaseClass.
package com.example.PageClass;
import com.example.Utils.Utilities;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.ITestResult;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
public class BaseClass {
public static WebDriver driver;
public static Properties prop;
public static LoginPage loginPage;
public static ExtentTest extentTest;
public static ITestResult result;
public static void properties() {
try {
FileInputStream fis = new FileInputStream("src/main/resources/generic.properties");
prop = new Properties();
prop.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setDriver() {
properties();
if (prop.getProperty("browser").contains("chrome")) {
System.setProperty("webdriver.chrome.driver", prop.getProperty("driverPath"));
driver = new ChromeDriver();
} else {
// FirefoxDriverManager.firefoxdriver().setup();
// driver = new FirefoxDriver();
}
driver.get(prop.getProperty("url"));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));
driver.manage().window().maximize();
loginPage = PageFactory.initElements(driver, LoginPage.class);
}
public static void closeDriver() throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getName()); //to add name in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getThrowable()); //to add error/exception in extent report
String screenshotPath = null;
try {
screenshotPath = Utilities.getUtilities().getScreenshot(driver, "firstScreenShot");
} catch (IOException e) {
throw new RuntimeException(e);
}
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report
extentTest.log(LogStatus.PASS, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report
}
driver.quit();
}
}
code inside StepsDef file:
package com.example.StepDefinitions;
import com.example.PageClass.BaseClass;
import com.example.Utils.Utilities;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.*;
import java.io.IOException;
public class LoginStepDefs extends BaseClass implements ITestListener {
#Before
public void setup(){
setDriver();
}
#After
public void teardown() throws IOException {
closeDriver();
}
#Then("I go to OrangeHRM Home page.")
public void iGoToOrangeHomePage() {
try {
loginPage.getOrangeHRMHome();
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#When("I enter {string} username and {string} password.")
public void iEnterUsernameAndPassword(String arg0, String arg1) {
try {
loginPage.systemLogin(arg0,arg1);
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#When("I enter username and password.")
public void iEnterUsernameAndPassword() {
try {
loginPage.systemLogin("Admin","admin123");
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#And("I navigate to PIM tab and click on add employee.")
public void iNavigateToPIMTabAndClickOnAddEmployee() {
try {
loginPage.clickOnPIM().clickOnAddEmployee();
} catch (Exception e) {
System.out.println("Username not navigate to add employee tab.");
}
}
#And("I enter employee details and save it.")
public void iEnterEmployeeDetailsAndSaveIt() {
try {
loginPage.enterFirstNameAndLastName().fileUpload().checkBoxCreateLoginDetail().enterLoginDetail().verifySuccessMessage().verifySuccessMessageForAdd();
} catch (Exception e) {
System.out.println("Username not navigate to add employee tab.");
}
}
My Folder Structure:
Can Anyone please help me out in this?
I am trying to extract only text from a pdf or word file that can contain images and other things as well using apache tika .How can I get only text from them?
What are the dependencies that i need in tika?
This the java code i have written:
package secondp;
import java.io.File;
import org.apache.tika.Tika;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.Tika;
import org.xml.sax.SAXException;
public class trial {
public static void main(final String[] args) {
try {
System.out.println(trial.convert("test.pdf"));
} catch (final Exception e) {
e.printStackTrace();
}
}
public static String convert(final String fileName) throws IOException, SAXException, TikaException {
try(final FileInputStream inputstream = new FileInputStream(new File(fileName))) {
final BodyContentHandler handler = new BodyContentHandler();
new PDFParser().parse(inputstream, handler, new Metadata(), new ParseContext());
return handler.toString().trim();
}
}
}
Similar to Background Thread for a Tomcat servlet app but I'm looking for a Java EE 7 specific solution.
This is what I finally came up with for WildFly 11 (Java EE 7) without using any configuration changes/additions to beans.xml/web.xml:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.concurrent.ManagedThreadFactory;
#Startup
#Singleton
public class IndexingTask implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(IndexingTask.class);
private Thread taskThread = null;
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
#Resource
private ManagedThreadFactory threadFactory;
#PostConstruct
public void postConstruct() {
taskThread = threadFactory.newThread(this);
taskThread.start();
}
#PreDestroy
public void preDestroy(){
shutdownLatch.countDown();
try {
taskThread.join();
} catch (InterruptedException ex) {
LOG.warn("interrupted while waiting for " + taskThread + " to shut down", ex);
}
}
#Override
public void run() {
LOG.info("started");
try {
while (!shutdownLatch.await(100, TimeUnit.MILLISECONDS)) {
}
} catch (InterruptedException ex) {
LOG.warn("", ex);
}
LOG.info("stopped");
}
}
https://javagc.leponceau.org/2017/10/how-to-runmanage-container-background.html
See also Java EE 7 containers: initialize bean at startup without adding it to beans.xml?
I need to create an app that involves browsing pdf from phone and then reading it (which will be executed later, once the browsing part is done) and I'm having trouble with it's code. I have gone through the following link I found on stackoverflow, but unfortunately it is not working,
Browse and upload pdf or word file in Android
Here is my MainActivity.java class
import java.io.File;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
Button btnAttach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAttach = (Button) findViewById(R.id.button1);
//button1 is the id of the only button I have in my activity_main.xml
// view products click event
btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button1_OnClick(view);
// Launching All products Activity
}
});
}
public void button1_OnClick(View view) {
getDocument();
}
private void getDocument() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/msword,application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
}
protected void onActivityResult ( int req, int result, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(req, result, data);
if (result == RESULT_OK) {
Uri fileuri = data.getData();
String docFilePath = getFileNameByUri(this, fileuri);
}
}
// get file path
private String getFileNameByUri(Context context, Uri uri) {
String filepath = "";//default fileName
File file;
if (uri.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = context.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION}, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mImagePath = cursor.getString(column_index);
cursor.close();
filepath = mImagePath;
} else if (uri.getScheme().compareTo("file") == 0) {
try {
file = new File(new URI(uri.toString()));
if (file.exists())
filepath = file.getAbsolutePath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
filepath = uri.getPath();
}
return filepath;
}
}
As #CherryDT pointed out, startActivityForResult(intent, REQUEST_CODE_DOC); was missing. Added it and fixed the issue.
I'm trying to run a piece of code that I found online to run JUnit test in parallel but the only thing I've modified is the URL to hit my local host. Problem is I'm constantly getting the following error and even though I've setup selenium grid many times and know how to set paths etc. I don't know how to fix this one.
org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see http://code.google.com/p/selenium/wiki/InternetExplorerDriver.
here's the code
package AutomationFrameWork;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;
public class Parallelized extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService executor;
public ThreadPoolScheduler() {
String threads = System.getProperty("junit.parallel.threads", "16");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}
#Override
public void finished() {
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
#Override
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
}
}
public Parallelized(Class<?> klass) throws Throwable {
super(klass);
setScheduler(new ThreadPoolScheduler());
}
}
package AutomationFrameWork;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
#RunWith(Parallelized.class)
public class JUnitParallel {
private String platform;
private String browserName;
private String browserVersion;
private WebDriver driver;
#Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
env.add(new String[]{Platform.WINDOWS.toString(), "chrome", "27"});
env.add(new String[]{Platform.WINDOWS.toString(),"firefox","20"});
env.add(new String[]{Platform.WINDOWS.toString(),"ie","11"});
env.add(new String[]{Platform.WINDOWS.toString(),"safari","5.1.7"});
//add more browsers here
return env;
}
public JUnitParallel(String platform, String browserName, String browserVersion) {
this.platform = platform;
this.browserName = browserName;
this.browserVersion = browserVersion;
}
#Before
public void setUp() throws Exception {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("platform", platform);
capability.setCapability("browser", browserName);
capability.setCapability("browserVersion", browserVersion);
capability.setCapability("build", "JUnit-Parallel");
capability.setCapability("InternetExplorerDriverServer.IE_ENSURE_CLEAN_SESSION",true);
System.setProperty("webdriver.ie.driver",
"C:\\Users\\path to driver\\IEDriverServer.exe");
driver = new RemoteWebDriver(
new URL("http://localhost:7777".concat("/wd/hub")),
capability
);
}
#Test
public void testSimple() throws Exception {
driver.get("http://www.google.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
driver = new Augmenter().augment(driver);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("Screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}