I'm attempting to display an inline image in a Java JEditorPane. The code below uses HTML content that properly displays the image in Firefox, but not in the JEditorPane. Any ideas why? Thanks.
import javax.swing.*;
import java.awt.*;
public class InlineImage {
public InlineImage() {
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane edit=new JEditorPane();
frame.getContentPane().add(edit);
edit.setContentType("text/html");
String html = "<html><body>Local image<br><img src=\"data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyCAYAAACqNX6+AAACeklEQVR42u1bHZBCURgNgiBYCINgIVhYCIKFhSBYCIIgCIKFxSBoZpsJgjAIgmAhCIIgCIKFIAiChSAIF4IgCL7d82abnWl69Xq9+7r1Dhyp93PfOff7ufd+n8/nEyF0AkmgIAQFoSDEjQgSCn1LPD6SbPZDSqWKNBqv0m5nZDh8lsnkUebziIH1OiC/d+wF/tteN50+GPfiGbVaQcrld8nnm8Y78C4K8odAYC3R6Jfkci2pVosGaYtFWDYbvynRKgDx8G4Ij7FgTBjbzQuC2ZhOd4wZCgIOzfBLYysSxooxh8OL2xAEH4KPGo3irs98pwF3CZcXi42vS5CtCPiAaxfBDLPZvRQKNUWW49CDEomBdDrpmxXBDN1uSlKprvj9m8sLgkHAx47HMU+JYObSkBmenxDYvDGTaRum63UhdoFUG9maa4IgW4KZkvzD6PVebMaYEy6GSS6XdyTcIlaroA1rsRgr6vU3zwVsp4BFZzC4ckYQBCmYH4k9D4NBwmLAP2IZFMNZUY6nxwf+rFRKJNJhYLVvSxAs9Bgz1ADcniQIzIprDLVbL+aua8+PyWSfxCkGOLYsSKuVI2mKAY4tC4LlP0lTv8ViWRAS5g4oyLUKQpelmctiUNcsqDPt1Szt5cJQs4Uht0402zrh5qKGm4tb19XvJ0mkq2ciPKC6ngOq3SNcEms/xXXsCJdFDhoWOeyWAdGFWSsDikTm7hXKwVq4VjEvlLNfWnpmKSkqGFlK+l9Kaj1WuFBs7cWKRrgmbYqtvdyOUCxW9W5HOCQOXBobdtjSxpY2J5o+L0W+55o+7bZFN5t5JW3RT0+fbIsmKAgFISgIBSHU4QdCoO0W7Xd4AwAAAABJRU5ErkJggg==\"></body></html>";
edit.setText(html);
frame.setSize(500,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {new InlineImage();}
}
You need to add a protocol handler for "data:" so an URL/URLConnection can be opened for it. Alternatively you could create some protocol handler "resource:" for class path resources.
You need a package data with a class Handler (fixed name convention!). This will be the factory class for "data:" return an URLConnection. We will create DataConnection for that.
Installing a protocol handler can be done via System.setProperty. Here I provided Handler.install(); to do that in a generic way.
package test1.data;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return new DataConnection(u);
}
public static void install() {
String pkgName = Handler.class.getPackage().getName();
String pkg = pkgName.substring(0, pkgName.lastIndexOf('.'));
String protocolHandlers = System.getProperty("java.protocol.handler.pkgs", "");
if (!protocolHandlers.contains(pkg)) {
if (!protocolHandlers.isEmpty()) {
protocolHandlers += "|";
}
protocolHandlers += pkg;
System.setProperty("java.protocol.handler.pkgs", protocolHandlers);
}
}
}
The URLConnection gives an InputStream to the bytes:
package test1.data;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.bind.DatatypeConverter;
public class DataConnection extends URLConnection {
public DataConnection(URL u) {
super(u);
}
#Override
public void connect() throws IOException {
connected = true;
}
#Override
public InputStream getInputStream() throws IOException {
String data = url.toString();
data = data.replaceFirst("^.*;base64,", "");
System.out.println("Data: " + data);
byte[] bytes = DatatypeConverter.parseBase64Binary(data);
return new ByteArrayInputStream(bytes);
}
}
The clever thing here is to use Base64 decoding of DatatypeConverter in standard Java SE.
P.S.
Nowadays one would use Base64.getEncoder().encode(...).
Related
I am trying to use "MiniKdc" in my code implementation like "MiniKdc.main(config)" but am getting error "can not resolve symbol 'MiniKdc' ".
I am following this example https://www.baeldung.com/spring-security-kerberos-integration
i have added this dependecy in my build.gradle
implementation 'org.springframework.security.kerberos:spring-security-kerberos-test:1.0.1.RELEASE'
i tried to search the dependecy from maven central/repository and i can't find it.
here is the class i am working on, i want to be able to import Minikdc in the second import statement.
import org.apache.commons.io.FileUtils;
import org.springframework.security.kerberos.test.MiniKdc;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
class KerberosMiniKdc {
private static final String KRB_WORK_DIR = ".\\spring-security-sso\\spring-security-sso-kerberos\\krb-test-workdir";
public static void main(String[] args) throws Exception {
String[] config = MiniKdcConfigBuilder.builder()
.workDir(prepareWorkDir())
.confDir("minikdc-krb5.conf")
.keytabName("example.keytab")
.principals("client/localhost", "HTTP/localhost")
.build();
MiniKdc.main(config);
}
private static String prepareWorkDir() throws IOException {
Path dir = Paths.get(KRB_WORK_DIR);
File directory = dir.normalize().toFile();
FileUtils.deleteQuietly(directory);
FileUtils.forceMkdir(directory);
return dir.toString();
}
}
is there anything am doing wrong?
As of 2021, spring-security-kerberos is not well maintained.
I suggest using Apache Kerby instead, either directly or via other library like Kerb4J. See an example here.
package com.kerb4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.kerby.kerberos.kerb.client.KrbConfig;
import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import java.io.File;
public class KerberosSecurityTestcase {
private static final Log log = LogFactory.getLog(KerberosSecurityTestcase.class);
private static int i = 10000;
protected int kdcPort;
private SimpleKdcServer kdc;
private File workDir;
private KrbConfig conf;
#BeforeAll
public static void debugKerberos() {
System.setProperty("sun.security.krb5.debug", "true");
}
#BeforeEach
public void startMiniKdc() throws Exception {
kdcPort = i++;
createTestDir();
createMiniKdcConf();
log.info("Starting Simple KDC server on port " + kdcPort);
kdc = new SimpleKdcServer(workDir, conf);
kdc.setKdcPort(kdcPort);
kdc.setAllowUdp(false);
kdc.init();
kdc.start();
}
#AfterEach
public void stopMiniKdc() throws Exception {
log.info("Stopping Simple KDC server on port " + kdcPort);
if (kdc != null) {
kdc.stop();
log.info("Stopped Simple KDC server on port " + kdcPort);
}
}
public void createTestDir() {
workDir = new File(System.getProperty("test.dir", "target"));
}
public void createMiniKdcConf() {
conf = new KrbConfig();
}
public SimpleKdcServer getKdc() {
return kdc;
}
public File getWorkDir() {
return workDir;
}
public KrbConfig getConf() {
return conf;
}
}
Disclaimer: I'm the author of Kerb4J
How to call screenshot method from one class to other class?
How to take screenshot home page after logging in to my code?
Below are the classes:-
Properties class:
package basepackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.io.FileHandler;
public class PropertiesClass extends BaseClass {
public static String propfile(String username) throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\pushk\\eclipse-workspace\\com.org.swag\\config.prop");
prop.load(fis);
return prop.getProperty(username);
}
public static void loginscreenshot() throws Exception {
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileHandler.copy(file, new File("C:\\Users\\pushk\\eclipse-workspace\\com.org.swag\\Screenshots.png"));
}
LoginPageClass:
package com.org.swag.Page;
import org.openqa.selenium.support.PageFactory;
import com.org.swag.pageobject.LoginPageObjects;
import basepackage.BaseClass;
import basepackage.PropertiesClass;
public class LoginPage extends BaseClass {
public void loginpage() throws Exception {
LoginPageObjects lpo = PageFactory.initElements(driver, LoginPageObjects.class);
lpo.username.sendKeys(PropertiesClass.propfile("username"));
lpo.password.sendKeys(PropertiesClass.propfile("password"));
lpo.loginsubmit.click();
lpo.menu.click();
lpo.logout.click();
}
}
Simply call the static screenshot method from another class (which imports basepackage.PropertiesClass) at the desired step. In your code, add the call after logging in:
LoginPageObjects lpo = PageFactory.initElements(driver, LoginPageObjects.class);
lpo.username.sendKeys(PropertiesClass.propfile("username"));
lpo.password.sendKeys(PropertiesClass.propfile("password"));
lpo.loginsubmit.click();
PropertiesClass.loginscreenshot();
lpo.menu.click();
lpo.logout.click();
I have below code for making a POST call to RestAPI for Tableau system, which is working and seeing response output.
However, I would like to capture cookie from this output and need to be used for further consumption! Can somebody help me on this problem?
Code:
package com.abc.it.automation.service;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Properties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity.HeadersBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import com.abc.it.automation.utils.SSLUtil;
public class BIaaSTableauService {
private static Properties tableau_properties = new Properties();
static {
// Loads the values from configuration file into the Properties instance
try {
tableau_properties.load(new FileInputStream("res/config.properties"));
} catch (IOException e) {
System.out.println(e);
}
}
private static final String loginURL = tableau_properties.getProperty("server.host");
private static final String siteSearchURL = tableau_properties.getProperty("site.search.url");
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException {
RestTemplate restTableau = new RestTemplate();
String requestLogin = "<tsRequest>"+
"<credentials name=\"svc_tableau\" password=\"xxxxxxxxx\" >"+
"<site contentUrl=\"\"/>"+
"</credentials>"+
"</tsRequest>";
SSLUtil.turnOffSslChecking();
ResponseEntity<String> responseLogin = restTableau.postForEntity(loginURL, requestLogin, String.class);
System.out.println(responseLogin.getBody());
You need to build your RestTemplate as follows.
RestTemplate restTableau = new RestTemplate(new MyClientHttpRequestFactory());
Extend ClientHttpRequestFactory as follows.
public class MyClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private Cookie cookie;
//setters and getters.
#Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
this.setCookie(connection.getRequestProperty("Cookie"));
}
}
This code was mostly taken from Pentaho's website on sample programs. The goal is to use their API to generate HTML output with a Pentaho report.
The report was created with Pentaho 3.5.0-RC2
The version of jars I am using are the following:
pentaho-reporting-engine-classic-core-3.5.0-RC2.jar
libloader-1.1.1.jar
libbase-1.1.1.jar
The exception I am getting is the following:
org.pentaho.reporting.libraries.resourceloader.ContentNotRecognizedException: None of the selected factories was able to handle the given data: ResourceKey{schema=org.pentaho.reporting.libraries.resourceloader.loader.URLResourceLoader, identifier=file:/C:/Users/elias.kopsiaftis/workspace_experimental/TestPentahoReport/bin/Test.prpt, factoryParameters={}, parent=null}
at org.pentaho.reporting.libraries.resourceloader.DefaultResourceManagerBackend.create(DefaultResourceManagerBackend.java:295)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:387)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:342)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.createDirectly(ResourceManager.java:205)
at ReportTester.getReportDefinition(ReportTester.java:74)
at ReportTester.getReport(ReportTester.java:25)
at ReportTester.main(ReportTester.java:84)
java.lang.NullPointerException
at ReportTester.getReport(ReportTester.java:26)
at ReportTester.main(ReportTester.java:84)
And finally, the code snippet!
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.io.*;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlReportUtil;
import org.pentaho.reporting.libraries.resourceloader.Resource;
import org.pentaho.reporting.libraries.base.util.StackableException;
import org.pentaho.reporting.libraries.resourceloader.ResourceException;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
public class ReportTester {
private String reportName = "FormCompleteUsagePerPartnerByMonth.prpt";
private String reportPath = "";
public void getReport() {
try {
final MasterReport report = getReportDefinition();
report.getParameterValues().put("partner", "");
report.getParameterValues().put("startingdate", "2015-03-01");
report.getParameterValues().put("endingdate", "2015-03-05");
HtmlReportUtil.createStreamHTML(report, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
private MasterReport getReportDefinition() {
try {
// Using the classloader, get the URL to the reportDefinition file
final ClassLoader classloader = this.getClass().getClassLoader();
final URL reportDefinitionURL = classloader.getResource(reportPath + reportName);
if(reportDefinitionURL == null) {
System.out.println("URL was null");
}
// Parse the report file
final ResourceManager resourceManager = new ResourceManager();
resourceManager.registerDefaults();
final Resource directly = resourceManager.createDirectly(reportDefinitionURL, MasterReport.class);
return (MasterReport) directly.getResource();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
ReportTester rt = new ReportTester();
rt.getReport();
}
}
Any advice on this would be much appreciated as I have been scratching my head on this all day. Thanks in advance!
I am trying to add the failed methodName to the screenshot that is taken when a failure occurs while running selenium using java. Ive tried multiple solutions around the net but they all wind up returning the methodName of the rule class or methodName. I am not sure how to make it so the screenshot file name returns 'shouldFail_date.png'.
package test;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ScreenShotRule extends TestWatcher {
private WebDriver browser;
public ScreenShotRule(WebDriver browser) {
this.browser = browser;
}
#Override
protected void failed(Throwable e, Description description) {
TakesScreenshot takesScreenshot = (TakesScreenshot) browser;
File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
File destFile = getDestinationFile();
try {
FileUtils.copyFile(scrFile, destFile);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
#Override
protected void finished(Description description) {
browser.close();
}
private File getDestinationFile() {
Throwable t = new Throwable();
String callerMethodName = t.getStackTrace()[1].getMethodName();
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy");
String userDirectory = "screenshots/" + dateFormat.format(new Date()) + "/";
new File(userDirectory).mkdirs();
String absoluteFileName = userDirectory callerMethodName + dateFormat.format(new Date()) + ".png";
return new File(absoluteFileName);
}
}
package test;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotTest {
private WebDriver browser = new FirefoxDriver();
#Rule
public ScreenShotRule screenShootRule = new ScreenShotRule(browser);
#Test
public void shouldFail() {
browser.get("http://www.google.com");
By link = By.partialLinkText("I do not expect to find a link with this text");
browser.findElement(link);
}
}
You can use one of the efficient selenium testing-frameworks - ISFW that is based on testng and provides descriptive reporting with the need you have. Here are some of the snapshots
Overview
Detail Report