I am trying to run Client code in Clinet-Server programming in java and I am getting error "Could not find or load main class."
javac DateClient.java
java DateClient (I have also tried "java -cp . DateClient" but still not working).
Program which I am trying to run is :
package edu.lmu.cs.networking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DateClient {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Your class is in the package edu.lmu.cs.networking. Its name is thus edu.lmu.cs.networking.DateClient. And you thus need to execute it with
java -cp . edu.lmu.cs.networking.DateClient
(assuming . contains the edu directory, which contains the lmu directory, which contains the cs directory, which contains the networking directory, which contains the file DateClient.class).
Related
I am trying to start the Appium server using Appium service builder but am getting the following error. I tried everything but still get the error.
AppiumTest
io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started. The given Node.js executable: C:\Program Files\nodejs\node.exe Arguments: [C:\Users\[username]\AppData\Roaming\npm\node_modules\appium\build\lib\main.js, --port, 4723, --address, 127.0.0.1]
at io.appium.java_client.service.local.AppiumDriverLocalService.start(AppiumDriverLocalService.java:191)
package MahiyarAutomation;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
public class AppiumBasics {
#Test
public void AppiumTest() throws MalformedURLException
{
AppiumDriverLocalService service = new AppiumServiceBuilder().withAppiumJS(new File("C:\\Users\\mahiyarwadia\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress("127.0.0.1").usingPort(4723).build();
service.start();
UiAutomator2Options options = new UiAutomator2Options();
options.setDeviceName ("MahiyarPhone");
options.setApp ("//Users//mahiyarwadia//eclipse-workspace//Appium//src//test//java//resources//ApiDemos-debug.apk");
}
}
Could you try the following?
AppiumServiceBuilder builder = new AppiumServiceBuilder()
.withAppiumJS(new File("C:\\Users\\mahiyarwadia\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress("127.0.0.1")
.usingPort(4723);
AppiumDriverLocalService service = AppiumDriverLocalService.buildService(builder);
service.start();
If it still does not work:
Are you able to start the server via the GUI or command line?
Is the Appium path correct?
How do I configure Micronaut app using Vert.x and testcontainers? I'm trying:
application-test.yml
datasources:
default:
url: jdbc:tc:mysql:8:///db
driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
vertx:
mysql:
client:
uri: jdbc:tc:mysql:8:///db
Tests with micronaut-data-jdbc work, but with micronaut-vertx-mysql-client not work:
Error:
Message: Cannot parse invalid connection URI: jdbc:tc:mysql:8:///db
I'm not very familiar with testecontainers, but it seems like it doesn't come up with a fixed port, so I don't know how to configure the connection URI.
Thanks!
It might be a problem that micronaut-vertx-mysql-client does not support the Testcontainers JDBC URL scheme (hard to say without further logs).
In this case, I would suggest to use Testcontainers with database container objects instead of the special JDBC URL.
I got a solution to the problem:
Micronaut + jdbc hikari + vertx mysql client + flyway mysql
package br.com.app;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.env.PropertySource;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.client.HttpClient;
import io.micronaut.runtime.EmbeddedApplication;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
#Testcontainers
class AuthTest {
static Logger log = LoggerFactory.getLogger(AuthTest.class.getName());
#Container
static MySQLContainer mysql = new MySQLContainer("mysql:8");
private HttpClient client;
private static EmbeddedApplication application;
private static ApplicationContext context;
#BeforeAll
public static void initTests(){
log.info("Mysql is running {}, port {}", mysql.isRunning(), mysql.getFirstMappedPort());
var port = mysql.getFirstMappedPort();
var host = mysql.getHost();
var database = mysql.getDatabaseName();
var user = mysql.getUsername();
var password = mysql.getPassword();
var url = String.format("jdbc:mysql://%s:%s/%s", host, port, database);
application = ApplicationContext.run(EmbeddedApplication.class,
PropertySource.of(
"test",
CollectionUtils.mapOf(
"vertx.mysql.client.port", port,
"vertx.mysql.client.host", host,
"vertx.mysql.client.database", database,
"vertx.mysql.client.user", user,
"vertx.mysql.client.password", password,
"datasources.default.url", url,
"datasources.default.username", user,
"datasources.default.password", password,
"flyway.datasources.default.enabled", true
)
));
context = application.getApplicationContext();
}
#BeforeEach
void beforeEach(){
this.authService = context.getBean(AuthService.class);
this.client = context.getBean(HttpClient.class);
}
#Test
void testItWorks() {
Assertions.assertTrue(application.isRunning());
}
// api tests
}
Help links:
https://dev.to/major13ua/micronaut-integration-testing-using-testcontainers-2e30
https://github.com/major13ua/micronaut-tc/blob/main/src/test/java/com/example/testcontainer/controller/DemoControllerTest.java
I am trying to run a python script from java; in py script I am using pywinauto package and want to initiate notepad++.
When I am running this script it works fine, however when same is called from Java main method it throws TypeError: __enter__(): expected 1 args; got 0.
Below is python script:
import sys
sys.path.append("C:\\jython2.7.0\\bin")
sys.path.append("C:\\Python27")
sys.path.append("C:\\Python27\\Lib")
sys.path.append("C:\\jython2.7.0\\Lib")
def runpradeep():
print "trying to run it"
from pywinauto.application import Application
app = Application().start('C:\\Program Files (x86)\\Notepad++\\notepad++.exe')
app.kill()
runpradeep()
and below is java class:
package himalaya;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Properties;
public class OpenBoApplication {
public static void main(String[] args) throws ScriptException {
Properties props = new Properties();
props.put("python.home", "C:\\Python27");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:path to py script\\renatoplease.py");
interpreter.exec("runpradeep()");
}
}
Below is error log:
Exception in thread "main" Traceback (most recent call last):
File "D:\pbhardwa\IdeaProjects\javapythongroovy\src\com\ingenico\runmiddleware\renatoplease.py", line 16, in
runpradeep()
File "D:\pbhardwa\IdeaProjects\javapythongroovy\src\com\ingenico\runmiddleware\renatoplease.py", line 11, in runpradeep
from pywinauto.application import Application
File "pyclasspath/pywinauto/application.py", line 72, in
File "C:\Python27\Lib\multiprocessing__init__.py", line 65, in
from multiprocessing.util import SUBDEBUG, SUBWARNING
File "C:\Python27\Lib\multiprocessing\util.py", line 39, in
import threading # we want threading to install it's
File "C:\Python27\Lib\threading.py", line 1191, in
_shutdown = _MainThread()._exitfunc
File "C:\Python27\Lib\threading.py", line 1083, in init
self._Thread__started.set()
File "C:\Python27\Lib\threading.py", line 582, in set
"""
File "C:\Python27\Lib\threading.py", line 286, in enter
return self.lock.__enter()
TypeError: enter(): expected 1 args; got 0
I am using Intellij ultimate edition and Pycharm plugin is installed. I have also installed pywinauto(as mentioned enter link description here), pythonpath is also set. Also added jython dependencies to class path. Attaching complete project
Any help will surely help us.
I am building simple chatting application using WebSocket using Eclipse and apache 7.x .However I am not able to compile my code cause it shows import javax.websocket cannot be resolved. After Googling a lot i found Link that shows external jar in application. I added a jar in my library section. It removed my current error but gave another. Now it showing WebSocket connection to 'ws://localhost:8080/WebSocket/socket' failed: Error during WebSocket handshake: Unexpected response code: 404
I'v tried a lot like adding servlet-api.jar to build path from apache lib. And also find some information like It provides also the javax.websocket-api-1.0.jar library so this is not needed in you application. You might need it at compile time but the server will provide it at runtime
Now I got stuck like in recursion. when I remove my jar got first error and when I add external jar then got second error. please help me in this issue cause we are developing mini project for real time collaborative editor and we are suppose to use websocket in it.
Now here is my code for websocket(not using maven):
WebSocket.java
package com.psl.service;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
#ServerEndpoint("/socket")
public class WebSocket {
Set<Session> sessionSet = Collections.synchronizedSet(new HashSet<>());
#OnOpen
public void onOpen(Session webSession) {
System.out.println("Opened");
sessionSet.add(webSession);
}
#OnMessage
public void onMessage(String message, Session webSession) throws IOException {
System.out.println("Got message "+message);
String username = (String)webSession.getUserProperties().get("username");
if(username==null) {
webSession.getUserProperties().put("username", message);
webSession.getBasicRemote().sendText(buildJSON(username, message));
}
else {
for(Session s : sessionSet) {
s.getBasicRemote().sendText(buildJSON(username, message));
}
}
}
private String buildJSON(String string, String string2) {
String jsonData="";
JSONObject obj=new JSONObject();
try {
obj.put("message",string + ":" + string2);
StringWriter out = new StringWriter();
JSONWriter jwriter = new JSONWriter(out);
jwriter.key(string).value(string2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#OnClose
public void onClose() {
System.out.println("CLosed");
sessionSet.remove(sessionSet);
}
}
chat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
var websocket = new WebSocket("ws://localhost:8080/WebSocketDemo/socket");
websocket.onmessage = function onMessage(message) {
var jsonData = JSON.parse(message.data);
if(jsonData.message != null) {
messageTextArea.value += jsonData.message + "\n";
}
}
function sendMessage() {
websocket.send(sendText.value);
sendText.value = "";
}
</script>
</head>
<body>
<textarea rows="30" cols="70" id="messageTextArea" ></textarea><br /><br />
<input id="sendText">
<input type="button" value="Send" onclick="sendMessage()">
</body>
</html>
I got answer for this query. This is because the added jar overrides my internal jars in apache tomcat. And I am using older tomcat that have not websocket-api.jar
So My solution for this problem is either use glashfish 4.x or else use apache tomcat 8.x that gives us required jar to run websocket. No need to add any extra websocket api jar.
I'm trying to write a REST service in java using Jersey and Glassfish Grizzly. I have a very simple case working internally, but can't seem to call on the server from an external address. I've tried using a variety of different pairs of machines with externally visible IP's, and tried specifying the actual IP address in the server instead of localhost, but nothing works. I'm somewhat loosely following the official user guide here. My resource:
package resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/simpleREST")
public class SimpleRESTResource
{
#GET
#Produces("text/plain")
public String getMessage()
{
return "Message from server\n";
}
}
And the server:
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main
{
public static final URI BASE_URI = UriBuilder.fromUri("http://localhost").port(9998).build();
public static void main(String[] args) throws IOException
{
System.out.println("Starting grizzly...");
ResourceConfig rc = new PackagesResourceConfig("resources");
HttpServer myServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
System.out.println(String.format("Jersey app started with WADL available at %s/application.wadl\n" +
"Try out %s/simpleREST\nHit enter to stop it...", BASE_URI, BASE_URI));
System.in.read();
myServer.stop();
}
}
On the same machine, I can successfully interact with the server using
curl -X GET localhost:9998/simpleREST
OR
curl -X GET [external numeric address]:9998/simpleREST
Many thanks in advance for any suggestions.
SOLUTION
I have fixed this problem by setting the server URI to http://0.0.0.0:9998 instead of localhost, 127.0.0.1, or the actual address.
To make a server IP adress visible outside of localhost, you must fist open the neccessary firewall ports(if you have one), or use "0.0.0.0" instead of "localhost" in order for the server to listen to all IP addresses and network adapters. Before testing it in your local network, try pinging your server device from your client device to check if there is an actual connection or if the devices are not connected at all.
With Jersey and Grizzly 2.30, it's simpler:
final ResourceConfig rc = new ResourceConfig().packages("com.rest");
HttpServer httpServer = Grizzly
HttpServerFactory.createHttpServer(URI.create("http://0.0.0.0:9998/api/"), rc);
or, you can try these codes below:
ResourceConfig rc = new PackagesResourceConfig("your-rest-packages");
HttpHandler handler = ContainerFactory.createContainer(HttpHandler.class, rc);
server = new HttpServer();
server.getServerConfiguration().addHttpHandler(handler);
//attach listeners
InetAddress localHost = InetAddress.getLocalHost();
String localHostAddr = localHost.getHostAddress();
NetworkListener localHostListener = new NetworkListener("localhost", localHostAddr, port);
server.addListener(localHostListener);
InetAddress loopback = InetAddress.getLoopbackAddress();
String loopbackAddr = loopback.getHostAddress();
NetworkListener loopbackListener = new NetworkListener("loopback", loopbackAddr, port);
now your server could both list to localhost and loopback