How to connect to zabbix server using java API - zabbix

I am trying to connect to a Zabbix server. I am able to access the Zabbix server running on port 10051 via the web browser, however, I am unable to connect to the same server using Java API. Following is the code that I am using to connect
import io.github.cgi.zabbix.api.DefaultZabbixApi;
import io.github.cgi.zabbix.api.ZabbixApi;
public class TestClass {
ZabbixApi zabbixApi;
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.before();
tc.testLogin();
// tc.testVersion();
}
public void before() {
String url = "http://xxx.xxx.xxx.xxx:10051/zabbix/api_jsonrpc.php";
zabbixApi = new DefaultZabbixApi(url);
zabbixApi.init();
}
public void testLogin() {
String user = "admin";
String password = "zabbix";
boolean login = zabbixApi.login(user, password);
System.out.println("login result:" + login);
}
public void testVersion() {
String version = zabbixApi.apiVersion();
System.err.println(version);
System.out.println("version := " + version);
}
}
Classpath is:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="lib" path="D:/Software_Development/Jars/zabbix-api-0.0.2.jar"/>
<classpathentry kind="lib" path="D:/Software_Development/Jars/httpclient-4.5.3.jar"/>
<classpathentry kind="lib" path="D:/Software_Development/Jars/jackson-all-1.9.9.jar/jackson-all-1.9.9.jar"/>
<classpathentry kind="lib" path="D:/Software_Development/Jars/httpcore-4.4.8.jar"/>
<classpathentry kind="lib" path="D:/Software_Development/Jars/commons-logging-1.2/commons-logging-1.2.jar"/>
<classpathentry kind="lib" path="D:/Software_Development/Jars/slf4j-api-1.7.25.jar"/>
<classpathentry kind="output" path="bin"/>
Error while running this code is :
Exception in thread "main" java.lang.RuntimeException: DefaultZabbixApi call exception!
at io.github.cgi.zabbix.api.DefaultZabbixApi.call(DefaultZabbixApi.java:142)
at io.github.cgi.zabbix.api.DefaultZabbixApi.login(DefaultZabbixApi.java:72)
at TestClass.testLogin(TestClass.java:25)
at TestClass.main(TestClass.java:12)
Caused by: org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:839)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at io.github.cgi.zabbix.api.DefaultZabbixApi.call(DefaultZabbixApi.java:138)
... 3 more
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:149)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:286)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:257)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:207)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:684)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
... 7 more
Need help in connecting to Zabbix server using Java API.

You are connecting to the zabbix-server (port 10051). API is a part of zabbix-frontend, so please connect to your web server (port depends on your web server configuration, usually 80).

change the below URL to port 80 or on which zabbix was running.
String url = "http://xxx.xxx.xxx.xxx:10051/zabbix/api_jsonrpc.php";

Related

Error connect SpringBoot with Mysql

I'm trying to connect to the MySQL database with SpringBoot but I get an error
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.sql.*;
#RestController
#RequestMapping
public class miController {
private static String driver = "com.mysql.jdbc.Driver";
private static String server = "jdbc:mysql://localhost/test";
private static Connection conexion = null;
miController(){
conectar();
}
private void conectar() {
try {
Class.forName(driver);
conexion = DriverManager.getConnection(server, "Yo", "pass");
} catch (Exception e) {
System.out.println("Error: Imposible realizar la conexion a BD.");
e.printStackTrace();
}
}
#RequestMapping(value = "/hola", method = RequestMethod.GET)
public #ResponseBody String hola() {
return "Hola mundo2!! " ;
}
}
The code of the error it gives when the application starts is:
Thu Jun 28 17:24:42 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Error: Imposible realizar la conexion a BD.
java.sql.SQLException: Unable to load authentication plugin 'caching_sha2_password'.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:869)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:865)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1746)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2188)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2219)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2014)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
It is my first app with SpringBoot and I don't understand why I get error when I connect with mysql... I think that I saw something the SSL, but I don't understand... Ty
Mysql should be configured in the application.properties file for SpringBoot. This is the beauty of SpringBoot.
Sample of the configuration as follows:
#Mysql connection configurations
spring.datasource.url = jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false
spring.datasource.username = yourDbUserName
spring.datasource.password = yourDbPassword
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

Unable to connect to any of the specified MySQL hosts. 6

I hosted my website on web server.
I run my website in visual studio using the server database, it worked fine but when i hosted it on the web server, after one day it started giving me this error.
Sometimes some pages works fine and sometimes the same pages gives this error.
What would be the problem ?
Any solution will be appreciable.
This is the error -
Server Error in '/AttWeb' Application.
Unable to connect to any of the specified MySQL hosts.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the specified MySQL hosts.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]
MySql.Data.MySqlClient.NativeDriver.Open() +1268
MySql.Data.MySqlClient.Driver.Open() +22
MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) +218
MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() +287
MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() +93
MySql.Data.MySqlClient.MySqlPool.GetConnection() +65
MySql.Data.MySqlClient.MySqlConnection.Open() +543
System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +2086
System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) +278
System.Web.UI.WebControls.ListControl.PerformSelect() +37
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +74
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +114
System.Web.UI.WebControls.ListControl.OnPreRender(EventArgs e) +23
System.Web.UI.Control.PreRenderRecursiveInternal() +88
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4775
and this is my code -
private MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
protected void keepData()
{
MySqlCommand cmd = new MySqlCommand("select deptName, year from subject where subId = '" + Request.Cookies["subject"].Value + "';", con);
try
{
con.Open();
MySqlDataReader result = cmd.ExecuteReader();
if (result.Read())
{
Response.Cookies["deptName"].Value = result["deptName"].ToString();
Response.Cookies["year"].Value = result["year"].ToString();
}
}
catch (MySqlException s) { Label1.Text = "Connection Failed"; }
catch (Exception ex) { Label1.Text = "Network Error"; }
con.Close();
}
and my web.config file contains connection string as
<connectionStrings>
<add name="DBCS"
connectionString="Server=MYSQL5016.SmarterASP.NET;Database=db_a0d03d_demo1;Uid=a0d03d_demo1;Pwd=***"
providerName="MySql.Data.MySqlClient" />
I am new to this please help me.
When you try to connect to other not local database you need allow remote request.

How to send mails from Java mail API from a server not having internet connection and using web server?

I am using JAVA mail API to send mails and using SMTP. When I am putting the code in the test server it is successfully sending mails as it is having internet connection. But in the production there is no internet connection. Is it possible to send mails using the web server? The code that I am using to send mails is as follows.
final String username = "momkutty#gmail.com";
final String password = "password";
Properties props = new Properties();
System.out.println("Setting properties");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.google.com");
props.put("mail.smtp.port", "25");
System.out.println("Properties set successfully");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
System.out.println("Setting message properties");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("momkutty#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("sumankalyan.roy#cmcltd.com"));
message.setSubject("Test Subject");
message.setText("Hey!!!! This is a TEST mail using SMTP SMTP port no.25.....");
System.out.println("Going to send mail...");
Transport.send(message);
System.out.println("Mail has been Sent");
} catch (MessagingException e) {
e.printStackTrace();
}
}e
If you have a SOCKS proxy server, see this JavaMail FAQ entry.
If you only have a web proxy server, you might need something like corkscrew.
I am using my web server IP as "socksProxyHost" and 1080 as "socksProxyPort"...!! refer the following lines....!
props.setProperty("proxySet","true");
props.setProperty("socksProxyHost","10.10.30.146");
props.setProperty("socksProxyPort","1080");
and trying to send mails through port no. 587...!!
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
but it says..
javax.mail.MessagingException: Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.cmcltd.vtms.sms.smsalert.SmsEmailAlerts.testMail(SmsEmailAlerts.java:1029)
at com.cmcltd.vtms.sms.smsalert.ScheduleJob.execute(ScheduleJob.java:25)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:534)
Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
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 com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
... 10 more
Is it because the 587 port is blocked in the web server? Or there is something wrong in the code...!!?

mysql connectivity issue: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I am attemping to establish Mysql connectivity to Database using Java Struts1. Here the code snippet.Also I added mysql-connector-java-5.0.8-bin.jar to web-inf/lib folder .
Also added the same to classpath variable.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class select {
public void connection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}.
This is Error message. What steps am I missing. Kindly suggest ASAP.
-------- MySQL JDBC Connection Testing ------------
Where is your MySQL JDBC Driver?
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Com.Candidjava.select.connection(select.java:14)
at Com.Candidjava.LoginAction.execute(LoginAction.java:26)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Add mysql-connector-java-5.0.8-bin.jar to your tomcat installation directory as well. And when right click on your project and select build path then libraries. and inside libraries Apache Tomcat you should find your connector jar then only your mysql will work
try this is an example of jdbc connection to mysql database:
import java.sql.DriverManager;
public class Connection {
private static java.sql.Connection conex = null;
public static java.sql.Connection getConnectionInstance() {
if (conex == null) {
try {
// connection to database
Class.forName("com.mysql.jdbc.Driver");
conex = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/databaseName","root",
"MySQLPassword");
return conex;
} catch (Exception e) {
}
}
return conex;
}
}
make sure you have opened the port selected during install.

connecting to MySQL using JDBC in eclipse

So I want to create a JDBC connection to MySQL server that is installed on my pc, here are the steps,
I installed MySQL with the username and password "root", downloaded mysql-connector-java and from theere I coped the JAR "mysql-connector-java-5.1.12-bin" to "C:\Sun\SDK\jdk\jre\lib\ext", I then added it as an external JAR in my project in eclipse, now in my class I have this code:
public void initialiseDatabase()
{
try {
// Load the Driver class.
Class.forName("com.mysql.jdbc.Driver");
//Create the connection using the static getConnection method
databaseConnection = DriverManager.getConnection (databaseUrl+databaseName,
dbUserName, dbPassword);
sqlStatement = databaseConnection.createStatement();
}
catch (SQLException e) {e.printStackTrace();}
catch (Exception e) {e.printStackTrace();}
}
(this is going to be psuedocode cause I am reading from a properties file and don't want the one helping me reading through long lines of code from main to figure out all the variables),
where databaseUrl = "127.0.0.1"
dbUserName = "root"
dbPassword = "root"
databaseName = "MySQL" //this one I am not sure of, do I need to create it or is it set inherenrly?
now the MySQL server is up and running, but when I call the method initialiseDatabase the following exception is thrown:
"java.sql.SQLException: No suitable driver found for rootroot
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Proxy$JDBCConnection.initialiseDatabase(Proxy.java:721)"
when line 721 is:
sqlStatement = databaseConnection.createStatement();
Where have I gone wrong?
thanks
Your database url should look like this:
jdbc:mysql://host:port/database
Example, if you use localhost, the default port and a database named cachedb, your url would be:
jdbc:mysql://localhost/cachedb