HtmlUnit on webserver: method <init>()V not found - webserver

I've managed to run the code in this question here properly in a test java project with no problem, but when I am following the exact same procedure to import HtmlUnit in my webserver, i keep getting the org.apache.http.protocol.BasicHttpContext: method <init>()V not found error.
the code im trying to run:
package com.testing;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
public class testingUnit {
public static void main(final String[] args) {
final WebClient webClient = new WebClient();
webClient.setTimeout(1000);
try {
System.out.println("Querying");
webClient.getPage("https://bulksms.vsms.net/register/");
System.out.println("Success");
} catch (final FailingHttpStatusCodeException e) {
System.out.println("One");
e.printStackTrace();
} catch (final MalformedURLException e) {
System.out.println("Two");
e.printStackTrace();
} catch (final IOException e) {
System.out.println("Three");
e.printStackTrace();
} catch (final Exception e) {
System.out.println("Four");
e.printStackTrace();
}
System.out.println("Finished");
}
}
Console:
Querying
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.http.protocol.BasicHttpContext: method <init>()V not found
at org.apache.http.impl.client.AbstractHttpClient.createHttpContext(AbstractHttpClient.java:273)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:797)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:776)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:152)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1439)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1358)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:307)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:373)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:358)
at com.testing.testingUnit.main(testingUnit.java:16)

Figured it out after posting the screenshot here. I had totally forgot to update the web app libraries. I did that and deleted all the outdated versions of jars I had (in the webcontent/lib folder), and the code above worked like a charm. Cheers!

Related

How to find elements in webview in android using appium

I am new in automation testing . I am trying to find elements in webview in Android app using appium .
Below is code i am using but I am not able to find say div using its id
private AppiumDriver<WebElement> driver;
#Before
public void setUp() throws Exception {
// set up appium
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void webView() throws InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName","Android Emulator");
capabilities.setCapability("appPackage", "com.hokucampusaffairs");
capabilities.setCapability("appActivity", "com.mybeeps.DashboardActivity");
try {
driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.sleep(6000);
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
System.out.println(contextName);
if (contextName.contains("WEBVIEW")){
driver.context(contextName);
}
}
String pagesource= driver.getPageSource();
String url= driver.getCurrentUrl();
try {
WebElement inputField = **driver.findElement(By.id("top-container"));**
inputField.click();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Code in bold is not finding div using its id . Also findelementbyTag is only finding parent elements .
I am using latest version of appium /Android sdk/java 1.8
Exception gives you the answer - no element found with id='top-container'
Make sure you switch driver to webview
Try other locator strategies, e.g. Xpath
For webview inspection you can use chrome dev tools: https://developers.google.com/web/tools/chrome-devtools/remote-debugging/webviews

Executing a Perl script on Java button ActionEvent

I'm trying to run a Perl script when I push a button on a JFrame. I read around and realize that I need to use Runtime.exec() to run a command, and this works in the following code:
import java.io.IOException;
public class Charts {
public static void main(String args[]) {
try {
Runtime.getRuntime().exec("perl C:/Users/ryanm/Documents/updateCharts.pl");
} catch (IOException e) {
System.out.println (e.toString());
}
}
}
However, if I place this code in the ActionEvent for a button on a jframe it doesn't work:
import java.io.IOException;
...
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Runtime.getRuntime().exec("perl C:/Users/ryanm/Documents/updateCharts.pl");
System.out.println ("Execute");
} catch (IOException e) {
System.out.println (e.toString());
}
}
...
...
The print statement in the try block prints out when I click the button, so I'm not sure what's wrong here.
Thanks for any help!

Unable to catch STException in StringTemplate 4

I am unable to catch the STException thrown by the STGroupFile. This is a problem. I need to abort if the template is bad. To reproduce this problem, I have this incorrect template file called tmp.stg:
temp1(param1)::=<<
%if(param1)%
%param1:{%temp2(p)%}; separator"\n"%
%endif%
>>
And this groovy code to process it:
#!/usr/bin/env groovy
#Grab(group="org.antlr", module="ST4", version="4.0.8")
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.NumberRenderer;
public class Gex {
public static void main(String [] args) {
System.out.println("Processing...")
File fn = new File("tmp.stg")
STGroupFile group;
try {
group = new STGroupFile(fn.toString());
} catch (Throwable e) {
throw new Exception("Caught first exception");
}
try {
group.registerRenderer(Integer.class, new NumberRenderer());
} catch (Throwable e) {
throw new Exception("Caught second exception");
}
throw new Exception("You should not see this");
}
}
Gex.main()
When I run that script, I get an error message but I cannot catch the exception:
can't load group file file:tmp.stg
The error message comes from STGroupFile.java:
throw new STException("can't load group file "+fileName, e);
But I am unable to catch this exception. How can I catch this exception and abort?
Following the advice of The ANTLR Guy, I extended the STErrorListener to throw an exception instead of printing a message to stderr. It looks like this:
File: lib/GexListener.groovy
import org.stringtemplate.v4.STErrorListener;
import org.stringtemplate.v4.misc.STMessage;
import org.stringtemplate.v4.misc.ErrorType;
class GexListener implements STErrorListener {
#Override
public void compileTimeError(STMessage msg) {
throw new Exception(msg.toString());
}
#Override
public void runTimeError(STMessage msg) {
if ( msg.error != ErrorType.NO_SUCH_PROPERTY ) { // ignore these
throw new Exception(msg.toString());
}
}
#Override
public void IOError(STMessage msg) {
throw new Exception(msg.toString());
}
#Override
public void internalError(STMessage msg) {
throw new Exception(msg.toString());
}
public void error(String s) { error(s, null); }
public void error(String s, Throwable e) {
System.err.println(s);
if ( e!=null ) {
throw new Exception(msg.toString());
}
}
}
Then the master script bin/gex.groovy looks like this:
#!/bin/bash
//usr/bin/env groovy -cp ${0%/*}/../lib "$0" "$#"; exit $?
#Grab(group="org.antlr", module="ST4", version="4.0.8")
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.NumberRenderer;
import GexListener
public class Gex {
public static void main(String [] args) {
System.out.println("Processing...")
File fn = new File("tmp.stg")
STGroupFile group;
GexListener listener = new GexListener();
group = new STGroupFile(fn.toString());
group.setListener(listener);
group.registerRenderer(Integer.class, new NumberRenderer());
System.out.println("You should not see this line")
}
}
Gex.main()
When it executes, there is a nasty side effect where the stacktrace is printed twice, but the program aborts before printing the last sentence "You should not see this line", which is the desired behaviour.
As you pointed out in a separate email: "I discovered that the exception is actually caught and not re-thrown. This happens inside STGroup.java:"
catch (Exception e) {
errMgr.IOError(null, ErrorType.CANT_LOAD_GROUP_FILE, e, fileName);
}
Why not override the IOError function (or a function in the listener that it calls?) to just re-throw e?

Embedding OSGI Declarative Services Bundle works fine but NO output visible

I am trying to embed an OSGI bundle that uses in my java application.
Below is my only java file in the bundle (I am doing it simple now):
package it.eng.test.ds.consumer;
public class Consumer {
public void activate(){
System.out.println("I'm here, in the activate ds automatic method ;)");
}
public void deactivate()
{
System.out.println("Bye Bye!");
}
}
Below is consumer.xml:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="it.eng.test.ds.consumer"
activate="activate"
deactivate="deactivate"
modified="modified"
enabled="true"
immediate="true">
<implementation class="it.eng.test.ds.consumer.Consumer"/>
</scr:component>
Below is MANIFEST.MF:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Ds-bundle
Bundle-SymbolicName: it.eng.test.ds.consumer
Bundle-Version: 1.0.0.qualifier
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
-Component: OSGI-INF/consumer.xml
Next, I embedded equinox in my application, started the required bundles (org.eclipse.equinox.ds and its dependencies), and finally started my bundle which is called it.eng.test.ds.consumer_1.0.0.201401071018.jar.
Below is my application code:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
public class MainEmbedder {
public static void main(String[] args)
{
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Map<String, String> config = new HashMap<String, String>();
//TODO: add some config properties
Framework framework = frameworkFactory.newFramework(config);
try {
framework.start();
} catch (BundleException e) {
e.printStackTrace();
}
BundleContext context = framework.getBundleContext();
List<Bundle> installedBundles = new LinkedList<Bundle>();
try {
installedBundles.add(context.installBundle("file:C:\\Users\\student\\Desktop\\DS-Plugins\\org.eclipse.osgi.services_3.3.100.v20120522-1822.jar"));
installedBundles.add(context.installBundle("file:C:\\Users\\student\\Desktop\\DS-Plugins\\org.eclipse.equinox.util_1.0.200.v20100503.jar"));
installedBundles.add(context.installBundle(
"file:C:\\Users\\student\\Desktop\\DS-Plugins\\org.eclipse.equinox.ds_1.4.1.v20120926-201320.jar"));
installedBundles.add(context.installBundle(
"file:C:\\Users\\student\\Desktop\\DS-Plugins\\plugins\\it.eng.test.ds.consumer_1.0.0.201401071018.jar"));
} catch (BundleException e) {
e.printStackTrace();
}
for (Bundle bundle : installedBundles) {
try {
bundle.start();
} catch (BundleException e) {
e.printStackTrace();
}
}System.out.println("after starting bundles");
}
}
When I run my app, I can see the message "after starting bundles", but I do not see the message "I'm here, in the activate ds automatic method ;)". This means that my bundle did not enter the activate method. Why is that? How can I solve this problem? Thanks.
Update:
I tried to start the bundle with Felix framework, using the below code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.felix.framework.Felix;
import org.apache.felix.framework.util.FelixConstants;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
public class HostApplication
{
private HostActivator m_activator = null;
private Felix m_felix = null;
public HostApplication()
{
// Create a configuration property map.
Map config = new HashMap();
config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
// Create host activator;
m_activator = new HostActivator();
List list = new ArrayList();
list.add(m_activator);
config.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
try
{
// Now create an instance of the framework with
// our configuration properties.
m_felix = new Felix(config);
// Now start Felix instance.
m_felix.start();
}
catch (Exception ex)
{
System.err.println("Could not create framework: " + ex);
ex.printStackTrace();
}
// Register the application's context as an OSGi service!
BundleContext bundleContext1 = m_felix.getBundleContext();
System.out.println("6");
try {
Bundle dsBundle = bundleContext1.installBundle("file:C:\\Users\\student\\Desktop\\DS-Plugins\\org.apache.felix.scr-1.8.0.jar");
dsBundle.start();
if(dsBundle.getState()== dsBundle.ACTIVE)
System.out.println("DS Bundle is Active!");
Bundle consumerBundle = bundleContext1.installBundle("file:C:\\Users\\student\\Desktop\\DS-Plugins\\plugins\\it.eng.test.ds.consumer_1.0.0.201401071018.jar");
consumerBundle.start();
if(consumerBundle.getState()== consumerBundle.ACTIVE)
System.out.println("Consumer Bundle is Active!");
System.out.println("done!");
} catch (BundleException e) {
e.printStackTrace();
System.out.println("Not done!");
}
shutdownApplication();
}
public Bundle[] getInstalledBundles()
{
// Use the system bundle activator to gain external
// access to the set of installed bundles.
return m_activator.getBundles();
}
public void shutdownApplication()
{
// Shut down the felix framework when stopping the
// host application.
try {
m_felix.stop();
} catch (BundleException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
m_felix.waitForStop(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now I get the following error:
ERROR: it.eng.test.ds.consumer (2): Component descriptor entry 'OSGI-INF/consumer.xml' not found.
I guess there is something wrong with my bundle, but it is very simple and just as I descried it above. Any ideas?
I've replayed your setup, and I've got it to work.
(A github repo is here, if all else fails)
Check if OSGI-INF/ is actually in your bundle, did you add it to build.properties (if you use PDE)
regards, Frank
I am not sure what your exact intention is but embedding osgi bundles into a standard java application is maybe not the best thing to do. I would recommend to convert your application to osgi (if possible and it's not too big). If you cannot do to that consider to emulate the bundle with the ds component, e.g. just create the component instance manually and set it's dependencies on foot. But don't mix both worlds.

How to call getPage from HtmlUnit WebClient and have setTimeout not wait forever?

I have the same problem as described in the question Call getPage from htmlunit WebClient with JavaScript disabled and setTimeout set to 10000 waits forever.
There is only one relevant (complicated) possible answer there (by theytoo). So I was wondering if:
Does someone have a simpler answer?
Can someone verify the solution works?
Code I used:
package main;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
public class Test {
public static void main(final String[] args) {
final WebClient webClient = new WebClient();
webClient.setTimeout(1000);
try {
System.out.println("Querying");
webClient.getPage("http://www.google.com");
System.out.println("Success");
} catch (final FailingHttpStatusCodeException e) {
System.out.println("One");
e.printStackTrace();
} catch (final MalformedURLException e) {
System.out.println("Two");
e.printStackTrace();
} catch (final IOException e) {
System.out.println("Three");
e.printStackTrace();
} catch (final Exception e) {
System.out.println("Four");
e.printStackTrace();
}
System.out.println("Finished");
}
}
Output (removed all CSS and JS warnings):
Querying
Success
Finished
After changing timeout from 1000 to 1 (I won't hit google in less than 1 ms):
Querying
Three
org.apache.http.conn.ConnectTimeoutException: Connect to www.google.com:80 timed out
at com.gargoylesoftware.htmlunit.SocksSocketFactory.connectSocket(SocksSocketFactory.java:92)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:776)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:152)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1439)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1358)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:307)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:373)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:358)
at main.Test.main(Test.java:17)
Finished
Conclusion: I can't reproduce it and it works as expected