JavaFX Application : cannot find SunPKCS11 class - javafx

I am developing a JavaFX application used to sign pdf using eToken Pro. The sign methods run perfectly in a normal Java project. While when run in the JavaFX application, it keeps encountering exceptions like this:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NoClassDefFoundError: sun/security/pkcs11/SunPKCS11
at javafxapplication3.JavaFXApplication3.start(JavaFXApplication3.java:21)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
Caused by: java.lang.ClassNotFoundException: sun.security.pkcs11.SunPKCS11
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 12 more
Java Result: 1
the codes I used to sign pdf are as follows:
#Override
public void start(Stage primaryStage) {
Signer signer = new Signer(new File("C:/Users/Adam/Desktop/pdf/hello.pdf"));
signer.signWithToken(true);
}
the codes of class Signer are as follows:
public class Signer {
// define the file to be signed
private final File file;
private static String smartcardDllPath;
private static int level;
private static String reason;
private static String src;
private static String dest;
private static String location;
private static Collection<CrlClient> crlList;
private static OcspClient ocspClient;
private static TSAClient tsaClient;
private static final String DLL = "C:/Windows/System32/eTPKCS11.dll";
public Signer(File theFile) {
location = "HK SAR";
smartcardDllPath = null;
file = theFile;
}
public void signWithToken(boolean certified) {
try {
String config = "name=eToken\nlibrary=" + DLL + "\nslotListIndex=" + getSlotsWithTokens(DLL)[0];
ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
Provider providerPKCS11 = new SunPKCS11(bais);
Security.addProvider(providerPKCS11);
configureParameters(certified);
// create PdfSignatureAppearance
PdfSignatureAppearance appearance = getPdfSigAppearance();
// configure the keystore, alias, private key and certificate chain
char[] pin = "love4Sakura".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, pin);
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, null);
Certificate[] chain = ks.getCertificateChain(alias);
printChainInfo(chain);
// configure the CRL, OCSP and TSA
configCrlOcspTsa(chain);
// create the signature
ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "SunPKCS11-eToken");
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, pks, chain, crlList, ocspClient,
tsaClient, 0, MakeSignature.CryptoStandard.CMS);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static long[] getSlotsWithTokens(String libraryPath) {
CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
String functionList = "C_GetFunctionList";
initArgs.flags = 0;
PKCS11 tmpPKCS11 = null;
long[] slotList = null;
try {
try {
tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, false);
System.out.println(tmpPKCS11.toString());
} catch (IOException ex) {
try {
throw ex;
} catch (IOException ex1) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex1);
}
}
} catch (PKCS11Exception e) {
try {
initArgs = null;
tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, true);
} catch (IOException | PKCS11Exception ex) {
}
}
try {
slotList = tmpPKCS11.C_GetSlotList(true);
for (long slot : slotList) {
CK_TOKEN_INFO tokenInfo = tmpPKCS11.C_GetTokenInfo(slot);
System.out.println("slot: " + slot + "\nmanufacturerID: "
+ String.valueOf(tokenInfo.manufacturerID) + "\nmodel: "
+ String.valueOf(tokenInfo.model));
}
} catch (PKCS11Exception ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
}
return slotList;
}
Before you guys answer: I want to emphasize that I reference the Signer class in a normal Java Project perfectly. So I donn't think it's a 32-bit or 64-bit problem. Plus, I am using the 32-bit JDK 1.7

This issue can be because unsupported version of java.Do one thing download particular jar file for that and include it on your project it'll work for you.
You can download the jar from this link -
http://www.docjar.com/jar/sunpkcs11.jar

I was also getting the same error -
java.lang.ClassNotFoundException: sun.security.pkcs11.SunPKCS11
Adding the following dependency in pom.xml helped me -
<dependency>
<groupId>sunpkcs11</groupId>
<artifactId>sunpkcs11</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>/Library/Java/JavaVirtualMachines/jdk1.8.0_341.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar</systemPath>
</dependency>
In <systemPath>...</systemPath>, give the appropriate path of sunpkcs11.jar from your system.

Related

How to get #FindAll working for InternetExplorer WebDriver with Selenium

I am trying to run a TestNG Suite against Internet Explorer. However, it seems to be failing trying to find an element on the webpage using the CSS locator. I am using the #FindAll annotation to specify multiple locating strategies and these strategies work fine for Chrome and Firefox. Here is the error I am seeing in the TestNG failure summary:
org.openqa.selenium.WebDriverException: (WARNING: The server did not
provide any stacktrace information) Command duration or timeout: 70
milliseconds Build info: version: '2.53.0', revision: '35ae25b', time:
'2016-03-15 17:00:58' System info: host: '(hostname was here-omitted)', ip:
'10.18.28.53', os.name: 'Windows 10', os.arch: 'amd64', os.version:
'10.0', java.version: '1.8.0_91' Driver info:
org.openqa.selenium.ie.InternetExplorerDriver Capabilities
[{browserAttachTimeout=0, ie.enableFullPageScreenshot=true,
enablePersistentHover=true, ie.forceCreateProcessApi=false,
ie.forceShellWindowsApi=false, pageLoadStrategy=normal,
ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000, version=11,
platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false,
elementScrollBehavior=0, ie.browserCommandLineSwitches=,
requireWindowFocus=false, browserName=internet explorer,
initialBrowserUrl=http://localhost:28843/, javascriptEnabled=true,
ignoreProtectedModeSettings=false, enableElementCacheCleanup=true,
unexpectedAlertBehaviour=dismiss}] Session ID:
3ccb2fc8-aac7-484c-8a0d-ca8c8539742e
*** Element info: {Using=css selector, value=#content > div.container > h1} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
Source) at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Source) at java.lang.reflect.Constructor.newInstance(Unknown Source)
at
org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at
org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at
org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:388)
at
org.openqa.selenium.remote.RemoteWebDriver.findElementsByCssSelector(RemoteWebDriver.java:496)
at org.openqa.selenium.By$ByCssSelector.findElements(By.java:441) at
org.openqa.selenium.support.pagefactory.ByAll.findElements(ByAll.java:63)
at
org.openqa.selenium.support.pagefactory.ByAll.findElement(ByAll.java:52)
at
org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy13.getText(Unknown Source) at
com.webcp.common.pageobjects.LoginPage.getLoginTextTop(LoginPage.java:58)
at
com.webcp.common.pageobjects.LoginPage.verifyLoginTextTop(LoginPage.java:65)
at
com.webcp.common.tests.LoginPageTest.verifyLoginPage(LoginPageTest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816) at
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124) at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774) at
org.testng.TestRunner.run(TestRunner.java:624) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:359) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:312) at
org.testng.SuiteRunner.run(SuiteRunner.java:261) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1215) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1140) at
org.testng.TestNG.run(TestNG.java:1048) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)
And here is the code block that is running:
TestBaseSetup class snippet:
public class TestBaseSetup
{
private static WebDriver driver;
private static Logger Log = Logger.getLogger(TestBaseSetup.class.getName());
static String driverPath = "C:\\Users\\bberndt\\eclipse\\Selenium Files\\";
public static WebDriver getDriver()
{
return driver;
}
private static WebDriver initIEDriver(String appURL)
{
Log.info("Launching Microsoft Internet Explorer with new profile");
File file = new File(driverPath + "IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
Log.info("Driver instantiated");
driver.manage().window().maximize();
Log.info("Window maximized");
driver.get(appURL);
Log.info("Navigating to: " + appURL);
return driver;
}
}
LoginPageTest Class:
public class LoginPageTest extends TestBaseSetup
{
private WebDriver driver;
private LoginPage loginPage;
private HomePage homePage;
private SoftAssert softAssert;
private static Logger Log = Logger.getLogger(LoginPageTest.class.getName());
private String sTestCaseName;
private int iTestCaseRow;
#BeforeMethod
public void setUpTest()
{
driver = getDriver();
Log.info("Driver loaded");
//loginPage = new LoginPage(driver);
loginPage = PageFactory.initElements(driver, LoginPage.class);
homePage = PageFactory.initElements(driver, HomePage.class);
softAssert = new SoftAssert();
}
#Test(priority = 1)
public void verifyLoginPage()
{
Log.info("--------------------------START TEST---------------------------");
Log.info("Test 1: verifyLoginPage");
softAssert.assertTrue(loginPage.verifyLoginPageTitle(), "Login page title does not match\n");
softAssert.assertTrue(loginPage.verifyLoginTextTop(), "Login text top does not match\n");
softAssert.assertTrue(loginPage.verifyLoginTextBottom(), "Login text bottom does not match\n");
softAssert.assertAll();
}
}
LoginPage object Repository:
public class LoginPage
{
protected WebDriver driver;
private static Logger Log = Logger.getLogger(LoginPage.class.getName());
#FindAll({ #FindBy(xpath = "/html/body/div/div/div/h1"),
#FindBy(css = "#content > div.container > h1") })
private WebElement loginTextTop;
#FindAll({ #FindBy(xpath = "/html/body/div/div/div/h2"),
#FindBy(css = "h2") })
private WebElement loginTextBottom;
public LoginPage(WebDriver driver)
{
this.driver = driver;
}
public String getPageTitle()
{
String title = driver.getTitle();
return title;
}
public boolean verifyLoginPageTitle()
{
String expectedPageTitle = "WTS";
return getPageTitle().contains(expectedPageTitle);
}
public String getLoginTextTop()
{
String TextTop = loginTextTop.getText();
return TextTop;
}
public boolean verifyLoginTextTop()
{
String expectedPageText = "Welcome to CenterPointâ„¢";
return getLoginTextTop().contains(expectedPageText);
}
public String getLoginTextBottom()
{
String TextBottom = loginTextBottom.getText();
return TextBottom;
}
public boolean verifyLoginTextBottom()
{
String expectedPageText = "Please Sign In";
return getLoginTextBottom().contains(expectedPageText);
}
}
Turns out that this was not an issue with the code. Rather, there was a setting in Internet Options that needed to be turned on in order to make it work.
Advanced > Settings > Security > Allow active content to run in files on My Computer.
Once I checked this box, my IE test worked as expected.

Spring MVC Multipart file upload random FileNotFoundException

I built a web application using spring MVC, everything is working fine except the file upload in which I got random FileNotFoundExceptions. I found some solutions online like using a different tmp folder but I keep getting random error.
My code is:
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("file") final MultipartFile multipartFile,
#RequestHeader("email") final String email, #RequestHeader("password") String password){
if (authenticateUser(email, password)) {
if (!multipartFile.isEmpty()) {
System.out.println("Start processing");
Thread thread = new Thread(){
public void run(){
ProcessCSV obj = new ProcessCSV();
try {
File file = multipartToFile(multipartFile);
if(file !=null) {
obj.extractEvents(file, email, cluster, session);
}
else {
System.out.println("null File");
}
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
}
}
};
thread.start();
return "true";
} else {
return "false";
}
}
else {
return "false";
}
}
and:
public File multipartToFile(MultipartFile multipartFile) throws IOException {
File uploadFile = null;
if(multipartFile != null && multipartFile.getSize() > 0) {
uploadFile = new File("/tmp/" + multipartFile.getOriginalFilename());
FileOutputStream fos = null;
try {
uploadFile.createNewFile();
fos = new FileOutputStream(uploadFile);
IOUtils.copy(multipartFile.getInputStream(), fos);
} catch (FileNotFoundException e) {
System.out.println("File conversion error");
e.printStackTrace();
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
}
}
}
}
else {
System.out.println("null MultipartFile");
}
return uploadFile;
}
and the configuration file:
multipart.maxFileSize: 100MB
multipart.maxRequestSize: 100MB
multipart.location = ${user.home}
server.port = 8090
I used different versions of the multipartToFile function, one was using multipartfile.transferTo() but I was getting the same random error. Any advice?
Thank you
EDIT stack trace:
java.io.IOException: java.io.FileNotFoundException: /Users/aaa/upload_07720775_4b37_4b86_b370_40280388f3a4_00000003.tmp (No such file or directory)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:121)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.transferTo(StandardMultipartHttpServletRequest.java:260)
at main.RESTController.multipartToFile(RESTController.java:358)
at main.RESTController$1.run(RESTController.java:241)
Caused by: java.io.FileNotFoundException: /Users/aaa/upload_07720775_4b37_4b86_b370_40280388f3a4_00000003.tmp (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:392)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:119)
... 3 more
I had just had a night of terror with this error. I found out that MultiPartFile is only recognisable to and by the #Controller class. So if you pass it to another bean which is not a controller, Spring will not be able to help you. It somewhat makes sense that the #Controller is tightly bound to the front screen (communication from the browser to the system - Controllers are the entry point from the browser). So any conversation must happen there in the Controller.
In my case, I did something like the following:
#Controller
public class FileUploadingController{
#PostMapping("/uploadHistoricData")
public String saveUploadedDataFromBrowser(#RequestParam("file") MultipartFile file) {
try {
String pathToFile = "/home/username/destination/"
new File(pathToFile).mkdir();
File newFile = new File(pathToFile + "/uploadedFile.csv");
file.transferTo(newFile); //transfer the uploaded file data to a java.io.File which can be passed between layers
dataService.processUploadedFile( newFile);
} catch (IOException e) {
//handle your exception here please
}
return "redirect:/index?successfulDataUpload";
}
}`
I had the same problem, it looks like MultipartFile is using different current dir internally, so all not absolute paths are not working.
I had to convert my path to an absolute path and then it worked.
It is working inside #RestController and in other beans too.
Path path = Paths.get(filename).toAbsolutePath();
fileToImport.transferTo(path.toFile());
fileToImport is MultipartFile.

How to call EJB from another app on the same server?

I have java SE sample client which run on desktop (code below). But I have access to WebSphere were called EJB is deployed. How to rewrite below code to work on WebSphere? (When I leave this code just like it is program works but I think this can be done more simple and clear)
Main method:
WSConn connection = new WSConn();
final Plan plan = connection.getPlanBean();
com.ibm.websphere.security.auth.WSSubject.doAs(connection.getSubject(), new java.security.PrivilegedAction<Object>() {
public Object run() {
try {
// App logic
} catch (Throwable t) {
System.err.println("PrivilegedAction - Error calling EJB: " + t);
t.printStackTrace();
}
return null;
}
}); // end doAs
WSConn class:
public class WSConn {
private static final String INITIAL_CONTEXT_FACTORY = "com.ibm.websphere.naming.WsnInitialContextFactory";
private static final String JAAS_MODULE = "WSLogin";
private static final String MODEL_EJB_NAME_LONG = "ejb/com/ibm/ModelHome";
private static final String PLAN_EJB_NAME_LONG = "ejb/com/ibm/PlanHome";
private Subject subject;
private InitialContext initialContext;
private String serverName;
private String serverPort;
private String uid;
private String pwd;
private String remoteServerName;
private Model modelBean;
private Plan planBean;
public WSConn() {
Properties props = new Properties();
try {
props.load(WSConn.class.getClassLoader().getResourceAsStream("WSConn.properties"));
} catch (IOException e) {
e.printStackTrace();
}
serverName = props.getProperty("WSConn.serverName");
serverPort = props.getProperty("WSConn.serverPort");
uid = props.getProperty("WSConn.userID");
pwd = props.getProperty("WSConn.password");
remoteServerName = props.getProperty("WSConn.remoteServerName");
}
private void init() {
if (subject == null || initialContext == null) {
subject = login();
}
}
private Subject login() {
Subject subject = null;
try {
LoginContext lc = null;
// CRATE LOGIN CONTEXT
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "corbaloc:iiop:" + serverName + ":" + serverPort);
initialContext = new InitialContext(env);
// Just to test the connection
initialContext.lookup("");
lc = new LoginContext(JAAS_MODULE, new WSCallbackHandlerImpl(uid, pwd));
lc.login();
subject = lc.getSubject();
} catch (javax.naming.NoPermissionException exc) {
System.err.println("[WSConn] - Login Error: " + exc);
} catch (Exception exc) {
System.err.println("[WSConn] - Error: " + exc);
}
return subject;
}
public wModel getModelBean() {
if (modelBean == null) {
init();
modelBean = (wModel) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wModel>() {
public wModel run() {
wModel session = null;
try {
Object o = initialContext.lookup(MODEL_EJB_NAME_LONG);
wModelHome home = (wModelHome) PortableRemoteObject.narrow(o, wModelHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting model bean: " + exc);
}
return session;
}
}); // end doAs
}
return modelBean;
}
public wPlan getPlanBean() {
if (planBean == null) {
init();
planBean = (wPlan) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wPlan>() {
public wPlan run() {
wPlan session = null;
try {
Object o = initialContext.lookup(PLAN_EJB_NAME_LONG);
wPlanHome home = (wPlanHome) PortableRemoteObject.narrow(o, wPlanHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting plan bean: " + exc);
}
return session;
}
}); // end doAs
}
return planBean;
}
public Subject getSubject() {
if (subject == null) {
init();
}
return subject;
}
}
As indicated in another answer, the classic mechanism is to lookup and narrow the home interface.
Get the initial context
final InitialContext initialContext = new InitialContext();
Lookup for the home by jndi name, specifying either the full jndi name
Object obj = initialContext.lookup("ejb/com/ibm/tws/conn/plan/ConnPlanHome");
or you can create e reference in your WAR and use java:comp/env/yourname
Then narrow the home to the home interface class
ConnPlanHome planHome = (ConnPlanHome)PortableRemoteObject.narrow(obj, ConnPlanHome.class);
and then create the EJB remote interface
ConnPlan plan = planHome.create();
The about calls should work for IBM Workload Scheduler distributed.
For IBM Workload Scheduler z/OS the JNDI name and the class names are different:
final InitialContext initialContext = new InitialContext();
String engineName = "XXXX";
Object obj = initialContext.lookup("ejb/com/ibm/tws/zconn/plan/ZConnPlanHome");
ZConnPlanHome planHome = (ZConnPlanHome)PortableRemoteObject.narrow(obj, ZConnPlanHome.class);
ZConnPlan plan = planHome.create(engineName);
User credentials are propagated from the client to the engine, the client need to be authenticated otherwise the engine will reject the request.
If you're trying to access an EJB from a POJO class, then there is nothing more simple than lookup+narrow. However, if the POJO is included in an application (EAR or WAR), then you could declare and lookup an EJB reference (java:comp/ejb/myEJB), and then the container would perform the narrow rather than your code. If you change your code to be a managed class like a servlet, another EJB, or a CDI bean, then you could use #EJB injection, and then you would not even need a lookup.

Spring MockMvc multipart reading in zip file IOException: Stream closed

I want to test a Multipart controller that reads a zip file in and goes through all of the entries. Here's the controller method that does it:
#RequestMapping(value = "/content/general-import", method = RequestMethod.POST)
public ModelAndView handleGeneralUpload(
#RequestParam("file") MultipartFile file) throws IOException {
String signature = "RETAILER_GROUP:*|CHANNEL:*|LOCALE:de-AT|INDUSTRY:5499";
LOG.info("Processing file archive: {} with signature: {}.", file.getName(), signature);
ModelAndView mav = new ModelAndView();
mav.setViewName("contentUpload");
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
// process each file, based on what it is and whether its a directory etc.
if (!entry.isDirectory()) {
// if the entry is a file, extract it
LOG.debug("Processing entry: {}",entry.getName());
int length = (int) entry.getSize();
Content contentToSave = null;
if(entry.getName().contains("gif")) {
contentToSave = Content.makeImage(entry.getName(), Content.GIF, signature, getBytesFrom(zis, "gif"));
} else if (entry.getName().contains("png")) {
contentToSave = Content.makeImage(entry.getName(), Content.PNG, signature, getBytesFrom(zis, "png"));
} else if (entry.getName().contains("jpeg")) {
contentToSave = Content.makeImage(entry.getName(), Content.JPEG, signature, getBytesFrom(zis, "jpeg"));
} else if (entry.getName().contains("json")) {
contentToSave = Content.makeFile(entry.getName(), Content.JSON, signature, getStringFrom(zis, length));
} else if (entry.getName().contains("js")) {
contentToSave = Content.makeFile(entry.getName(), Content.JS, signature, getStringFrom(zis, length));
} else if (entry.getName().contains("css")) {
contentToSave = Content.makeFile(entry.getName(), Content.CSS, signature, getStringFrom(zis, length));
}
Content contentAleadyThere = contentService.fetch(entry.getName());
if(contentAleadyThere != null) {
LOG.warn("Replacing file: {} with uploaded version.", contentToSave.getName());
}
contentService.put(contentToSave);
LOG.info("Persisted file: {} from uploaded version.", contentToSave.getName());
}
}
mav.addObject("form", UploadViewModel.make("/content/general-import", "Updated content with file"));
return mav;
} else {
mav.addObject("form", UploadViewModel.make("/content/general-import", "Could not update content with file"));
return mav;
}
}
Now the associated test is as follows:
#Test
public void testProcessingGeneralUpload() throws Exception {
Resource template = wac.getResource("classpath:lc_content/content.zip");
MockMultipartFile firstFile = new MockMultipartFile(
"file", "filename.zip", MediaType.APPLICATION_OCTET_STREAM_VALUE, template.getInputStream());
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/content/general-import")
.file(firstFile))
.andExpect(status().isOk())
.andExpect(view().name("contentUpload"))
.andExpect(model().attributeExists("form")).andReturn();
// processing assertions
ModelMap modelMap = mvcResult.getModelAndView().getModelMap();
Object object = modelMap.get("form");
assertThat(object, is(not(nullValue())));
assertThat(object, is(instanceOf(UploadViewModel.class)));
UploadViewModel addModel = (UploadViewModel) object;
assertThat(addModel.getMessage(), is(notNullValue()));
assertThat(addModel.getPostUrl(), is(notNullValue()));
assertThat(addModel.getPostUrl(), is("/content/general-import"));
assertThat(addModel.getMessage(), is("Updated content with file"));
// persistence assertions
}
The error I get is:
java.io.IOException: Stream closed
at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:67)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:116)
at com.touchcorp.touchpoint.resource.mvc.ContentUploadResource.handleGeneralUpload(ContentUploadResource.java:221)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:170)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:137)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
at com.touchcorp.touchpoint.resource.mvc.ContentUploadResourceUnitTest.testProcessingGeneralUpload(ContentUploadResourceUnitTest.java:190)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
What seems to be the issue is that I can't seem to construct the MockMultipartFile in the right state. I guess one work around is to refactor all of the processing logic into a separate method and test it out-of-container, but I'd rather keep the logic all in one place. Can anyone tell me how to instantiate the MockMultipartFile so that it can read the content.zip?
Found the answer, I needed to replace the line:
MockMultipartFile firstFile = new MockMultipartFile(
"file", "filename.zip", MediaType.APPLICATION_OCTET_STREAM_VALUE, template.getInputStream());
with:
MockMultipartFile firstFile = new MockMultipartFile(
"file", "filename.zip", MediaType.APPLICATION_OCTET_STREAM_VALUE, new ZipInputStream(template.getInputStream()));
Although, I now have a new problem: the file is empty, in other words: file.isEmpty() in the controller returns true.
EDIT
and this too has an answer, I replaced the line again with:
MockMultipartFile firstFile = new MockMultipartFile(
"file", "content.zip", MediaType.APPLICATION_OCTET_STREAM_VALUE, extractFile(template.getFile()));
where extractFile is:
private byte[] extractFile(File zipFile) throws IOException {
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
System.out.println("length of file: " + zipFile.length());
byte[] output = null;
try {
byte[] data = new byte[(int)zipFile.length()];
zipIn.read(data);
zipIn.close();
output = data;
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
It seems that I need to read in all the data from the stream in order for the bytes to be filled. However it is still not solved, but see: How to go from spring mvc multipartfile into zipinputstream for discussion on that.

JSch/SSHJ - Connecting to SSH server on button click

I'm trying to connect to SSH Unix server on button click (code written in actionPerformed() method). I'm using JSch for connecting to SSH server. The code is written in SwingWorker class as it is a network operation.
private void testConnectionButtonActionPerformed(java.awt.event.ActionEvent evt) {
SwingWorker<Boolean, Void> sw = new SwingWorker<Boolean, Void>(){
#Override
protected Boolean doInBackground() throws Exception {
JSch jsch = new JSch();
String host = "ServerHost";
String username = "username";
String password = "password";
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return true;
}
#Override
public void done(){
try {
System.out.println(get().toString());
} catch (Exception ex) {
System.out.err(ex);
}
}
};
sw.execute();
}
But after running the with correct host, username and password details, I get the below error all the time:
com.jcraft.jsch.JSchException: timeout: socket is not established
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
But whenever I run the same code in standalone program, I mean instead for writing actionPerformed() method, If I write it in normal method and calling from main() method. It will work. when I integrate the same code with Button Click's actionPerformed() method, it will give me above exception.
Can anyone suggest what I'm doing wrong here or any modification should be made to the code.
I tried to connect to SSH Server using "SSHJ" implementation, but I get the below error:
java.net.SocketException: Connection reset
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
Can someone help me - how to move forward?
I took your code, wrapped it in some GUI code (and converted it to non-generics to be able to compile it with the same settings as the rest of the JSch examples). It works for me. Try this, and report what exception you get (it has a bit more exception logging).
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import com.jcraft.jsch.*;
class SwingWorkerExample {
JTextField hostField;
JTextField userNameField;
JTextField passwordField;
JPanel panel;
public SwingWorkerExample() {
JPanel p = panel = new JPanel(new GridLayout(0,2));
hostField = new JTextField(20);
userNameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton testButton = new JButton("connect!");
testButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
testConnectionButtonActionPerformed(ev);
}
});
p.add(new JLabel("host:"));
p.add(hostField);
p.add(new JLabel("user:"));
p.add(userNameField);
p.add(new JLabel("password:"));
p.add(passwordField);
p.add(testButton);
}
public JPanel getPanel() {
return panel;
}
private void testConnectionButtonActionPerformed(ActionEvent evt) {
SwingWorker sw = new SwingWorker(){
protected Object doInBackground() throws Exception {
try {
JSch jsch = new JSch();
String host = hostField.getText();
String username = userNameField.getText();
String password = passwordField.getText();
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return session;
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static void main(String[] egal) {
EventQueue.invokeLater(new Runnable(){public void run() {
SwingWorkerExample ex = new SwingWorkerExample();
JFrame f = new JFrame("bla");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(ex.getPanel());
f.pack();
f.setVisible(true);
}});
}
}

Resources