Getting Java SocketException - java

Hello I want to develope a App for my Team, but I'm getting This Error:
java.net.SocketException: Address family not supported by protocol family: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1226)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1162)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1056)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:990)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1570)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1498)
at java.net.URL.openStream(URL.java:1067)
at de.tbprivi.mgde.Home.Home.getEventData(Home.java:37)
at de.tbprivi.mgde.Home.Home.<init>(Home.java:29)
at de.tbprivi.mgde.main.Main.main(Main.java:8)
My code is this:
package de.tbprivi.mgde.Home;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Home {
public JFrame frame;
private JSONParser parser;
public Home(){
frame = new JFrame();
frame.setTitle("Miners-Games.de - TEAM APP");
frame.setSize(700,500);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
try {
getEventData();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
private void getEventData() throws IOException, ParseException {
Object obj = parser.parse(new InputStreamReader(new URL("http://mylink.com/events.json").openStream()));
JSONObject file = (JSONObject) obj;
file.get("events");
}
}
I'm using the org.json.simple Library.
The thing is if I'm just calling getEventsdata() and not the Home home = new Home() from my public static void main() than it is working.
Thanks in advance for the help :)

This happens if the call doesn't use the IPv4 stack.
I guess that the Java option -Djava.net.preferIPv4Stack=true would do the trick.
If you are using eclipse set it via the jvm program line arguments

Related

Using mockito-inline MockedConstruction to mock FileInputStream throws Could not initialize mocked construction

I'm trying to get rid of PowerMock and replace it with mockito-inline new feature Mocking object construction ,
as I can't refactor the old source code.
One of the test classes I have is mocking FileInputStream,
the class under test FileViewer
import java.awt.Button;
import java.awt.Event;
import java.awt.Font;
import java.awt.TextArea;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileViewer extends java.awt.Frame {
private static final long serialVersionUID = 1L;
Button close;
GUIListener fGuiListener;
public FileViewer() {
super();
fGuiListener = new GUIListener();
addWindowListener(fGuiListener);
}
public FileViewer(String filename) throws IOException {
super("FileViewer: " + filename);
fGuiListener = new GUIListener();
addWindowListener(fGuiListener);
File f = new File(filename);
int size = (int) f.length();
int bytes_read = 0;
byte[] data = new byte[size];
try (FileInputStream in = new FileInputStream(f)) {
while (bytes_read < size)
bytes_read += in.read(data, bytes_read, size - bytes_read);
}
TextArea ta = new TextArea(new String(data, 0), 24, 80);
ta.setFont(new Font("Helvetica", Font.PLAIN, 12));
ta.setEditable(false);
this.add("Center", ta);
close = new Button("Close");
this.add("South", close);
this.pack();
this.show();
}
public boolean action(Event e, Object what) {
if (e.target == close) {
this.hide();
this.dispose();
return true;
} else
return false;
}
}
and the original unit test using powermock was
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#PowerMockIgnore({ "javax.management.*", "javax.security.*" })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ FileViewer.class, FileInputStream.class, java.awt.Frame.class })
public class FileViewerTest {
String dir = System.getProperty("user.dir");
String fileName = "/testFiles/testRead.txt";
FileInputStream mockStream = null;
#Before
public void setup() throws Exception {
mockStream = Mockito.mock(FileInputStream.class);
when(mockStream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(2000);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(mockStream);
}
#Test
public void testFileViewer_wFilename() throws Exception {
FileViewer spy = Mockito.spy(new FileViewer(dir + fileName));
verify(mockStream, times(1)).close();
spy.dispose();
}
}
I tried to follow the example Mock Java Constructors With Mockito | Configuration and Examples
and creat a new unit test using MockedConstruction as the following
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
public class FileViewerMockitoTest {
String dir = System.getProperty("user.dir");
String fileName = "/testFiles/testRead.txt";
#Test
public void testFileViewerWithFilename() throws Exception {
try (MockedConstruction<FileInputStream> mocked = Mockito.mockConstruction(FileInputStream.class,
(mock, context) -> {
// further stubbings ...
when(mock.read(any(), any(), any())).thenReturn((int) new File(dir + fileName).length() + 1);
})) {
FileViewer cut = new FileViewer(dir + fileName);
verify(mocked, times(1)).close();
cut.dispose();
}
}
}
But I got the following Exception
org.mockito.exceptions.base.MockitoException: Could not initialize mocked construction
at java.io.FileInputStream.<init>(FileInputStream.java)
at sun.misc.URLClassPath$FileLoader$1.getInputStream(URLClassPath.java:1385)
at sun.misc.Resource.cachedInputStream(Resource.java:77)
at sun.misc.Resource.getByteBuffer(Resource.java:160)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at com.cds.nrd.xss.util.FileViewerMockitoTest.testFileViewerWithFilename(FileViewerMockitoTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.lang.NullPointerException
at com.cds.nrd.xss.util.FileViewerMockitoTest.lambda$0(FileViewerMockitoTest.java:27)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker$InlineConstructionMockControl.lambda$enable$0(InlineByteBuddyMockMaker.java:710)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.lambda$new$3(InlineByteBuddyMockMaker.java:272)
at org.mockito.internal.creation.bytebuddy.MockMethodAdvice.handleConstruction(MockMethodAdvice.java:176)
at org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher.handleConstruction(MockMethodDispatcher.java:53)
... 57 more
Any idea about the reason of the exception or how to make it work, or any alternate approach?
Found the solution:
We can't set any() parameter in the stub of the lambda function in try-with-resource
(in your case, when(mock.read(any(), any(), any())) in FileViewerMockitoTest), which will cause mock.read(any(), any(), any()) to throw an NPE: "could not unbox null" (don't know what it means).
Just simply replace (all of) these arguments to something like any(ArgClass.class), will solve the NPE problem, so do with the Could not initialize mocked construction MockitoException problem.
(How did I find the problem? By extracting the lambda function as a method, we can get the real description of the NPE in the debug environment.)
(I was surprised that there was no information on the internet other than this question.)

Mock email using Green mail - Error-Couldn't connect to host, port: localhost, 3025; timeout -1;

i'm trying to mock email test using greenmail and testNG. so i got code from greenmail website. i tried to implement it but i got connection refused.
this is my GreenEmail.java class
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GreenEmail {
private final static Properties mailProperties = new Properties();
private final String imapHost;
private final int imapPort;
public GreenEmail(String smtpHost, int smtpPort,
String imapHost, int imapPort,
String user, String password) {
this.imapHost = imapHost;
this.imapPort = imapPort;
mailProperties.setProperty("mail.smtp.host", smtpHost);
mailProperties.setProperty("mail.smtp.port", Integer.toString(smtpPort));
mailProperties.setProperty("mail.user", "bar#example.com");
mailProperties.setProperty("mail.password", "secret-pwd");
mailProperties.setProperty("mail.store.protocol", "imap");
}
/*sendEmail method which takes following parameters
* to- email to which we send an email
* from-email from which we send an email
* subject-subject of the email we send
* content-message that we send in our email*/
public void sendMail(String to, String from, String subject,
String content) throws MessagingException {
Session session = Session.getDefaultInstance(mailProperties);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setText(content);
Transport.send(message);
}`
I have a testNg class to test this sending email test.
import java.io.IOException;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.icegreen.greenmail.user.GreenMailUser;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;
import com.sun.mail.imap.IMAPStore;
public class TestMail {
#Test
public void test() throws MessagingException, IOException{
GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
GreenMailUser greenMailUser = greenMail.setUser("bar#example.com", "bar#example.com", "secret-pwd");
GreenEmail mailingClass = new GreenEmail(
"localhost", ServerSetupTest.SMTP.getPort(),
"localhost", ServerSetupTest.IMAP.getPort(),
greenMailUser.getLogin(), greenMailUser.getPassword());
String to = "receiver#testmailingclass.net";
String from = greenMailUser.getEmail();
String subject = "Sending test";
String content = "This content should be sent by the user.";
Session smtpSession = greenMail.getSmtp().createSession();
Message msg = new MimeMessage(smtpSession);
msg.setFrom(new InternetAddress("foo#example.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("bar#example.com"));
msg.setSubject("Email sent to GreenMail via plain JavaMail");
msg.setText("Fetch me via IMAP");
mailingClass.sendMail(to, from, subject, content);
// let GreenMail create and configure a store:
IMAPStore imapStore = greenMail.getImap().createStore();
imapStore.connect("bar#example.com", "secret-pwd");
Folder inbox = imapStore.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msgReceived = inbox.getMessage(1);
Assert.assertEquals(msg.getSubject(), msgReceived.getSubject());
imapStore.close();
After running my TestNg class i got the stack trace like this.
[TestNG] Running:
C:\Users\leela krishna\AppData\Local\Temp\testng-eclipse-1553107636\testng- customsuite.xml
[Utils] Attempting to create D:\workspace\MockEmail\test-output\Default suite\Default test.html
[Utils] Directory D:\workspace\MockEmail\test-output\Default suite exists: true
[Utils] Attempting to create D:\workspace\MockEmail\test-output\Default suite\Default test.xml
[Utils] Directory D:\workspace\MockEmail\test-output\Default suite exists: true
FAILED: test
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 3025; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2100)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at com.qpair.qp.GreenEmail.sendMail(GreenEmail.java:46)
at com.qpair.qp.TestMail.test(TestMail.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:823)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1131)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:778)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1225)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1150)
at org.testng.TestNG.runSuites(TestNG.java:1075)
at org.testng.TestNG.run(TestNG.java:1047)
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)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2066)
... 33 more
So i didn't understand the problem. if anybody can clear this that would be a great help for me. Thanks in advance.

java.lang.NoSuchFieldError: INSTANCE exception is thrown by appium driver varriable

I am trying to write this java class that opens an apk file in an android device and presses some buttons through appium,using the code below:
package new_appium_test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class new_appium_test {
public MobileDriver driver;
#Before
public void setUp() throws MalformedURLException, InterruptedException, Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "GT-I9300"); //specify your cellphone name
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,"4.3"); //specify the platform version
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appium-version", "1.2.4.1");
capabilities.setCapability("appPackage","wizzo.mbc.net");
capabilities.setCapability("appActivity","wizzo.mbc.net.activities.SplashActivity");
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#Test
public void chooseEnglish() throws Exception
{
driver.findElement(By.name("English")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}
although this failure trace appears:
java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:71)
at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:251)
at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:228)
at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:89)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:63)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:58)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:155)
at io.appium.java_client.DefaultGenericMobileDriver.<init>(DefaultGenericMobileDriver.java:22)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:202)
at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:50)
at new_appium_test.new_appium_test.setUp(new_appium_test.java:34)
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.junit.internal.runners.BeforeAndAfterRunner.invokeMethod(BeforeAndAfterRunner.java:74)
at org.junit.internal.runners.BeforeAndAfterRunner.runBefores(BeforeAndAfterRunner.java:50)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:33)
at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
the problem is located on the command driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);.
Can anyone please tell me why this is happening?
NoSuchfield exception is thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field. If this error is happening at the Android driver instantiation, then it could be that some of capabilites you have may not be right. There is no such capability as appium-version - Link. Also device_name is ignored for Android. Try out below capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,
"Selendroid");
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "4.3");
capabilities.setCapability(MobileCapabilityType.APP_PACKAGE: "wizzo.mbc.net");
capabilities.setCapability(MobileCapabilityType.APP_ACTIVITY: "wizzo.mbc.net.activities.SplashActivity");

Java Errors on HttpURLConnection

I wrote something similar to this and it was giving me an error. So I found this online and it still gives me an error. What Am I not doing correct ?
/* package whatever; // don't place package name! */
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
URL u = new URL ("http://www.yahoo.com/");
HttpURLConnection huc = ( HttpURLConnection ) u.openConnection ();
huc.setRequestMethod ("GET"); //OR huc.setRequestMethod ("HEAD");
huc.connect();
int code = huc.getResponseCode();
System.out.println(code);
}
}
The errors I am getting are
Exception in thread "main" java.net.UnknownHostException: www.yahoo.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
at urlCheck.UrlRTest.main(UrlRTest.java:30) " LINE 30 is huc.connect();
The error has been seen in SpringToolSuite & Ideone.com

Compiliing and executing Java programs in OSX

Someone needs a public RSA key from me & gave me a java program to make a keypair. I have zero experience with Java so very simple things are very difficult for me. The program looks like this:
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class CustomRSAKeyPairGenerator{
public void generate() {
try {
KeyPairGenerator objlRSAKeyPairGen =
KeyPairGenerator.getInstance("RSA");
objlRSAKeyPairGen.initialize(2048);
KeyPair objlRSAKeyPair = objlRSAKeyPairGen.generateKeyPair();
RSAPublicKey objlPublicKey = (RSAPublicKey) objlRSAKeyPair.getPublic();
RSAPrivateKey objlPrivateKey = (RSAPrivateKey) objlRSAKeyPair.getPrivate();
StringBuffer strblPublicKey = new StringBuffer();
strblPublicKey.append(objlPublicKey.getModulus().toString(16).toUpperCase());
strblPublicKey.append('~');
strblPublicKey.append(objlPublicKey.getPublicExponent().toString(16).toUpperCase()
);
System.out.println(strblPublicKey.toString());
StringBuffer strblPrivateKey = new StringBuffer();
strblPrivateKey.append(objlPrivateKey.getModulus().toString(16).toUpperCase());
strblPrivateKey.append('~');
strblPrivateKey.append(objlPrivateKey.getPrivateExponent().toString(16).toUpperCase());
System.out.println(strblPrivateKey.toString());
}catch (NoSuchAlgorithmException noSuchAlgrtm){
System.out.println(noSuchAlgrtm.getMessage());
}
}
}
When I compile this I get a file called "CustomRSAKeyPairGenerator.class" so I then run that like this:
mylogin$java CustomRSAKeyPairGenerator
and I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: CustomRSAKeyPairGenerator/class
Caused by: java.lang.ClassNotFoundException: CustomRSAKeyPairGenerator.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Am I running this wrong or is there a problem in the java source that I need to fix? Is there a way to use this to make the RSA keypair that I need?

Categories