Broken connection with MariaDB - mariadb

I have a Wildly server connected to MariaDB Server on the same machine.
For some reason I get this error from time to time:
20:38:51,536 INFO [stdout] (default task-1) 20:38:51.535 [default task-1] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 08
20:38:51,536 INFO [stdout] (default task-1) 20:38:51.536 [default task-1] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - (conn=25) Connection reset by peer (Write failed)
20:38:51,549 INFO [stdout] (default task-1) 20:38:51.548 [default task-1] ERROR o.s.t.i.TransactionInterceptor - Application exception overridden by rollback exception
20:38:51,550 INFO [stdout] (default task-1) org.springframework.dao.DataAccessResourceFailureException: could not prepare statement; nested exception is org.hibernate.exception.JDBCConnectionException: could not prepare statement
20:38:51,550 INFO [stdout] (default task-1) at deployment.datalis_admin.war//org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:275)
20:38:51,550 INFO [stdout] (default task-1) at deployment.datalis_admin.war//org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
20:38:51,550 INFO [stdout] (default task-1) at deployment.datalis_admin.war//org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
In MariaDB log I get: 2019-03-06 20:27:51 25 [Warning] Aborted connection 25 to db: 'production_gateway' user: 'wildfly' host: 'localhost' (Got timeout reading communication packets)
Do you know what might be the issue and how to fix it?
POM file:
https://pastebin.com/HUNy0ULy
application.properties:
spring.datasource.jndi-name=java:/global/production_gateway
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
JPA configuration:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class ContextDatasource {
#Bean
public EntityManager entityManager(EntityManagerFactory emf) {
return emf.createEntityManager();
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
JDBC driver:
mariadb-java-client-2.4.0.jar
MariaDB version:
mysql Ver 15.1 Distrib 10.3.13-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
Can you advice?

Please show us your pom.xml and watch out if your driver's version is compatible for your DB version as well. Some they have to update the driver web the DB developer make some change.

Related

How can I use a Webdriver Testcontainer in Bitbucket Pipelines?

When trying to use a Webdriver Testcontainer in Bitbucket Pipelines, I get the following error messages:
[main] WARN 🐳 [selenium/standalone-chrome:4.1.1] - Unable to mount a file from test host into a running container. This may be a misconfiguration or limitation of your Docker environment. Some features might not work.
[main] ERROR 🐳 [selenium/standalone-chrome:4.1.1] - Could not start container
com.github.dockerjava.api.exception.DockerException: Status 403: {"message":"authorization denied by plugin pipelines: -v only supports $BITBUCKET_CLONE_DIR and its subdirectories"}
My testcontainers version is 1.17.6
Here is the code I'm using while trying to troubleshoot:
package com.byzpass.demo;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testcontainers.containers.BrowserWebDriverContainer;
public class SeleniumTest {
public ChromeOptions chromeOptions = new ChromeOptions().addArguments("--no-sandbox").addArguments("--headless").addArguments("--disable-dev-shm-usage");
#Rule
public BrowserWebDriverContainer<?> driverContainer = new BrowserWebDriverContainer<>().withCapabilities(chromeOptions);
#Test
public void openWikipedia() {
WebDriver driver = new RemoteWebDriver(driverContainer.getSeleniumAddress(), chromeOptions);
driver.navigate().to("https://www.wikipedia.org/");
String subtitleText = driver.findElement(By.cssSelector("#www-wikipedia-org h1 strong")).getText();
assert subtitleText.equals("The Free Encyclopedia");
driver.quit();
System.out.println("Finished opening wikipedia. 📖 🤓 🔍 👍 ✨");
}
}
Here is my bitbucket-pipelines.yml:
pipelines:
default:
- step:
image: amazoncorretto:11
services:
- docker
script:
- export TESTCONTAINERS_RYUK_DISABLED=true
- cd selenium-test ; bash ./mvnw --no-transfer-progress test
definitions:
services:
docker:
memory: 2048
By setting a breakpoint in my test method and using docker inspect -f '{{ .Mounts }}' I was able to discover that the container for the selenium/standalone-chrome:4.1.1 image has [{bind /dev/shm /dev/shm rw true rprivate}]
I thought that using the --disable-dev-shm-usage argument in my chrome options would prevent that, but it didn't. I don't know whether that's what's causing my issue in Bitbucket Pipelines though.
I found that it worked after setting shm size to zero. Here's the code that worked:
package com.byzpass.demo;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testcontainers.containers.BrowserWebDriverContainer;
import java.util.ArrayList;
public class SeleniumTest {
#Test
public void openWikipedia() {
ChromeOptions chromeOptions = new ChromeOptions().addArguments("--no-sandbox").addArguments("--headless").addArguments("--disable-dev-shm-usage");
BrowserWebDriverContainer driverContainer = new BrowserWebDriverContainer<>().withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.SKIP, null);
driverContainer.setShmSize(0L);
driverContainer.start();
WebDriver driver = new RemoteWebDriver(driverContainer.getSeleniumAddress(), chromeOptions);
driver.navigate().to("https://www.wikipedia.org/");
String subtitleText = driver.findElement(By.cssSelector("#www-wikipedia-org h1 strong")).getText();
assert subtitleText.equals("The Free Encyclopedia");
driver.quit();
driverContainer.stop();
System.out.println("Finished opening wikipedia. 📖 🤓 🔍 👍 ✨");
}
}

Started stub server for project [] on port -1

I am trying to create a single (fat) spring boot jar for consumer with producer's stub as a dependency to it. With this, when i start-up the consumer app, it should start the contract stub as well.
Here is what I have done so far:
I used this pom example (https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer_with_external_contracts/pom.xml#L98) and created a fat jar for producer
producer.pom
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<configuration>
<baseClassMappings>
<baseClassMapping>
<contractPackageRegex>.*contract.*</contractPackageRegex>
</baseClassMapping>
</baseClassMappings>
<contractDependency>
<groupId>com.groupId</groupId>
<artifactId>producer</artifactId>
</contractDependency>
<contractsMode>LOCAL</contractsMode>
<classifier>stubs</classifier>
<basePackageForTests>com.groupId.producer</basePackageForTests>
<convertToYaml>true</convertToYaml>
</configuration>
</plugin>
This is then imported into my consumer.pom like below:
<dependency>
<groupId>com.groupId</groupId>
<artifactId>producer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
The application properties are as below:
producer - application.properties
server.port=8081
consumer - application.properties
stubrunner.ids=com.groupId:producer:+:stubs:8081
stubrunner.stubsMode=LOCAL
stubrunner.repositoryRoot=com.groupId.producer
stubrunner.minPort=8081
ControllerTests.java
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
#AutoConfigureMockMvc
#AutoConfigureJsonTesters
#AutoConfigureStubRunner( ids = "com.groupId:producer:+:stubs:8081",
stubsMode = StubRunnerProperties.StubsMode.LOCAL )
#DirtiesContext
public class ContractTests extends AbstractTest {
...
}
ConsumerApplication.java
#SpringBootApplication
#EnableWebMvc
#EnableStubRunnerServer
#Slf4j
public class ConsumerApplication {
...
}
ContractService.java
public class ContractService {
public #ResponseBody MockResponse verifyWithContract(SomeObj someObj) {
ResponseEntity<MockResponse> response = this.restTemplate.exchange(
RequestEntity
.post(URI.create( http://localhost:8081/someEndpoint ))
.contentType(MediaType.APPLICATION_JSON)
.body(someObj), MockResponse.class);
return response.getBody();
}
}
I have 2 issues:
When I run my test I get the below exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.contract.stubrunner.server.HttpStubsController': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'batchStubRunner' defined in org.springframework.cloud.contract.stubrunner.spring.StubRunnerConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.contract.stubrunner.BatchStubRunner]: Factory method 'batchStubRunner' threw exception; nested exception is java.lang.IllegalStateException: Remote repositories for stubs are not specified and work offline flag wasn't passed
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
I have also tried the below in test but that didn't help:
#AutoConfigureStubRunner( ids = "com.groupId:producer:+:stubs:8081",
stubsMode = StubRunnerProperties.StubsMode.REMOTE, rootRepository="com.groupId.producer" )
Ignoring the test failures, when i start the application, it starts fine with the below log lines
2019-04-09 11:38:50.454 INFO 75383 --- [ main] o.s.c.contract.stubrunner.StubServer : Started stub server for project [com.groupId:producer:0.0.1-SNAPSHOT:stubs] on port -1
2019-04-09 11:38:50.454 INFO 75383 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.gorupId:producer:0.0.1-SNAPSHOT:stubs=-1}]
2019-04-09 11:38:50.673 INFO 75383 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (https) with context path ''
but when i send a request to the rest URL: https://localhost:8080/someEndpoint
it returns the below error:
{
"timestamp": 1554837050058,
"status": 500,
"error": "Internal Server Error",
"message": "I/O error on POST request for \"http://localhost:8081/someEndpoint\": Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)",
"path": "/someEndpoint"
}
log lines:
2019-04-09 12:10:50.045 ERROR 75383 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:8081/someEndpoint": Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)] with root cause
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_171]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_171]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_171]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_171]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_171]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_171]
at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:75) ~[spring-cloud-contract-shade-2.1.1.RELEASE.jar:2.1.1.RELEASE]
I think i am missing some stubRunner configuration for stubrunner port.

Java EE 7 and Wildfly 10.1.0 - IllegalStateException: EJBCLIENT000025

I created following EJB-Module:
1) My Remote interface
package calculator.beans;
import javax.ejb.Remote;
#Remote
public interface CalculatorRemote {
public int addNum(int num1, int num2);
}
2) A bean which implements the interface
package calculator.beans;
import javax.ejb.Stateless;
#Stateless
public class CalculatorBean implements CalculatorRemote {
#Override
public int addNum(int num1, int num2) {
return num1 + num2;
}
}
3) Next I created a property-file 'jboss-ejb-client.properties'
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port = 8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=appuser
remote.connection.default.password=apppassword
After the deployment to wildfly everything was fine. I get following Information:
INFO [org.jboss.as.ejb3.deployment] (MSC service thread 1-4) WFLYEJB0473: JNDI bindings for session bean named 'CalculatorBean' in deployment unit 'deployment "CalculatorEJB.jar"' are as follows:
java:global/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
java:app/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
java:module/CalculatorBean!calculator.beans.CalculatorRemote
java:jboss/exported/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
java:global/CalculatorEJB/CalculatorBean
java:app/CalculatorEJB/CalculatorBean
java:module/CalculatorBean
4) Then I created my Java Client
package calculator.client;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import calculator.beans.CalculatorRemote;
public class RemoteRechnerClient {
public static void main(String[] args) {
try {
final Hashtable<String, String> jndiProperties = new Hashtable<>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context ctx = new InitialContext(jndiProperties);
String crName = CalculatorRemote.class.getName();
CalculatorRemote cr = (CalculatorRemote) ctx.lookup("ejb:CalculatorEJB/beans/CalculatorBean!" + crName);
System.out.println("Result: " + cr.addNum(5, 4));
} catch (NamingException ex) {
ex.printStackTrace();
}
}
}
The code is simple enough. But if I run the Client I get following Error-Message:
Apr 06, 2017 3:30:26 PM org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 2.0.1.Final
Apr 06, 2017 3:30:26 PM org.xnio.Xnio <clinit>
INFO: XNIO version 3.3.0.Final
Apr 06, 2017 3:30:26 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.3.0.Final
Apr 06, 2017 3:30:26 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 4.0.6.Final
Apr 06, 2017 3:30:27 PM org.jboss.ejb.client.remoting.VersionReceiver handleMessage
INFO: EJBCLIENT000017: Received server version 2 and marshalling strategies [river]
Apr 06, 2017 3:30:27 PM org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver associate
INFO: EJBCLIENT000013: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#3c0f93f1, receiver=Remoting connection EJB receiver [connection=org.jboss.ejb.client.remoting.ConnectionPool$PooledConnection#31dc339b,channel=jboss.ejb,nodename=john-waynes-macbook-pro]} on channel Channel ID b98547a5 (outbound) of Remoting connection 0c84e8ba to /127.0.0.1:8080
Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:CalculatorEJB, moduleName:beans, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#2758fe70
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:749)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:186)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy0.addNum(Unknown Source)
at calculator.client.RemoteRechnerClient.main(RemoteRechnerClient.java:27)
/Users/manhthangd/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I am using Netbeans 8.2, Java EE 7 and Wildfly 10.1.0-Final.
What can I do to solve the problem?
Your JNDI lookup name is incorrect.
You need to use the highlighted portion of:
java:jboss/exported/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
ie.
CalculatorRemote cr = (CalculatorRemote) ctx.lookup("ejb:CalculatorEJB/CalculatorBean!" + crName);
Where did you get "ejb:CalculatorEJB/beans/CalculatorBean!" from?

WebSocketServlet in a WAR-file: Bad character 13 for SelectChannelEndPoint

On Mac with Oracle java "1.8.0_45" I have create a Jetty base dir with:
# java -jar /Users/afarber/jetty-distribution-9.3.10.v20160621/start.jar jetty.home=/Users/afarber/jetty-distribution-9.3.10.v20160621 jetty.base=/Users/afarber/jetty-base --add-to-startd=http,servlet,webapp,resources,ext,fcgi,websocket,proxy-protocol,deploy
INFO: ext initialised in ${jetty.base}/start.d/ext.ini
INFO: resources initialised in ${jetty.base}/start.d/resources.ini
INFO: server initialised (transitively) in ${jetty.base}/start.d/server.ini
INFO: http initialised in ${jetty.base}/start.d/http.ini
INFO: servlet initialised in ${jetty.base}/start.d/servlet.ini
INFO: fcgi initialised in ${jetty.base}/start.d/fcgi.ini
INFO: proxy-protocol initialised in ${jetty.base}/start.d/proxy-protocol.ini
INFO: webapp initialised in ${jetty.base}/start.d/webapp.ini
INFO: websocket initialised in ${jetty.base}/start.d/websocket.ini
MKDIR: ${jetty.base}/lib
MKDIR: ${jetty.base}/lib/ext
MKDIR: ${jetty.base}/resources
MKDIR: ${jetty.base}/webapps
INFO: Base directory was modified
Then I have put $JETTY_BASE/webapps/ws-servlet-0.1-SNAPSHOT.war produced by the very simple Maven project out of -
WsServlet.java
public class WsServlet extends WebSocketServlet
{
#Override
public void configure(WebSocketServletFactory factory) {
factory.register(EchoListener.class);
}
}
EchoListener.java
public class EchoListener implements WebSocketListener {
private static final Logger LOG = Log.getLogger(EchoListener.class);
private Session mSession;
#Override
public void onWebSocketConnect(Session session) {
LOG.info("onWebSocketConnect {}", session);
mSession = session;
}
#Override
public void onWebSocketText(String message) {
LOG.info("onWebSocketText {}", message);
if (mSession != null && mSession.isOpen()) {
mSession.getRemote().sendString("ECHO: " + message, null);
}
}
}
Finally I have created the $JETTY_BASE/webapps/ws.xml file pointing to the WAR-file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
"http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/ws</Set>
<Set name="war"><SystemProperty name="jetty.base"/>/webapps/ws-servlet-0.1-SNAPSHOT.war</Set>
</Configure>
When I start Jetty and then connect to it using simple JavaScript code in browser var ws = new WebSocket("//127.0.0.1:8080/ws"); or the Simple Web Socket Client extension for Chrome the error comes:
# java -Dorg.eclipse.jetty.LEVEL=DEBUG -jar /Users/afarber/jetty-distribution-9.3.10.v20160621/start.jar jetty.base=/Users/afarber/jetty-base
....
WARN:oejs.ProxyConnectionFactory:qtp1993134103-12: Bad character 13 for SelectChannelEndPoint#26ba5622{/127.0.0.1:49883<->8080,Open,in,out,-,-,0/30000,ProxyConnection#49376d8e}{io=1/0,kio=1,kro=1}
Here is the full Jetty log, what have I missed here please?
UPDATE:
I have also tried connecting to ws://127.0.0.1:8080/ws-servlet-0.1-SNAPSHOT and tried adding annotations like #WebServlet(name = "WsServlet", urlPatterns = { "/ws" })- but that does not help. Also I have tried the older version 9.3.9.v20160517.
UPDATE 2:
Is the root cause the PROXY Protocol, which I have to use at my production server, because I offload SSL and normal connections to HAProxy? From the doc I read that 13 is sent as the first byte.
UPDATE 3:
The problem has been solved by adding a trailing slash: ws://127.0.0.1:8080/ws/

How to Allocate a Private IP address and Port with Ghostdriver

I wrote a Ghostdriver Maven Java project where I call many instances of the jar file using a shell script in Ubuntu 14.04 64bit.
Each line in my shell script calls a new instance of my jar file.
The format of each line:
screen -dmS name java -jar /path/name.jar arg1 arg2 arg3
Currently I have 1 network interface (eth0) split up into multiple network aliases (eth0:1, eth0:2, etc), each alias points to a private IP which in turns points to a public IP.
I am trying to find the best way to allocate a private IP and possibly port number to each instance of my java program. Currently I call Ghostdriver inside my program.
The way I call ghost driver within my program:
public class className {
PhantomJSDriver driver;
public static final File PHANTOMJS_EXE = new File("//home/username/phantomjs/bin/phantomjs");
public className() {
callGhostdriver();
driver.quit();
}
private void callGhostdriver() {
{
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("phantomjs.binary.path",
PHANTOMJS_EXE.getAbsolutePath());
driver = new PhantomJSDriver(caps);
driver.manage().window().maximize();
actions = new Actions(driver);
}
}
}
Any help would be greatly appreciated.
***Update****
I tried changing the callGhostdriver method but had no success.
private void callGhostdriver() {
DesiredCapabilities dcaps = new DesiredCapabilities();
dcaps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
PHANTOMJS_EXE.getAbsolutePath());
String[] phantomJsArgs = {"--webdriver=172.16.190.131:6781"};
dcaps.setCapability(
PhantomJSDriverService.PHANTOMJS_CLI_ARGS,
phantomJsArgs);
driver = new PhantomJSDriver(dcaps);
driver.manage().window().maximize();
actions = new Actions(driver);
}
Argument --webdriver=IP:PORT seems to be overridden by a default
--webdriver call.
Output from running jar:
*Apr 12, 2015 5:26:25 PM org.openqa.selenium.phantomjs.PhantomJSDriverService INFO: port: 8651
Apr 12, 2015 5:26:25 PM
org.openqa.selenium.phantomjs.PhantomJSDriverService INFO: arguments:
[--webdriver=172.16.190.131:6781, --webdriver=8651,
--webdriver-logfile=/home/RemovedPath/phantomjsdriver.log] Apr 12, 2015 5:26:25 PM org.openqa.selenium.phantomjs.PhantomJSDriverService
INFO: environment: {} [INFO - 2015-04-12T21:26:26.584Z] GhostDriver -
Main - running on port 8651
Port 6781 with the different private IP should be what it is using but it uses 8651 instead.
I was able to find a hackish way to set the port but still haven't figured out how to set the private ip, I may have to use iptables to route the traffic.
private void loadLightWeightDriverCustom() {
ArrayList<String> cliArgsCap = new ArrayList();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, PHANTOMJS_EXE.getAbsolutePath());
cliArgsCap.add("--web-security=false");
cliArgsCap.add("--ssl-protocol=any");
cliArgsCap.add("--ignore-ssl-errors=true");
capabilities.setCapability(
PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
driver = new PhantomJSDriver(Configure(cliArgsCap), capabilities);
}
private PhantomJSDriverService Configure(ArrayList<String> cap) {
return new PhantomJSDriverService.Builder().usingPhantomJSExecutable(PHANTOMJS_EXE)
.usingPort(5555)
.usingCommandLineArguments(
(cap.toArray(new String[cap.size()])))
.build();
}
Try this -->
List<String> cliArgsCap = Arrays.asList(
"--webdriver=172.16.190.131:6781");
dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
I was able to find a fix to the --webdriver command, https://github.com/detro/ghostdriver/pull/438, I compiled that jar and loaded it in. Now I am getting
Apr 24, 2015 10:35:04 AM org.openqa.selenium.phantomjs.PhantomJSDriverService
INFO: executable: C:*Removed Path\phantomjs-2.0.0-windows\bin\phantomjs.exe
Apr 24, 2015 10:35:04 AM org.openqa.selenium.phantomjs.PhantomJSDriverService
INFO: port: 41533
Apr 24, 2015 10:35:04 AM org.openqa.selenium.phantomjs.PhantomJSDriverService
INFO: arguments: [--webdriver=127.0.0.1:6666, --webdriver-logfile=C:\Removed Path*\phantomjsdriver.log]
Apr 24, 2015 10:35:04 AM org.openqa.selenium.phantomjs.PhantomJSDriverService
INFO: environment: {}
[INFO - 2015-04-24T14:35:06.222Z] GhostDriver - Main - running on port 6666
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
System info: host: 'MBC5708', ip: '167.74.185.13', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_45'
Driver info: driver.version: PhantomJSDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:593)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:126)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:139)
My method invoking phantomjs is:
ArrayList<String> cliArgsCap = new ArrayList<String>();
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
cliArgsCap.add("--webdriver=6666");
capabilities.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,PHANTOMJS_EXE.getAbsolutePath());
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
driver = new PhantomJSDriver(capabilities);

Resources