├── .restyled.yaml
├── renovate.json
├── .gitignore
├── src
└── main
│ └── java
│ └── com
│ └── smartmarmot
│ ├── common
│ ├── SmartLogger.java
│ └── db
│ │ ├── DBConn.java
│ │ ├── DBJob.java
│ │ └── DBEnquiry.java
│ ├── orabbix
│ ├── Bootstrap.java
│ ├── Utility.java
│ ├── Constants.java
│ ├── Querybox.java
│ ├── Query.java
│ ├── Orabbixmon.java
│ ├── Sender.java
│ └── Configurator.java
│ └── zabbix
│ └── ZabbixItem.java
├── .github
└── workflows
│ └── issue-metrics.yml
├── README.md
└── pom.xml
/.restyled.yaml:
--------------------------------------------------------------------------------
1 | enabled: true
2 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": [
4 | "config:recommended"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | pom.xml.tag
3 | pom.xml.releaseBackup
4 | pom.xml.versionsBackup
5 | pom.xml.next
6 | release.properties
7 | dependency-reduced-pom.xml
8 | buildNumber.properties
9 | .mvn/timing.properties
10 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar
11 | .mvn/wrapper/maven-wrapper.jar
12 |
13 | # Eclipse m2e generated files
14 | # Eclipse Core
15 | .project
16 | # JDT-specific (Eclipse Java Development Tools)
17 | .classpath
18 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/common/SmartLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.common;
21 |
22 | import org.apache.log4j.Level;
23 |
24 | import org.apache.log4j.Logger;
25 |
26 | import com.smartmarmot.orabbix.Constants;
27 |
28 |
29 | public class SmartLogger {
30 | public static void logThis(Level level, String message) {
31 | Logger logger = Logger.getLogger(Constants.PROJECT_NAME);
32 | if (message == null) {
33 | message = new String("");
34 | }
35 | logger.log(level, message);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/common/db/DBConn.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.common.db;
21 |
22 | import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
23 |
24 | public class DBConn {
25 | private SharedPoolDataSource spds;
26 | private String dbaname;
27 |
28 | public DBConn(SharedPoolDataSource _spds, String _name) {
29 | if (_spds == null)
30 | throw new RuntimeException("empty datasource");
31 | this.spds = _spds;
32 | if (_name != null && _name.length() > 0)
33 | this.dbaname = _name;
34 | else
35 | this.dbaname = "undefined";
36 | }
37 |
38 | public String getName() {
39 | return this.dbaname;
40 | }
41 |
42 | public SharedPoolDataSource getSPDS() {
43 | return this.spds;
44 | }
45 |
46 | }
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Bootstrap.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | * @author Andrea Dalle Vacche
4 | *
5 | * This file is part of DBforBIX.
6 | *
7 | * Orabbix is free software: you can redistribute it and/or modify it under the
8 | * terms of the GNU General Public License as published by the Free Software
9 | * Foundation, either version 3 of the License, or (at your option) any later
10 | * version.
11 | *
12 | * Orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
13 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 | * details.
16 | *
17 | * You should have received a copy of the GNU General Public License along with
18 | * Orabbix. If not, see .
19 | */
20 |
21 | package com.smartmarmot.orabbix;
22 | import com.smartmarmot.orabbix.Constants;
23 |
24 | public class Bootstrap {
25 |
26 |
27 | private static Orabbixmon runner;
28 | public static void printUsage() {
29 | System.out.println(Constants.BANNER);
30 | }
31 |
32 | /**
33 | * @param args
34 | * @throws Exception
35 | */
36 | public static void main(final String[] args) {
37 | try {
38 | if (args.length > 2) {
39 | printUsage();
40 | return;
41 | }
42 |
43 | String cmd = new String(args[0].toString());
44 | String configFile = new String(args[1].toString());
45 |
46 |
47 | if (cmd.equalsIgnoreCase("start")) {
48 | runner = new Orabbixmon(configFile);
49 | new Thread(runner);
50 | runner.run();
51 | }
52 | else if (args[0].equalsIgnoreCase("stop")) {
53 | if (runner != null) {
54 | runner.terminate();
55 | System.err.println("Runner terminated");
56 | }
57 | else
58 | System.err.println("No daemon running");
59 | } else{
60 | printUsage();
61 | }
62 | } catch (Exception ex) {
63 | ex.printStackTrace();
64 | }
65 |
66 | }
67 |
68 |
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Utility.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.orabbix;
21 |
22 | import java.io.File;
23 | import java.io.FileOutputStream;
24 | import java.io.IOException;
25 | import java.io.PrintStream;
26 |
27 | import org.apache.log4j.Level;
28 |
29 | import com.smartmarmot.common.SmartLogger;
30 |
31 | public class Utility {
32 |
33 | public static void writePid(String _pid, String _pidfile) throws Exception {
34 | try {
35 |
36 | // Open an output stream
37 |
38 | File target = new File(_pidfile);
39 |
40 | File newTarget = new File(target.getAbsoluteFile()
41 | .getCanonicalPath());
42 | target = null;
43 |
44 | if (newTarget.exists()) {
45 | boolean success = newTarget.delete();
46 | if (!success) {
47 | SmartLogger.logThis(Level.ERROR,
48 | "Delete: deletion failed "
49 | + newTarget.getAbsolutePath());
50 | }
51 | }
52 | if (!newTarget.exists()) {
53 | FileOutputStream fout = new FileOutputStream(newTarget);
54 | new PrintStream(fout).print(_pid);
55 | // Close our output stream
56 | fout.close();
57 | }
58 |
59 | }
60 | // Catches any error conditions
61 | catch (IOException e) {
62 | SmartLogger.logThis(Level.ERROR, "Unable to write to file "
63 | + _pidfile + " error:" + e);
64 | }
65 |
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/zabbix/ZabbixItem.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 |
21 |
22 | package com.smartmarmot.zabbix;
23 |
24 | public final class ZabbixItem {
25 |
26 | private final String key;
27 | private final String value;
28 | private final String hostname;
29 |
30 | /**
31 | * Create a literal value item.
32 | *
33 | * @param key
34 | * The monitoring server's key for this statistic.
35 | * @param value
36 | * The literal value.
37 | */
38 |
39 | /*public ZabbixItem(final String key, final String value) {
40 | if (key == null || "".equals(key.trim())) {
41 | throw new IllegalArgumentException("empty key");
42 | }
43 | if (value == null) {
44 | throw new IllegalArgumentException("null value for key '" + key
45 | + "'");
46 | }
47 |
48 | this.key = key;
49 | this.value = value;
50 | this.hostname = null;
51 | }
52 | */
53 | public ZabbixItem(final String key, final String value,
54 | final String hostname) {
55 | if (key == null || "".equals(key.trim())) {
56 | throw new IllegalArgumentException("empty key");
57 | }
58 | if (value == null) {
59 | throw new IllegalArgumentException("null value for key '" + key
60 | + "'");
61 | }
62 | if (hostname == null) {
63 | throw new IllegalArgumentException("null value for hostname '"
64 | + hostname + "'");
65 | }
66 |
67 | this.key = key;
68 | this.value = value;
69 | this.hostname = hostname;
70 | }
71 |
72 | /**
73 | * @return The current hostname for this item.
74 | * @throws Exception
75 | */
76 | public String getHostName() throws Exception {
77 | return hostname;
78 | // return JMXHelper.Query(value, attribute);
79 | }
80 |
81 | /**
82 | * Find the item's key.
83 | *
84 | * @return The monitoring server's key for this item.
85 | */
86 | public String getKey() {
87 | return key;
88 | }
89 |
90 | /**
91 | * @return The current value for this item.
92 | * @throws Exception
93 | * When the item could not be queried in the platform's mbean
94 | * server.
95 | */
96 | public String getValue() throws Exception {
97 | return value;
98 | // return JMXHelper.Query(value, attribute);
99 | }
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/.github/workflows/issue-metrics.yml:
--------------------------------------------------------------------------------
1 | # https://github.com/github/issue-metrics/blob/main/docs/authenticating-with-github-app-installation.md
2 | name: Monthly repo metrics
3 | on:
4 | workflow_dispatch:
5 | schedule:
6 | - cron: '3 2 1 * *'
7 |
8 | permissions:
9 | contents: read
10 |
11 | jobs:
12 | build:
13 | name: issue metrics
14 | runs-on: ubuntu-latest
15 | permissions:
16 | issues: write
17 | pull-requests: read
18 |
19 | steps:
20 |
21 | - name: Get dates for last month
22 | shell: bash
23 | run: |
24 | # Calculate the first day of the previous month
25 | first_day=$(date -d "last month" +%Y-%m-01)
26 |
27 | # Calculate the last day of the previous month
28 | last_day=$(date -d "$first_day +1 month -1 day" +%Y-%m-%d)
29 |
30 | #Set an environment variable with the date range
31 | echo "$first_day..$last_day"
32 | echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV"
33 |
34 | - name: Run issue-metrics tool
35 | uses: github/issue-metrics@v3
36 | env:
37 | GH_APP_ID: ${{ secrets.GH_APP_ID }}
38 | GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
39 | GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
40 | SEARCH_QUERY: 'repo:snickerjp/orabbix is:issue created:${{ env.last_month }} -reason:"not planned"'
41 |
42 | # - name: Get user names from team
43 | # run: |
44 | # teamMembers="$(gh api /orgs/ORG/teams/TEAM_SLUG/members | jq -r '.[].login' | paste -sd, -)"
45 | # echo 'TEAM_MEMBERS='$teamMembers >> $GITHUB_ENV
46 | # env:
47 | # GITHUB_TOKEN: ${{ secrets.CUSTOM_TOKEN }}
48 |
49 | - name: Create issue
50 | uses: peter-evans/create-issue-from-file@v5
51 | id: create_monthly_report_issue # Add id
52 | with:
53 | title: Monthly issue metrics report
54 | token: ${{ secrets.GITHUB_TOKEN }}
55 | content-filepath: ./issue_metrics.md
56 | labels: metrics # Corrected labels
57 | #assignees: ${{ env.TEAM_MEMBERS }}
58 |
59 | - name: Close monthly report issue # Add step to close issue
60 | uses: peter-evans/close-issue@v3
61 | with:
62 | repository: snickerjp/orabbix
63 | issue-number: ${{ steps.create_monthly_report_issue.outputs.issue-number }}
64 | comment: Automated report, closing.
65 |
66 | - name: Report on PRs
67 | uses: github/issue-metrics@v3
68 | env:
69 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
70 | SEARCH_QUERY: 'repo:snickerjp/orabbix is:pr created:${{ env.last_month }} -is:draft'
71 |
72 | - name: Create report for PRs
73 | uses: peter-evans/create-issue-from-file@v5
74 | id: create_pr_report_issue # Add id
75 | with:
76 | title: Monthly PR metrics report
77 | token: ${{ secrets.GITHUB_TOKEN }}
78 | content-filepath: ./issue_metrics.md
79 | labels: metrics # Corrected labels
80 |
81 | - name: Close PR report issue # Add step to close issue
82 | uses: peter-evans/close-issue@v3
83 | with:
84 | repository: snickerjp/orabbix
85 | issue-number: ${{ steps.create_pr_report_issue.outputs.issue-number }}
86 | comment: Automated report, closing.
87 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Constants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.orabbix;
21 |
22 |
23 | public class Constants {
24 | public static final String VERSION = "Version 1.2.3 ";
25 | public static final String BANNER = Constants.PROJECT_NAME + " " + VERSION;
26 | public static final String PROJECT_NAME = "Orabbix";
27 | public static final String DATABASES_LIST = "DatabaseList";
28 | public static final String DELIMITER = ",";
29 | public static final String QUERY_LIST = "QueryList";
30 | public static final String QUERY_LIST_FILE = "QueryListFile";
31 | public static final String EXTRA_QUERY_LIST_FILE = "ExtraQueryListFile";
32 | public static final String QUERY_POSTFIX = "Query";
33 | public static final String QUERY_NO_DATA_FOUND = "NoDataFound";
34 | public static final String CONN_URL = "Url";
35 | public static final String CONN_USERNAME = "User";
36 | public static final String CONN_PASSWORD = "Password";
37 | public static final String CONN_DEFAULT_USERNAME = "DefaultUser";
38 | public static final String CONN_DEFAULT_PASSWORD = "DefaultPassword";
39 | public static final String CONN_MAX_ACTIVE = "MaxActive";
40 | public static final String CONN_MAX_IDLE = "MaxIdle";
41 | public static final String CONN_MAX_WAIT = "MaxWait";
42 | public static final String ORACLE = "Oracle";
43 | public static final String ORACLE_VALIDATION_QUERY = "SELECT SYSDATE FROM DUAL";
44 | public static final String ORACLE_DRIVER = "oracle.jdbc.OracleDriver";
45 | public static final String ORACLE_WHOAMI_QUERY = "SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER') FROM DUAL";
46 | public static final String ORACLE_DBNAME_QUERY = "SELECT SYS_CONTEXT ('USERENV', 'DB_NAME') FROM DUAL";
47 | public static final String RACE_CONDITION_QUERY = "RaceConditionQuery";
48 | public static final String RACE_CONDITION_EXCLUDE_COLUMNS = "RaceConditionQueryExcludeColumnsList";
49 | public static final String RACE_CONDITION_VALUE = "RaceConditionValue";
50 | public static final String QUERY_PERIOD = "Period";
51 | public static final String QUERY_DEFAULT_PERIOD = "DefaultQueryPeriod";
52 | public static final String QUERY_ACTIVE = "Active";
53 | public static final String ZABBIX_SERVER_LIST = "ZabbixServerList";
54 | public static final String ZABBIX_SERVER_PORT = "Port";
55 | public static final String ZABBIX_SERVER_HOST = "Address";
56 | public static final String ORABBIX_PIDFILE = "OrabbixDaemon.PidFile";
57 | public static final String ORABBIX_DAEMON_SLEEP = "OrabbixDaemon.Sleep";
58 | public static final String ORABBIX_DAEMON_THREAD = "OrabbixDaemon.MaxThreadNumber";
59 | public static final int ZABBIX_SERVER_DEFAULT_PORT = 10051;
60 | public static final String QUERY_TRIM = "Trim";
61 | public static final String QUERY_SPACE = "AddSpaces";
62 | public static final String QUERY_EXCLUDE_COLUMNS = "ExcludeColumnsList";
63 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Orabbix - Oracle Database Monitoring for Zabbix
2 |
3 | > [!IMPORTANT]
4 | > **Official Oracle Zabbix Integration**: An official Oracle monitoring template is provided by Zabbix. We strongly recommend using this for more comprehensive and up-to-date monitoring features. 👍
5 | > * [Oracle monitoring and integration with Zabbix](https://www.zabbix.com/jp/integrations/oracle)
6 |
7 | > [!WARNING]
8 | > **Regarding Orabbix Development Status**: ⚠️
9 | > * Currently, active new feature development for Orabbix is not being pursued. 🛑
10 | > * Future new feature development is also challenging. 😥
11 | > * Bug fixes and security responses will be handled on a best-effort basis, but there are no plans for adding new features or making major changes. 🛠️
12 | > * Thank you for your long-term use. 🙏
13 |
14 | [](https://app.codacy.com/app/snickerjp/orabbix?utm_source=github.com&utm_medium=referral&utm_content=snickerjp/orabbix&utm_campaign=Badge_Grade_Settings)
15 |
16 | Orabbix is a monitoring solution that integrates Oracle Database with Zabbix monitoring system.
17 |
18 | ## Compatibility
19 |
20 | ### Zabbix Versions
21 | - ✅ Zabbix 4.0
22 | - ✅ Zabbix 5.0
23 | - ✅ Zabbix 6.0
24 | - ✅ Zabbix 7.0
25 |
26 | ### Java Versions
27 | - ✅ Java 8 (Recommended)
28 | - ✅ Java 17
29 | - ✅ Java 21 (Testing)
30 | - ⚠️ Java 7 (Not actively tested)
31 |
32 | For Java support information, see:
33 | - [Oracle Java SE Support Roadmap (EN)](https://www.oracle.com/java/technologies/java-se-support-roadmap.html)
34 | - [Oracle Java SE Support Roadmap (JP)](https://www.oracle.com/jp/java/technologies/java-se-support-roadmap.html)
35 |
36 | ### Oracle Database Versions
37 | - ✅ Oracle 11g
38 | - ✅ Oracle 12c
39 | - ✅ Oracle 21c XE
40 | - ✅ Oracle 23c Free
41 |
42 | ## Building from Source
43 |
44 | ### Prerequisites
45 | - Java Development Kit (JDK 8 or later)
46 | - Git
47 | - Maven 3.x
48 |
49 | ### Build Instructions
50 |
51 | #### Using Maven (Recommended)
52 | 1. Clone the repository:
53 | ```sh
54 | git clone https://github.com/snickerjp/orabbix.git -b main
55 | cd orabbix
56 | ```
57 |
58 | 2. Build with Maven:
59 | ```sh
60 | mvn clean package
61 | ```
62 |
63 | The built JAR files will be available in the `target` directory:
64 | - `orabbix-1.2.3.jar`: Basic JAR file
65 | - `orabbix-1.2.3-jar-with-dependencies.jar`: JAR with all dependencies included
66 |
67 | #### Alternative Build Method (Legacy)
68 |
69 | 1. Clone the repository:
70 | ```sh
71 | git clone https://github.com/snickerjp/orabbix.git -b legacy
72 | cd orabbix
73 | ```
74 |
75 | 2. Download Orabbix:
76 | Download from: https://sourceforge.net/projects/orabbix/
77 | ```sh
78 | unzip orabbix-1.2.3.zip
79 | # OR
80 | unzip -d orabbix-1.2.3 orabbix-1.2.3.zip
81 | ```
82 |
83 | 3. Compile:
84 | ```sh
85 | # Requires java-1.8.0-openjdk-devel (example for RHEL-based systems)
86 | javac -cp "$(for _JAR in orabbix-1.2.3/lib/*.jar;do echo -n $_JAR:;done)orabbix-1.2.3/orabbix-1.2.3.jar" com/smartmarmot/orabbix/Sender.java
87 | mkdir -p ./build
88 | cp orabbix-1.2.3/orabbix-1.2.3.jar ./build
89 | cd build
90 | jar -xvf orabbix-1.2.3.jar com
91 | cp ../com/smartmarmot/orabbix/Sender.class com/smartmarmot/orabbix/Sender.class
92 | jar -uf orabbix-1.2.3.jar com
93 | ```
94 |
95 | ## Screenshots
96 |
97 | 
98 |
99 | ## Notes
100 | - Main development branch is `main`
101 | - Branch `legacy` is legacy style
102 |
103 | For more details and issues, please refer to the [GitHub Issues](https://github.com/snickerjp/orabbix/issues)
104 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Querybox.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.orabbix;
21 |
22 | import java.util.ArrayList;
23 | import java.util.Arrays;
24 | // import java.util.Date;
25 | import java.util.Properties;
26 |
27 | import org.apache.log4j.Level;
28 |
29 | import com.smartmarmot.common.SmartLogger;
30 | import com.smartmarmot.orabbix.Configurator;
31 |
32 | public class Querybox {
33 | private Query[] _query;
34 | private String _dbname;
35 | private String _queriesfile;
36 | private String _extraqueriesfile;
37 |
38 | public Querybox(String _localdbname, String _prp,String _extraprp) {
39 | try {
40 | if (Configurator.propVerify(_prp)){
41 | this.setQueriesFile(_prp);
42 | }
43 | if (Configurator.propVerify(_extraprp)){
44 | this.setExtraQueriesFile(_extraprp);
45 | }
46 |
47 | if (_localdbname.length() > 0 && _localdbname != null) {
48 | this.setDBName(_localdbname);
49 | }
50 | refresh();
51 |
52 | } catch (Exception e) {
53 | // TODO Auto-generated catch block
54 | SmartLogger.logThis(Level.ERROR, "Error on QueryBox "
55 | + e.getMessage());
56 | }
57 |
58 | }
59 |
60 | public String getDBName() {
61 | return _dbname;
62 | }
63 |
64 | public Query[] getQueries() {
65 | return _query;
66 | }
67 |
68 |
69 | public String getQueriesFile() {
70 | return _queriesfile;
71 | }
72 |
73 |
74 | public void refresh() {
75 | try {
76 | Query[] firstq=null;
77 | Query[] extraq=null;
78 |
79 | if (_queriesfile != null){
80 | Properties prp = Configurator.getPropsFromFile(_queriesfile);
81 | firstq =Configurator.getQueries(prp);
82 | //this.setQueries(q);
83 | }
84 | if (_extraqueriesfile != null){
85 | Properties prp = Configurator.getPropsFromFile(_extraqueriesfile);
86 | extraq =Configurator.getQueries(prp);
87 | }
88 |
89 | Query[] refreshedq = addQueries(firstq,extraq);
90 | if (this._query==null){
91 | this.setQueries(refreshedq);
92 | } else {
93 | for (int i = 0; i tempOriginalArray = new ArrayList(Arrays.asList(_originalquery));
124 | ArrayList tempNewArray = new ArrayList(Arrays.asList(_newquery));
125 | for (int i = 0; i < _originalquery.length; i++){
126 | for (int j = 0; j < _newquery.length; j++){
127 | if (_originalquery[i].getName().equals(_newquery[j].getName())){
128 | tempOriginalArray.remove(_originalquery[i]);
129 | tempOriginalArray.add(_newquery[j]);
130 | tempNewArray.remove(_newquery[j]);
131 | }
132 | }
133 | }
134 | tempOriginalArray.addAll(tempNewArray);
135 | Query[] queries = (Query[]) tempOriginalArray.toArray(new Query[0]);
136 | //this.setQueries(queries);
137 | return queries;
138 | }
139 |
140 | public void setQueriesFile(String _queriesfile) {
141 | this._queriesfile = _queriesfile;
142 | }
143 |
144 | public void setExtraQueriesFile(String _extraqueriesfile) {
145 | this._extraqueriesfile = _extraqueriesfile;
146 | }
147 |
148 | }
149 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Query.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.orabbix;
21 |
22 |
23 | import java.util.List;
24 | import java.util.Date;
25 |
26 | public class Query {
27 |
28 | private String sql;
29 | private String name;
30 | private String nodata;
31 | private String racequery;
32 | private String racevalue;
33 | private List raceExcludeColumns = null;
34 | private int period = -1;
35 | private Date nextrun;
36 | private Boolean active = true;
37 | private List excludeColumns = null;
38 | private Boolean space = false;
39 | private Boolean trim = true;
40 |
41 | public Query(String _query, String _name, String _nodata, String _rccondq,
42 | String _rccondval, int _period, Boolean _active, Boolean _trim,
43 | Boolean _space, List _excludeColumns,
44 | List _raceExcludeColumns) {
45 | if (_query == null || _query.length() == 0)
46 | throw new RuntimeException("empty query");
47 | this.sql = _query;
48 | if (_name != null && _name.length() > 0)
49 | this.name = _name;
50 | else
51 | this.name = _query;
52 | if (_nodata != null && _nodata.length() > 0) {
53 | this.nodata = _nodata;
54 | } else
55 | this.nodata = "";
56 | this.racequery = "";
57 | this.racevalue = "";
58 | if (_rccondq != null && _rccondq.length() > 0) {
59 | if (_rccondval != null && _rccondval.length() > 0) {
60 | this.racequery = _rccondq;
61 | this.racevalue = _rccondval;
62 | }
63 | }
64 | if (_period != 0) {
65 | this.period = _period;
66 | if (period > 0) {
67 | Date newNextRun = new Date(System.currentTimeMillis());
68 | // Date now =new Date(System.currentTimeMillis());
69 | // Date newNextRun=new Date(now.getTime()+(period*1000*60));
70 | this.nextrun = newNextRun;
71 | }
72 | }
73 | if (_trim != null) {
74 | this.setTrim(_trim);
75 | }
76 | if (_space != null) {
77 | this.setSpace(_space);
78 | }
79 | if (_active != null) {
80 | this.setActive(_active);
81 | }
82 | if (_excludeColumns != null) {
83 | this.setExcludeColumnsList(_excludeColumns);
84 | }
85 | if (_raceExcludeColumns != null) {
86 | this.setRaceExcludeColumnsList(_raceExcludeColumns);
87 | }
88 | }
89 |
90 | public Boolean getActive() {
91 | return active.booleanValue();
92 | }
93 |
94 | public String getName() {
95 | return this.name;
96 | }
97 |
98 | public Date getNextrun() {
99 | return nextrun;
100 | }
101 |
102 | public String getNoData() {
103 | return this.nodata;
104 | }
105 |
106 | public int getPeriod() {
107 | return period;
108 | }
109 |
110 | public String getRaceQuery() {
111 | return this.racequery;
112 | }
113 |
114 | public String getRaceValue() {
115 | return this.racevalue;
116 | }
117 |
118 | public String getSQL() {
119 | return this.sql;
120 | }
121 |
122 | public void setActive(Boolean active) {
123 | this.active = active;
124 | }
125 |
126 | public void setNextrun(Date nextrun) {
127 | this.nextrun = nextrun;
128 | }
129 |
130 | public void setPeriod(int period) {
131 | this.period = period;
132 |
133 | }
134 |
135 | public void setRaceQuery(String _raceQuery) {
136 | this.racequery = _raceQuery;
137 | }
138 |
139 | public void setSql(String _sql) {
140 | this.sql = _sql;
141 | // TODO Auto-generated method stub
142 |
143 | }
144 |
145 | public void setTrim(Boolean trim) {
146 | this.trim = trim;
147 | }
148 | public Boolean getTrim() {
149 | return trim;
150 | }
151 | public void setSpace(Boolean space) {
152 | this.space = space;
153 | }
154 | public Boolean getSpace() {
155 | return space;
156 | }
157 | public List getExcludeColumnsList() {
158 | return this.excludeColumns;
159 | }
160 | public void setExcludeColumnsList(List excludeList) {
161 | if (excludeList != null) {
162 | this.excludeColumns = excludeList;
163 | }
164 | }
165 | public void setRaceExcludeColumnsList(List raceExcludeColumns) {
166 | this.raceExcludeColumns = raceExcludeColumns;
167 | }
168 | public List getRaceExcludeColumnsList() {
169 | return raceExcludeColumns;
170 | }
171 | }
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/common/db/DBJob.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.common.db;
21 |
22 | import java.sql.Connection;
23 | import java.sql.PreparedStatement;
24 | import java.sql.ResultSet;
25 |
26 | import java.util.Hashtable;
27 | import java.util.concurrent.BlockingQueue;
28 | import java.util.concurrent.LinkedBlockingQueue;
29 |
30 | import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
31 | import org.apache.log4j.Level;
32 |
33 | import com.smartmarmot.common.SmartLogger;
34 | import com.smartmarmot.orabbix.Constants;
35 | import com.smartmarmot.orabbix.Query;
36 | import com.smartmarmot.orabbix.Sender;
37 | import com.smartmarmot.zabbix.ZabbixItem;
38 |
39 | public class DBJob implements Runnable {
40 | private final SharedPoolDataSource _spds;
41 | private Query[] _queries;
42 | private final BlockingQueue _queue = new LinkedBlockingQueue();
43 | private final String _dbname;
44 | private final String _queriesGroup;
45 | private final int _dgNum;
46 | private final Hashtable _zabbixServers;
47 |
48 | public DBJob(SharedPoolDataSource spds, Query[] queries, String queriesGroup,
49 | Hashtable zabbixServers, String dbname) {
50 | this._spds = spds;
51 | this._queries = queries;
52 | this._queriesGroup = queriesGroup;
53 | this._zabbixServers = zabbixServers;
54 | this._dbname = dbname;
55 | this._dgNum = 0;
56 | }
57 |
58 | public DBJob(SharedPoolDataSource spds, Query[] queries, String queriesGroup,
59 | Hashtable zabbixServers, String dbname, int dgNum) {
60 | this._spds = spds;
61 | this._queries = queries;
62 | this._zabbixServers = zabbixServers;
63 | this._queriesGroup = queriesGroup;
64 | this._dbname = dbname;
65 | if (dgNum > 0) {
66 | this._dgNum = dgNum;
67 | } else {
68 | this._dgNum = 0;
69 | }
70 | }
71 |
72 | private boolean Alive(Connection _conn){
73 | try {
74 | PreparedStatement p_stmt = null;
75 | p_stmt = _conn
76 | .prepareStatement(Constants.ORACLE_VALIDATION_QUERY);
77 | ResultSet rs = null;
78 | rs = p_stmt.executeQuery();
79 | rs.next();
80 | //_conn.close();
81 | return true;
82 | } catch (Exception e) {
83 | // TODO Auto-generated catch block
84 | e.printStackTrace();
85 | SmartLogger.logThis(Level.DEBUG, "Database "
86 | + this._dbname + " is not alive");
87 | return false;
88 | }
89 | }
90 |
91 | @Override
92 | public void run() {
93 |
94 | SmartLogger.logThis(Level.DEBUG, "Starting dbJob on database "
95 | + _dbname + " " + _queriesGroup);
96 | final long start = System.currentTimeMillis();
97 |
98 | try {
99 | Connection dbConn=this._spds.getConnection();
100 | /* if (dbConn.isClosed()){
101 | dbConn = this._spds.getConnection();
102 | }*/
103 | if (Alive(dbConn)){
104 | _queue.offer(new ZabbixItem("alive", "1",this._dbname));
105 | _queue.offer(new ZabbixItem(Constants.PROJECT_NAME+"."+"Version", Constants.BANNER,this._dbname));
106 | ZabbixItem[] zitems = DBEnquiry.execute(this._queries,
107 | dbConn, this._dbname);
108 | if (zitems != null && zitems.length > 0) {
109 | SmartLogger.logThis(Level.DEBUG, "Item retrieved "
110 | + zitems.length + " on database " + this._dbname);
111 | for (int cnt = 0; cnt < zitems.length; cnt++) {
112 | String zItemName = zitems[cnt].getKey();
113 | if (this._dgNum > 0) {
114 | zItemName = zItemName + "_" + _dgNum;
115 | }
116 | SmartLogger.logThis(Level.DEBUG, "dbname " + this._dbname
117 | + " sending item " + zitems[cnt].getKey()
118 | + " value " + zitems[cnt].getValue());
119 | _queue.offer(new ZabbixItem(zItemName, zitems[cnt]
120 | .getValue(),
121 | _dbname));
122 | }
123 |
124 | }
125 | dbConn.close();
126 | Sender sender = new Sender(_queue, _zabbixServers, this._dbname);
127 | sender.run();
128 | } else{
129 | BlockingQueue _queue = new LinkedBlockingQueue();
130 | _queue.offer(new ZabbixItem("alive", "0",this._dbname));
131 | _queue.offer(new ZabbixItem(Constants.PROJECT_NAME+"."+"Version", Constants.BANNER,this._dbname));
132 | for (int cnt = 0; cnt < this._queries.length; cnt++) {
133 | _queue.offer(new ZabbixItem(_queries[cnt].getName(),
134 | _queries[cnt].getNoData(),_dbname));
135 |
136 | }
137 | Sender sender = new Sender(_queue, _zabbixServers,
138 | _dbname);
139 | sender.run();
140 | }
141 | } catch (Exception e) {
142 | SmartLogger.logThis(Level.ERROR, "Error on dbJob for database "
143 | + _dbname + " " + _queriesGroup + " error: " + e);
144 | } finally {
145 | if (_queries != null)
146 | _queries = null;
147 | }
148 | SmartLogger.logThis(Level.INFO, "Done with dbJob on database "
149 | + _dbname + " " + _queriesGroup + " elapsed time "
150 | + (System.currentTimeMillis() - start) + " ms");
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Orabbixmon.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of DBforBIX.
5 | *
6 | * Orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * Orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * Orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.orabbix;
21 |
22 | import java.lang.management.ManagementFactory;
23 | import java.lang.management.RuntimeMXBean;
24 | import java.util.Hashtable;
25 | import java.util.Locale;
26 | import java.util.concurrent.ExecutorService;
27 | import java.util.concurrent.Executors;
28 |
29 | import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
30 | import org.apache.log4j.Level;
31 |
32 | import com.smartmarmot.common.SmartLogger;
33 | import com.smartmarmot.common.db.DBConn;
34 | import com.smartmarmot.common.db.DBJob;
35 |
36 | public class Orabbixmon implements Runnable {
37 |
38 | private boolean running = true;
39 | private boolean stopped = false;
40 |
41 | private static String configFile;
42 |
43 | public Orabbixmon(String _cfgfile) {
44 | try {
45 | configFile = _cfgfile;
46 | SmartLogger.logThis(Level.INFO, "Starting " + Constants.BANNER);
47 | } catch (Exception ex) {
48 | ex.printStackTrace();
49 | }
50 |
51 | // TODO Auto-generated constructor stub
52 | }
53 |
54 | public void terminate() {
55 | running = false;
56 | while (!stopped)
57 | try {
58 | Thread.sleep(1000);
59 | } catch (InterruptedException e) {
60 | e.printStackTrace();
61 | }
62 | System.out.println("Stopped");
63 | }
64 |
65 | @Override
66 | public void run() {
67 | try {
68 | Configurator cfg = null;
69 | try {
70 | cfg = new Configurator(configFile);
71 | } catch (Exception e) {
72 | SmartLogger.logThis(Level.ERROR,
73 | "Error while creating configurator with " + configFile
74 | + " " + e);
75 | }
76 | RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
77 | String pid = rmxb.getName();
78 | SmartLogger.logThis(Level.INFO, Constants.PROJECT_NAME
79 | + " started with pid:" + pid.split("@")[0].toString());
80 | // System.out.print("pid: "+pid.split("@")[0].toString());
81 | String pidfile = cfg.getPidFile();
82 | try {
83 | Utility.writePid(pid.split("@")[0].toString(), pidfile);
84 | } catch (Exception e) {
85 | SmartLogger.logThis(Level.ERROR,
86 | "Error while trying to write pidfile " + e);
87 | }
88 |
89 | Locale.setDefault(Locale.US);
90 |
91 | DBConn[] myDBConn = cfg.getConnections();
92 |
93 | if (myDBConn == null) {
94 | SmartLogger.logThis(Level.ERROR,
95 | "ERROR on main - Connections is null");
96 | throw new Exception("ERROR on main - Connections is null");
97 |
98 | } else if (myDBConn.length == 0) {
99 | SmartLogger.logThis(Level.ERROR,
100 | "ERROR on main - Connections is empty");
101 | throw new Exception("ERROR on main - Connections is empty");
102 | }
103 |
104 | /**
105 | * retrieve maxThread
106 | */
107 | Integer maxThread = 0;
108 | try {
109 | maxThread = cfg.getMaxThread();
110 | } catch (Exception e) {
111 | SmartLogger.logThis(Level.WARN,
112 | "MaxThread not defined calculated maxThread = "
113 | + myDBConn.length * 3);
114 | }
115 | if (maxThread == null)
116 | maxThread = 0;
117 | if (maxThread == 0) {
118 | maxThread = myDBConn.length * 3;
119 | }
120 |
121 | ExecutorService executor = Executors.newFixedThreadPool(maxThread.intValue());
122 | /**
123 | * populate qbox
124 | */
125 | Hashtable qbox = new Hashtable();
126 | for (int i = 0; i < myDBConn.length; i++) {
127 | Querybox qboxtmp = Configurator.buildQueryBoxbyDBName(myDBConn[i].getName());
128 | qbox.put(myDBConn[i].getName(), qboxtmp);
129 | }// for (int i = 0; i < myDBConn.length; i++) {
130 |
131 | cfg = null;
132 | /**
133 | * daemon begin here
134 | */
135 | while (running) {
136 | /**
137 | * istantiate a new configurator
138 | */
139 | Configurator c = new Configurator(configFile);
140 |
141 | /*
142 | * here i rebuild DB's List
143 | */
144 | if (!c.isEqualsDBList(myDBConn)) {
145 |
146 | // rebuild connections DBConn[]
147 |
148 | myDBConn = c.rebuildDBList(myDBConn);
149 | for (int i = 1; i < myDBConn.length; i++) {
150 | if (!qbox.containsKey(myDBConn[i].getName())) {
151 | Querybox qboxtmp = Configurator.buildQueryBoxbyDBName(myDBConn[i].getName());
152 | qbox.put(myDBConn[i].getName(), qboxtmp);
153 | }
154 | }
155 | }// if (!c.isEqualsDBList(myDBConn)) {
156 |
157 | /*
158 | * ready to run query
159 | */
160 |
161 | for (int i = 0; i < myDBConn.length; i++) {
162 | Querybox actqb = qbox.get(myDBConn[i].getName());
163 | actqb.refresh();
164 | Query[] q = actqb.getQueries();
165 |
166 | SharedPoolDataSource spds = myDBConn[i].getSPDS();
167 |
168 | Hashtable zabbixServers = c.getZabbixServers();
169 | SmartLogger.logThis(
170 | Level.DEBUG,
171 | "Ready to run DBJob for dbname ->"
172 | + myDBConn[i].getName());
173 | Runnable runner = new DBJob(spds, q, Constants.QUERY_LIST,
174 | zabbixServers, myDBConn[i].getName());
175 | executor.execute(runner);
176 |
177 | }// for (int i = 0; i < myDBConn.length; i++) {
178 | Thread.sleep(60 * 1000);
179 | SmartLogger.logThis(Level.DEBUG, "Waking up Goood Morning");
180 | }
181 | } catch (Exception e1) {
182 | // TODO Auto-generated catch block
183 | System.out.println("Stopping");
184 | e1.printStackTrace();
185 | stopped = true;
186 | }
187 |
188 | }
189 |
190 | }
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/common/db/DBEnquiry.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 | package com.smartmarmot.common.db;
21 |
22 | import java.sql.Connection;
23 | import java.sql.PreparedStatement;
24 | import java.sql.ResultSet;
25 | import java.sql.ResultSetMetaData;
26 | import java.text.DateFormat;
27 | import java.text.SimpleDateFormat;
28 | import java.util.ArrayList;
29 | import java.util.Collection;
30 | import java.util.Date;
31 | import java.util.List;
32 |
33 | import org.apache.log4j.Level;
34 |
35 | import com.smartmarmot.common.SmartLogger;
36 | import com.smartmarmot.orabbix.Constants;
37 | import com.smartmarmot.orabbix.Query;
38 | import com.smartmarmot.zabbix.ZabbixItem;
39 |
40 |
41 |
42 | public class DBEnquiry {
43 |
44 |
45 |
46 | public static String ask(String _query, Connection _con, String queryName,
47 | String dbName, Boolean trim, Boolean space,
48 | List _excludeColumns) {
49 | String tempStr="";
50 | try{
51 | ResultSet rs = null;
52 | PreparedStatement p_stmt = _con.prepareStatement(_query);
53 | rs = p_stmt.executeQuery();
54 | ResultSetMetaData rsmd = rs.getMetaData();
55 | int numColumns = rsmd.getColumnCount();
56 | while (rs.next()) {
57 | for (int r = 1; r < numColumns + 1; r++) {
58 | Integer tmpInteger = Integer.valueOf(r);
59 | if (!_excludeColumns.contains(tmpInteger)) {
60 | if (trim) {
61 | tempStr = tempStr + rs.getObject(r).toString().trim();
62 | } else {
63 | tempStr = tempStr + rs.getObject(r).toString();
64 | }
65 | if (space && (r < numColumns)) {
66 | tempStr = tempStr + ' ';
67 | }
68 | }
69 | }
70 | }
71 | try{
72 | if (rs != null)
73 | rs.close();
74 | } catch (Exception ex) {
75 | SmartLogger.logThis(Level.ERROR,
76 | "Error on DBEnquiry while closing resultset "
77 | + ex.getMessage() + " on database=" + dbName);
78 | }
79 | } catch (Exception ex) {
80 | SmartLogger.logThis(Level.WARN,
81 | "Error while executing ->"
82 | + queryName
83 | + "- on database ->"
84 | + dbName
85 | + "- Exception received "
86 | + ex.getMessage());
87 | tempStr = null;
88 | }
89 | return tempStr;
90 | }
91 |
92 |
93 |
94 |
95 | public static ZabbixItem[] execute(Query[] _queries, Connection _conn,
96 | String dbname) {
97 | if (_queries == null || _queries.length < 1) {
98 | throw new IllegalArgumentException("Query's array is empty or null");
99 | }
100 | Connection con = _conn;
101 |
102 | Collection SZItems = new ArrayList();
103 | for (int i = 0; i < _queries.length; i++) {
104 | // System.out.println(queries[i].getSQL());
105 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
106 | String datetime = dateFormat.format(_queries[i].getNextrun());
107 |
108 | // Configurator.logThis(Level.DEBUG,"Actual query is "+_queries[i].getName()+" on database="+
109 | // dbname+" Period="+_queries[i].getPeriod()+" nextRun="+datetime);
110 | // System.out.println(queries[i].getName());
111 | String tempStr = new String("");
112 | // check if is the right time to execute the statements
113 | try {
114 |
115 | if (_queries[i].getActive()) {
116 | // if item is active
117 | Date now = new Date(System.currentTimeMillis());
118 | Date nextRun = _queries[i].getNextrun();
119 | if (now.after(nextRun)) {
120 |
121 | Date newNextRun = new Date(nextRun.getTime()
122 | + (_queries[i].getPeriod() * 1000 * 60));
123 | _queries[i].setNextrun(newNextRun);
124 |
125 | datetime = dateFormat.format(_queries[i].getNextrun());
126 | SmartLogger.logThis(Level.DEBUG, "Actual query is "
127 | + _queries[i].getName() + "Nextrun " + datetime
128 | + " on database=" + dbname + " Period="
129 | + _queries[i].getPeriod());
130 |
131 | /*
132 | * execute RaceConditionQuery
133 | */
134 | boolean racecond = true;
135 | String result = "";
136 | if (_queries[i].getRaceQuery() != null) {
137 | if (_queries[i].getRaceQuery().length() > 0) {
138 | SmartLogger.logThis(Level.DEBUG, "INFO:"
139 | + _queries[i].getName()
140 | + " RaceCondiftionQuery ->"
141 | + _queries[i].getRaceQuery());
142 | result = ask(
143 | _queries[i].getRaceQuery(),
144 | _conn,
145 | _queries[i].getName()
146 | + Constants.RACE_CONDITION_QUERY,
147 | dbname, _queries[i].getTrim(),
148 | _queries[i].getSpace(),
149 | _queries[i]
150 | .getRaceExcludeColumnsList());
151 | if (result != null) {
152 | if (_queries[i].getRaceValue() != null) {
153 | if (!result.equalsIgnoreCase(_queries[i]
154 | .getRaceValue())) {
155 | racecond = false;
156 | }
157 | }
158 | }
159 | }
160 | }
161 | result = "";
162 | if (racecond) {
163 | result = ask(_queries[i].getSQL().toString(),
164 | _conn, _queries[i].getName(), dbname,
165 | _queries[i].getTrim(), _queries[i]
166 | .getSpace(),
167 | _queries[i]
168 | .getExcludeColumnsList());
169 | if (result == null) {
170 | if (_queries[i].getNoData().length() > 0
171 | && _queries[i].getNoData() != null) {
172 | result = _queries[i].getNoData();
173 | }
174 | } else if (result.length() == 0) {
175 | if (_queries[i].getNoData().length() > 0
176 | && _queries[i].getNoData() != null) {
177 | result = _queries[i].getNoData();
178 | }
179 | }
180 |
181 | ZabbixItem zitem = new ZabbixItem(_queries[i]
182 | .getName(), result,dbname);
183 | SZItems.add(zitem);
184 | SmartLogger.logThis(Level.DEBUG,
185 | "I'm going to return " + result
186 | + " for query "
187 | + _queries[i].getName()
188 | + " on database=" + dbname);
189 | }
190 | }
191 |
192 | }
193 | } catch (Exception ex) {
194 | SmartLogger.logThis(Level.ERROR,
195 | "Error on DBEnquiry on query=" + _queries[i].getName()
196 | + " on database=" + dbname
197 | + " Error returned is " + ex);
198 | if (_queries[i].getNoData() != null)
199 | {
200 | if (_queries[i].getNoData().length() > 0)
201 | tempStr = _queries[i].getNoData();
202 | } else {
203 | tempStr = "";
204 | }
205 | ZabbixItem zitem = new ZabbixItem(_queries[i].getName(),
206 | tempStr , dbname);
207 | SZItems.add(zitem);
208 | SmartLogger.logThis(Level.DEBUG, "I'm going to return "
209 | + tempStr + " for query " + _queries[i].getName()
210 | + " on database=" + dbname);
211 | }
212 |
213 | }
214 | try {
215 | if (!con.isClosed())
216 | con.close();
217 | } catch (Exception ex) {
218 | SmartLogger.logThis(Level.ERROR,
219 | "Error on DBEnquiry while closing connection "
220 | + ex.getMessage() + " on database=" + dbname);
221 | }
222 | ZabbixItem[] items = SZItems.toArray(new ZabbixItem[0]);
223 | return items;
224 | }
225 | }
226 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Sender.java:
--------------------------------------------------------------------------------
1 | package com.smartmarmot.orabbix;
2 |
3 |
4 |
5 | /* This file is part of Zapcat.
6 | *
7 | * Zapcat is free software: you can redistribute it and/or modify it under the
8 | * terms of the GNU General Public License as published by the Free Software
9 | * Foundation, either version 3 of the License, or (at your option) any later
10 | * version.
11 | *
12 | * Zapcat is distributed in the hope that it will be useful, but WITHOUT ANY
13 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 | * details.
16 | *
17 | * You should have received a copy of the GNU General Public License along with
18 | * Zapcat. If not, see .
19 | */
20 |
21 | import java.io.IOException;
22 | import java.io.InputStream;
23 | // import java.io.OutputStreamWriter;
24 | import java.io.OutputStream;
25 | import java.io.UnsupportedEncodingException;
26 | import java.net.Socket;
27 | import java.util.Enumeration;
28 | import java.util.Hashtable;
29 | import java.util.concurrent.BlockingQueue;
30 |
31 | import org.apache.log4j.Level;
32 | import org.apache.log4j.Logger;
33 |
34 | import org.apache.commons.codec.binary.Base64;
35 |
36 | import com.smartmarmot.common.SmartLogger;
37 | import com.smartmarmot.zabbix.ZabbixItem;
38 | /**
39 | * A daemon thread that waits for and forwards data items to a Zabbix server.
40 | *
41 | * @author Kees Jan Koster Completely modified by
42 | * Andrea Dalle Vacche
43 | */
44 | public final class Sender implements Runnable {
45 | private static final Logger log = Logger.getLogger("Orabbix");
46 |
47 | private final BlockingQueue queue;
48 |
49 | private final Hashtable zabbixServers;
50 |
51 |
52 |
53 | private final String head;
54 |
55 | private final String host;
56 |
57 | private static final String middle = "";
58 |
59 | private static final String tail = "";
60 |
61 | private final byte[] response = new byte[1024];
62 |
63 | private boolean stopping = false;
64 |
65 | private static final int retryNumber = 10;
66 |
67 | private static final int TIMEOUT = 30 * 1000;
68 |
69 | /**
70 | * Create a new background sender.
71 | *
72 | * @param queue
73 | * The queue to get data items from.
74 | * @param zabbixServer
75 | * The name or IP of the machine to send the data to.
76 | * @param zabbixPort
77 | * The port number on that machine.
78 | * @param host
79 | * The host name, as defined in the host definition in Zabbix.
80 | *
81 | */
82 | public Sender(final BlockingQueue queue,
83 | Hashtable ZabbixServers,
84 |
85 | final String host) {
86 | /* super("Zabbix-sender");
87 | setDaemon(true);
88 | */
89 | this.queue = queue;
90 | this.zabbixServers = ZabbixServers;
91 | this.host = host;
92 | this.head = "" + base64Encode(host) + "";
93 | }
94 |
95 | /**
96 | * Indicate that we are about to stop.
97 | */
98 | public void stopping() {
99 | stopping = true;
100 | /*interrupt();*/
101 | }
102 |
103 | /**
104 | * @see java.lang.Thread#run()
105 | */
106 | @Override
107 | public void run() {
108 | try {
109 | final ZabbixItem item = queue.take();
110 | int retryCount = 0;
111 | trysend1:
112 | while (retryCount<= retryNumber){
113 | try{
114 | send(item.getKey(), item.getValue());
115 | break;
116 | }catch (Exception e){
117 | SmartLogger.logThis(Level.WARN,
118 | "Warning while sending item " + item.getKey()
119 | + " value " + item.getValue() + " on host "
120 | + host + " retry number " + retryCount
121 | + " error:" + e);
122 | Thread.sleep(1000);
123 | retryCount++;
124 | if (retryCount==retryNumber){
125 | SmartLogger.logThis(Level.WARN,
126 | "Error i didn't sent item " + item.getKey()
127 | + " on Zabbix server " + " on host "
128 | + host + " tried " + retryCount
129 | + " times");
130 | }
131 | continue trysend1;
132 | }
133 | }
134 |
135 |
136 | } catch (InterruptedException e) {
137 | if (!stopping) {
138 | log.warn("ignoring exception", e);
139 | }
140 |
141 | } catch (Exception e) {
142 | log.warn("ignoring exception", e);
143 | }
144 |
145 |
146 | // drain the queue
147 | while (queue.size() > 0) {
148 | final ZabbixItem item = queue.remove();
149 | int retryCount = 0;
150 | trysend2:
151 | while (retryCount<= retryNumber){
152 | try {
153 | send(item.getKey(), item.getValue());
154 | break;
155 | } catch (Exception e) {
156 | SmartLogger.logThis(Level.WARN,
157 | "Warning while sending item " + item.getKey()
158 | + " on host " + host + " retry number "
159 | + retryCount + " error:" + e);
160 | retryCount++;
161 | continue trysend2;
162 | }
163 |
164 | }
165 | if (retryCount==retryNumber){
166 | SmartLogger.logThis(Level.WARN, "Error i didn't sent item "
167 | + item.getKey() + " on host " + host + " tried "
168 | + retryCount);
169 | }
170 | }
171 | }
172 |
173 | /**
174 | * Encodes data for transmission to the server.
175 | *
176 | * This method encodes the data in the ASCII encoding, defaulting to
177 | * the platform default encoding if that is somehow unavailable.
178 | *
179 | * @param data
180 | * @return byte[] containing the encoded data
181 | */
182 | protected byte[] encodeString(String data) {
183 | try {
184 | return data.getBytes("ASCII");
185 | } catch (UnsupportedEncodingException e) {
186 | return data.getBytes();
187 | }
188 | }
189 |
190 | protected String base64Encode(String data) {
191 | return new String(Base64.encodeBase64(encodeString(data)));
192 | }
193 |
194 | private void send(final String key, final String value) throws IOException {
195 | final StringBuilder message = new StringBuilder(head);
196 | //message.append(Base64.encode(key));
197 | message.append(base64Encode(key));
198 | message.append(middle);
199 | //message.append(Base64.encode(value == null ? "" : value));
200 | message.append(base64Encode(value == null ? "" : value));
201 | message.append(tail);
202 |
203 | if (log.isDebugEnabled()) {
204 | SmartLogger.logThis(Level.DEBUG,"sending " + message);
205 | }
206 |
207 | Socket zabbix = null;
208 | // OutputStreamWriter out = null;
209 | OutputStream out = null;
210 | InputStream in = null;
211 | Enumeration serverlist = zabbixServers.keys();
212 |
213 | while (serverlist.hasMoreElements()){
214 | String zabbixServer = serverlist.nextElement();
215 | try {
216 | zabbix = new Socket(zabbixServer, zabbixServers.get(
217 | zabbixServer).intValue());
218 | zabbix.setSoTimeout(TIMEOUT);
219 |
220 | byte[] data = message.toString().getBytes("UTF-8");
221 |
222 | byte[] header = new byte[] {
223 | 'Z', 'B', 'X', 'D', '\1',
224 | (byte)(data.length & 0xFF),
225 | (byte)((data.length >> 8) & 0xFF),
226 | (byte)((data.length >> 16) & 0xFF),
227 | (byte)((data.length >> 24) & 0xFF),
228 | '\0', '\0', '\0', '\0'};
229 |
230 | byte[] packet = new byte[header.length + data.length];
231 | System.arraycopy(header, 0, packet, 0, header.length);
232 | System.arraycopy(data, 0, packet, header.length, data.length);
233 |
234 | // out = new OutputStreamWriter(zabbix.getOutputStream());
235 | out = zabbix.getOutputStream();
236 | out.write(packet);
237 | out.flush();
238 |
239 | in = zabbix.getInputStream();
240 | final int read = in.read(response);
241 | if (log.isDebugEnabled()) {
242 | SmartLogger.logThis(Level.DEBUG, "received "
243 | + new String(response));
244 | }
245 | if (read != 2 || response[0] != 'O' || response[1] != 'K') {
246 | SmartLogger.logThis(Level.WARN,
247 | "received unexpected response '"
248 | + new String(response) + "' for key '"
249 | + key + "'");
250 | }
251 | } catch (Exception ex){
252 | SmartLogger.logThis(Level.ERROR,
253 | "Error contacting Zabbix server " + zabbixServer
254 | + " on port "
255 | + zabbixServers.get(zabbixServer));
256 | }
257 |
258 | finally {
259 | if (in != null) {
260 | in.close();
261 | }
262 | if (out != null) {
263 | out.close();
264 | }
265 | if (zabbix != null) {
266 | zabbix.close();
267 | }
268 |
269 | }
270 | }
271 | }
272 | }
273 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | com.smartmarmot
4 | orabbix
5 | 1.2.3
6 |
7 | 1.8
8 | 1.8
9 | UTF-8
10 | 5.11.4
11 | 3.5.0
12 | 3.6.0
13 | 8.45.1
14 | 3.5.2
15 | 0.8.13
16 | 3.11.2
17 |
18 | 0%
19 | 0%
20 | 20
21 | 5
22 |
23 |
24 |
25 | org.junit.jupiter
26 | junit-jupiter-api
27 | ${junit.version}
28 | test
29 |
30 |
31 | org.junit.jupiter
32 | junit-jupiter-engine
33 | ${junit.version}
34 | test
35 |
36 |
37 | commons-dbcp
38 | commons-dbcp
39 | 1.4
40 |
41 |
42 | org.apache.logging.log4j
43 | log4j-api
44 | 2.24.3
45 |
46 |
47 | org.apache.logging.log4j
48 | log4j-core
49 | 2.24.3
50 |
51 |
52 | org.apache.logging.log4j
53 | log4j-1.2-api
54 | 2.24.3
55 |
56 |
57 | commons-codec
58 | commons-codec
59 | 1.18.0
60 |
61 |
62 | commons-lang
63 | commons-lang
64 | 2.6
65 |
66 |
67 |
68 | com.oracle.database.jdbc
69 | ojdbc8
70 | 19.28.0.0
71 |
72 |
73 |
74 |
75 | com.oracle.database.jdbc
76 | ucp
77 | 19.28.0.0
78 |
79 |
80 |
81 |
82 |
83 | org.apache.maven.plugins
84 | maven-enforcer-plugin
85 | ${maven-enforcer-plugin.version}
86 |
87 |
88 |
89 | enforce
90 |
91 |
92 |
93 |
94 | 3.6.3
95 |
96 |
97 | true
98 |
99 |
100 |
101 |
102 |
103 | org.apache.maven.plugins
104 | maven-checkstyle-plugin
105 | ${maven-checkstyle-plugin.version}
106 |
107 |
108 | com.puppycrawl.tools
109 | checkstyle
110 | ${checkstyle.version}
111 |
112 |
113 |
114 | google_checks.xml
115 | UTF-8
116 | true
117 | true
118 | true
119 |
120 |
121 |
122 | checkstyle
123 | validate
124 |
125 | check
126 |
127 |
128 |
129 |
130 |
131 | org.apache.maven.plugins
132 | maven-surefire-plugin
133 | ${maven-surefire-plugin.version}
134 |
135 |
136 | org.jacoco
137 | jacoco-maven-plugin
138 | ${jacoco-maven-plugin.version}
139 |
140 |
141 | pre-unit-test
142 |
143 | prepare-agent
144 |
145 |
146 |
147 | post-unit-test
148 | test
149 |
150 | report
151 |
152 |
153 |
154 | check-unit-test
155 | test
156 |
157 | check
158 |
159 |
160 | ${project.build.directory}/jacoco.exec
161 |
162 |
163 | BUNDLE
164 |
165 |
166 | INSTRUCTION
167 | COVEREDRATIO
168 | ${jacoco.unit-tests.limit.instruction-ratio}
169 |
170 |
171 | BRANCH
172 | COVEREDRATIO
173 | ${jacoco.unit-tests.limit.branch-ratio}
174 |
175 |
176 |
177 |
178 | CLASS
179 |
180 |
181 | COMPLEXITY
182 | TOTALCOUNT
183 | ${jacoco.unit-tests.limit.class-complexity}
184 |
185 |
186 |
187 |
188 | METHOD
189 |
190 |
191 | COMPLEXITY
192 | TOTALCOUNT
193 | ${jacoco.unit-tests.limit.method-complexity}
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 | org.apache.maven.plugins
204 | maven-jar-plugin
205 | 3.3.0
206 |
207 |
208 |
209 | true
210 | lib/
211 | com.smartmarmot.orabbix.Bootstrap
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 | org.apache.maven.plugins
220 | maven-dependency-plugin
221 | 3.6.1
222 |
223 |
224 | copy-dependencies
225 | prepare-package
226 |
227 | copy-dependencies
228 |
229 |
230 | ${project.build.directory}/lib
231 | false
232 | false
233 | true
234 |
235 |
236 |
237 |
238 |
239 |
240 | org.apache.maven.plugins
241 | maven-assembly-plugin
242 | 3.7.1
243 |
244 |
245 |
246 | com.smartmarmot.orabbix.Bootstrap
247 |
248 |
249 |
250 | jar-with-dependencies
251 |
252 |
253 |
254 |
255 | make-assembly
256 | package
257 |
258 | single
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 | org.codehaus.mojo
267 | build-helper-maven-plugin
268 | 3.5.0
269 |
270 |
271 | add-source
272 | generate-sources
273 |
274 | add-source
275 |
276 |
277 |
278 | ${project.build.directory}/generated-sources/java
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 | src/main/resources
289 | true
290 |
291 | Constants.java.template
292 |
293 | ${project.build.directory}/generated-sources/java/com/smartmarmot/orabbix
294 |
295 |
296 |
297 |
298 |
299 |
300 | org.apache.maven.plugins
301 | maven-javadoc-plugin
302 | ${maven-javadoc-plugin.version}
303 |
304 |
305 |
306 |
307 |
--------------------------------------------------------------------------------
/src/main/java/com/smartmarmot/orabbix/Configurator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 Andrea Dalle Vacche.
3 | *
4 | * This file is part of orabbix.
5 | *
6 | * orabbix is free software: you can redistribute it and/or modify it under the
7 | * terms of the GNU General Public License as published by the Free Software
8 | * Foundation, either version 3 of the License, or (at your option) any later
9 | * version.
10 | *
11 | * orabbix is distributed in the hope that it will be useful, but WITHOUT ANY
12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 | * details.
15 | *
16 | * You should have received a copy of the GNU General Public License along with
17 | * orabbix. If not, see .
18 | */
19 |
20 |
21 | package com.smartmarmot.orabbix;
22 |
23 |
24 | import java.io.File;
25 | import java.io.FileInputStream;
26 | import java.io.FileNotFoundException;
27 | import java.io.IOException;
28 | import java.sql.Connection;
29 | import java.sql.PreparedStatement;
30 | import java.sql.ResultSet;
31 | import java.sql.ResultSetMetaData;
32 | import java.util.ArrayList;
33 | import java.util.Collection;
34 | import java.util.Hashtable;
35 | import java.util.List;
36 | import java.util.Properties;
37 | import java.util.StringTokenizer;
38 |
39 | import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
40 | import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
41 | import org.apache.commons.lang.ArrayUtils;
42 | import org.apache.log4j.Level;
43 |
44 |
45 | import com.smartmarmot.common.SmartLogger;
46 | import com.smartmarmot.common.db.DBConn;
47 |
48 | public class Configurator {
49 | private static Properties _props;
50 |
51 | protected static Properties getPropsFromFile(String _filename) {
52 | try {
53 | verifyConfig();
54 | Properties propsq = new Properties();
55 | FileInputStream fisq;
56 | if (_filename != "" && _filename != null) {
57 | File queryFile = new File(_filename);
58 | fisq = new FileInputStream(new java.io.File(queryFile
59 | .getAbsoluteFile().getCanonicalPath()));
60 | queryFile = null;
61 | SmartLogger.logThis(Level.DEBUG, "Loaded the properties from " + _filename);
62 | propsq.load(fisq);
63 | fisq.close();
64 | return propsq;
65 | }
66 | } catch (Exception e) {
67 | // TODO Auto-generated catch block
68 | SmartLogger.logThis(Level.ERROR, "Error on Configurator reading properties file getPropsFromFile("
69 | + _filename + ") " + e.getMessage());
70 | return null;
71 | }
72 | return null;
73 | }
74 |
75 | protected static Query[] getQueries(Properties _propsq) throws Exception {
76 | return getQueries(Constants.QUERY_LIST, _propsq);
77 | }
78 |
79 |
80 | private static Query[] getQueries(String parameter, Properties _propsq)
81 | throws Exception {
82 | try {
83 | StringTokenizer stq = new StringTokenizer(_propsq
84 | .getProperty(parameter), Constants.DELIMITER);
85 | String[] QueryLists = new String[stq.countTokens()];
86 | int count = 0;
87 | while (stq.hasMoreTokens()) {
88 | String token = stq.nextToken().toString().trim();
89 | QueryLists[count] = token;
90 | count++;
91 | }
92 |
93 | Collection Queries = new ArrayList();
94 | for (int i = 0; i < QueryLists.length; i++) {
95 | try {
96 | Query q = getQueryProperties(_propsq, QueryLists[i]);
97 | Queries.add(q);
98 | }catch (Exception e1){
99 | SmartLogger.logThis(Level.ERROR, "Error on Configurator on reading query "+QueryLists[i] +e1);
100 | SmartLogger.logThis(Level.INFO, "Query "+QueryLists[i] +" skipped due to error " +e1);
101 |
102 | }
103 | }
104 | Query[] queries = (Query[]) Queries.toArray(new Query[0]);
105 | return queries;
106 | } catch (Exception ex) {
107 |
108 | SmartLogger.logThis(Level.ERROR, "Error on Configurator on reading properties file "+ _propsq.toString() +" getQueries("
109 | + parameter + "," + _propsq.toString() + ") "
110 | + ex.getMessage());
111 | return null;
112 | }
113 |
114 | }
115 |
116 | private static Query getQueryProperties(Properties _propsq,
117 | String _queryName) throws Exception {
118 | try {
119 |
120 | String query = "";
121 | try {
122 | query = new String(_propsq.getProperty(_queryName + "."
123 | + Constants.QUERY_POSTFIX));
124 | } catch (Exception ex) {
125 | SmartLogger.logThis(Level.ERROR, "Error while getting " + _queryName + "."
126 | + Constants.QUERY_POSTFIX + " " + ex.getMessage());
127 | }
128 |
129 | String noDataFound = "";
130 | try {
131 | noDataFound = new String(_propsq.getProperty(_queryName + "."
132 | + Constants.QUERY_NO_DATA_FOUND));
133 | } catch (Exception ex) {
134 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName
135 | + "." + Constants.QUERY_NO_DATA_FOUND
136 | + " null or not present " + ex.getMessage());
137 | }
138 | String raceCondQuery = "";
139 | try {
140 | raceCondQuery = new String(_propsq.getProperty(_queryName + "."
141 | + Constants.RACE_CONDITION_QUERY));
142 | } catch (Exception ex) {
143 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName
144 | + "." + Constants.RACE_CONDITION_QUERY
145 | + " null or not present " + ex.getMessage());
146 | }
147 | String raceCondValue = "";
148 | try {
149 | raceCondValue = new String(_propsq.getProperty(_queryName + "."
150 | + Constants.RACE_CONDITION_VALUE));
151 | } catch (Exception ex) {
152 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName
153 | + "." + Constants.RACE_CONDITION_VALUE
154 | + " null or not present " + ex.getMessage());
155 | }
156 | /**
157 | * set Period if not defined period =2 min.
158 | */
159 | int period = -1;
160 | try {
161 | period = Integer.parseInt(_propsq.getProperty(_queryName + "."
162 | + Constants.QUERY_PERIOD));
163 | } catch (Exception ex) {
164 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName
165 | + "." + Constants.QUERY_PERIOD
166 | + " null or not present " + ex.getMessage());
167 | try {
168 | period = Integer.parseInt(_propsq.getProperty(Constants.QUERY_DEFAULT_PERIOD));
169 | } catch (Exception ex1) {
170 | SmartLogger.logThis(Level.DEBUG, "Note: " + Constants.QUERY_DEFAULT_PERIOD
171 | + " null or not present using default values 2 min.");
172 | period = 2;
173 | }
174 | }
175 |
176 | Boolean active = true;
177 | try {
178 | String active_str = _propsq.getProperty(_queryName + "."
179 | + Constants.QUERY_ACTIVE);
180 | if (active_str != null) {
181 | if (active_str.equalsIgnoreCase("false")) {
182 | active = false;
183 | }
184 | }
185 | } catch (Exception ex) {
186 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName
187 | + "." + Constants.QUERY_ACTIVE
188 | + " null or not present " + ex.getMessage());
189 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
190 | + Constants.QUERY_ACTIVE
191 | + " null or not present using default values TRUE");
192 | }
193 |
194 | Boolean trim = true;
195 | try {
196 | String trim_str = _propsq.getProperty(_queryName + "."
197 | + Constants.QUERY_TRIM);
198 | if (trim_str != null) {
199 | if (trim_str.equalsIgnoreCase("false")) {
200 | trim = false;
201 | }
202 | }
203 | } catch (Exception ex) {
204 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
205 | + Constants.QUERY_TRIM + " null or not present "
206 | + ex.getMessage());
207 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
208 | + Constants.QUERY_TRIM
209 | + " null or not present using default values TRUE");
210 | }
211 |
212 | Boolean space = false;
213 | try {
214 | String space_str = _propsq.getProperty(_queryName + "."
215 | + Constants.QUERY_SPACE);
216 | if (space_str != null) {
217 | if (space_str.equalsIgnoreCase("false")) {
218 | space = false;
219 | }
220 | }
221 | } catch (Exception ex) {
222 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
223 | + Constants.QUERY_SPACE + " null or not present "
224 | + ex.getMessage());
225 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
226 | + Constants.QUERY_SPACE
227 | + " null or not present using default values TRUE");
228 | }
229 |
230 | List excludeColumns = new ArrayList();
231 | try {
232 | String excludeColumnsList = new String(_propsq
233 | .getProperty(_queryName + "."
234 | + Constants.QUERY_EXCLUDE_COLUMNS));
235 |
236 | StringTokenizer st = new StringTokenizer(excludeColumnsList,
237 | Constants.DELIMITER);
238 | while (st.hasMoreTokens()) {
239 | String token = st.nextToken().toString();
240 | Integer tmpInteger = Integer.valueOf(token);
241 | excludeColumns.add(tmpInteger);
242 | }
243 | } catch (Exception ex) {
244 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
245 | + Constants.QUERY_EXCLUDE_COLUMNS + " error "
246 | + ex.getMessage());
247 | }
248 |
249 | List raceExcludeColumns = new ArrayList();
250 | try {
251 | String excludeColumnsList = new String(_propsq
252 | .getProperty(_queryName + "."
253 | + Constants.RACE_CONDITION_EXCLUDE_COLUMNS));
254 |
255 | StringTokenizer st = new StringTokenizer(excludeColumnsList,
256 | Constants.DELIMITER);
257 | while (st.hasMoreTokens()) {
258 | String token = st.nextToken().toString();
259 | Integer tmpInteger = Integer.valueOf(token);
260 | excludeColumns.add(tmpInteger);
261 | }
262 | } catch (Exception ex) {
263 | SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "."
264 | + Constants.RACE_CONDITION_EXCLUDE_COLUMNS + " error "
265 | + ex.getMessage());
266 | }
267 |
268 |
269 |
270 | Query q = new Query(query, _queryName, noDataFound, raceCondQuery,
271 | raceCondValue, period, active, trim, space, excludeColumns,
272 | raceExcludeColumns);
273 |
274 | return q;
275 | } catch (Exception ex) {
276 |
277 | SmartLogger.logThis(Level.ERROR, "Error on Configurator on getQueryProperties("
278 | + _propsq.toString() + ") " + ex.getMessage());
279 | return null;
280 | }
281 | }
282 |
283 |
284 | /*protected Query[] refresh(Query[] _myquery, String _prpFile,String _extraPrpFile) {
285 | if (_prpFile!=null){
286 | Properties _prp = getPropsFromFile(_prpFile);
287 | Query[] q = Configurator.getQueries(_prp);
288 |
289 |
290 |
291 | _prp = getPropsFromFile(_extraPrpFile);
292 | Query[] q = Configurator.getQueries(_prp);
293 |
294 |
295 | Configurator.getQueryProperties(_prpFile, q);
296 | }
297 |
298 |
299 | /*Properties _prp = getPropsFromFile(_prpFile);
300 | for (int i = 0; i < _myquery.length; i++) {
301 | try {
302 | Query qnew = Configurator.getQueryProperties(_prp, _myquery[i]
303 | .getName());
304 | if (!_myquery[i].getSQL().equalsIgnoreCase(qnew.getSQL())) {
305 | _myquery[i].setSql(qnew.getSQL());
306 | SmartLogger.logThis(Level.INFO, "Statement changed on query "
307 | + _myquery[i].getName() + " new statement ->"
308 | + qnew.getSQL());
309 | }
310 | if ((_myquery[i].getActive().equals(true) && qnew.getActive()
311 | .equals(false))
312 | || (_myquery[i].getActive().equals(false) && qnew
313 | .getActive().equals(true))) {
314 |
315 | _myquery[i].setActive(qnew.getActive());
316 | SmartLogger.logThis(Level.INFO, "Status of query "
317 | + _myquery[i].getName() + " has changed ->"
318 | + qnew.getActive());
319 | }
320 | if (_myquery[i].getPeriod() != qnew.getPeriod()) {
321 | _myquery[i].setPeriod(qnew.getPeriod());
322 | if (qnew.getPeriod() > 0) {
323 | Date now = new Date(System.currentTimeMillis());
324 | Date newNextRun = new Date(now.getTime()
325 | + (qnew.getPeriod() * 1000 * 60));
326 | _myquery[i].setNextrun(newNextRun);
327 | }
328 | SmartLogger.logThis(Level.INFO, "Period of query "
329 | + _myquery[i].getName() + " has changed ->"
330 | + qnew.getPeriod());
331 | }
332 | if (!_myquery[i].getRaceQuery().equalsIgnoreCase(
333 | qnew.getRaceQuery())) {
334 | _myquery[i].setRaceQuery(qnew.getRaceQuery());
335 | SmartLogger.logThis(Level.INFO, "RaceQuery for query "
336 | + _myquery[i].getName() + " has changed ->"
337 | + qnew.getRaceQuery());
338 | }
339 | if (!_myquery[i].getRaceValue().equalsIgnoreCase(
340 | qnew.getRaceValue())) {
341 | _myquery[i].setRaceQuery(qnew.getRaceQuery());
342 | SmartLogger.logThis(Level.INFO, "RaceValue of query "
343 | + _myquery[i].getName() + " has changed ->"
344 | + qnew.getRaceValue());
345 | }
346 | } catch (Exception e) {
347 | // TODO Auto-generated catch block
348 | SmartLogger.logThis(Level.ERROR,
349 | "Error on Configurator while getting getQueryProperties( "
350 | + _prp + " , " + _myquery[i].getName()
351 | + ") Error " + e.getMessage());
352 | }
353 | }
354 | return _myquery;
355 | }*/
356 |
357 | private static void verifyConfig() {
358 | if (_props == null ) {
359 | throw new IllegalArgumentException("empty properties");
360 | }
361 |
362 | }
363 |
364 | public Configurator(String _url) throws IOException {
365 | Properties props = new Properties();
366 |
367 | FileInputStream fis;
368 | try {
369 | try {
370 | File configFile = new File(_url);
371 | File canonicalFile = configFile.getCanonicalFile(); // Fix: Retrieve the canonical path of the configuration file
372 | if (!canonicalFile.isFile()) { // Fix: Check if the canonical path is a valid file
373 | throw new FileNotFoundException("Invalid file path: " + canonicalFile.getPath());
374 | }
375 | fis = new FileInputStream(canonicalFile);
376 | props.load(fis);
377 | fis.close();
378 | } catch (Exception e) {
379 | SmartLogger.logThis(Level.ERROR,
380 | "Error on Configurator while retrieving configuration file "
381 | + _url + " " + e.getMessage());
382 | }
383 | _props = props;
384 | } catch (Exception e) {
385 | // TODO Auto-generated catch block
386 | SmartLogger.logThis(Level.ERROR, "Error on Configurator " + e.getMessage());
387 | }
388 | }
389 |
390 | private DBConn getConnection(String dbName) throws Exception {
391 | try {
392 | verifyConfig();
393 |
394 | SmartLogger.logThis(Level.DEBUG, "getConnection for database " + dbName);
395 | String url = "";
396 | try {
397 | url = new String(_props.getProperty(dbName + "."
398 | + Constants.CONN_URL));
399 | } catch (Exception ex) {
400 | SmartLogger.logThis(Level.ERROR,
401 | "Error on Configurator getConnection while getting "
402 | + dbName + "." + Constants.CONN_URL + " "
403 | + ex.getMessage());
404 | }
405 |
406 | String uname = "";
407 | try {
408 | uname = new String(_props.getProperty(dbName + "."
409 | + Constants.CONN_USERNAME));
410 | } catch (Exception ex) {
411 | try {
412 | SmartLogger.logThis(Level.DEBUG,
413 | "Error on Configurator getConnection while getting "
414 | + dbName + "."
415 | + Constants.CONN_USERNAME + " "
416 | + ex.getMessage());
417 |
418 | uname = new String(_props.getProperty(
419 | Constants.CONN_DEFAULT_USERNAME));
420 | } catch (Exception ex1){
421 | SmartLogger.logThis(Level.ERROR,
422 | "Error on Configurator getConnection while getting "
423 | + Constants.CONN_DEFAULT_USERNAME + " "
424 | + ex1.getMessage());
425 | }
426 | }
427 | String password = "";
428 | try {
429 | password = new String(_props.getProperty(dbName + "."
430 | + Constants.CONN_PASSWORD));
431 | } catch (Exception ex) {
432 | try{
433 | SmartLogger.logThis(Level.DEBUG,
434 | "Error on Configurator getConnection while getting "
435 | + dbName + "."
436 | + Constants.CONN_PASSWORD + " "
437 | + ex.getMessage());
438 | password = new String(_props.getProperty(
439 | Constants.CONN_DEFAULT_PASSWORD));
440 | } catch (Exception ex1){
441 | SmartLogger.logThis(Level.ERROR,
442 | "Error on Configurator getConnection while getting "
443 | + dbName + "." + Constants.CONN_PASSWORD + " "
444 | + ex.getMessage());
445 | }
446 | }
447 | DriverAdapterCPDS cpds = new DriverAdapterCPDS();
448 | cpds.setDriver(Constants.ORACLE_DRIVER);
449 | cpds.setUrl(url.toString());
450 | cpds.setUser(uname.toString());
451 | cpds.setPassword(password.toString());
452 | SharedPoolDataSource tds = new SharedPoolDataSource();
453 | tds.setConnectionPoolDataSource(cpds);
454 | // tds.setMaxActive(5);
455 | Integer maxActive = Integer.valueOf(5);
456 | try {
457 | maxActive = Integer.valueOf(_props.getProperty(dbName + "." + Constants.CONN_MAX_ACTIVE));
458 | } catch (Exception ex) {
459 | SmartLogger.logThis(Level.DEBUG, "Note: " + dbName + "."
460 | + Constants.CONN_MAX_ACTIVE + " " + ex.getMessage());
461 | try {
462 | maxActive = Integer.valueOf(_props
463 | .getProperty(Constants.DATABASES_LIST + "."
464 | + Constants.CONN_MAX_ACTIVE));
465 | } catch (Exception e) {
466 | SmartLogger.logThis(Level.WARN, "Note: "
467 | + Constants.DATABASES_LIST + "."
468 | + Constants.CONN_MAX_ACTIVE + " " + e.getMessage());
469 | SmartLogger.logThis(Level.WARN, "Warning I will use default value "
470 | + maxActive);
471 | }
472 | }
473 | tds.setMaxActive(maxActive.intValue());
474 | Integer maxWait = Integer.valueOf(100);
475 | try {
476 | maxWait = Integer.valueOf(_props.getProperty(dbName + "."
477 | + Constants.CONN_MAX_WAIT));
478 | } catch (Exception ex) {
479 | SmartLogger.logThis(Level.DEBUG, "Note: " + dbName + "."
480 | + Constants.CONN_MAX_WAIT + " " + ex.getMessage());
481 | try {
482 | maxWait = Integer.parseInt(_props
483 | .getProperty(Constants.DATABASES_LIST + "."
484 | + Constants.CONN_MAX_WAIT));
485 | } catch (Exception e) {
486 | SmartLogger.logThis(Level.WARN, "Note: "
487 | + Constants.DATABASES_LIST + "."
488 | + Constants.CONN_MAX_WAIT + " " + e.getMessage());
489 | SmartLogger.logThis(Level.WARN, "Warning I will use default value "
490 | + maxWait);
491 | }
492 | }
493 | tds.setMaxWait(maxWait.intValue());
494 | Integer maxIdle = Integer.valueOf(1);
495 | try {
496 | maxIdle = Integer.valueOf(_props.getProperty(dbName + "."
497 | + Constants.CONN_MAX_IDLE));
498 | } catch (Exception ex) {
499 | SmartLogger.logThis(Level.DEBUG, "Note: " + dbName + "."
500 | + Constants.CONN_MAX_IDLE + " " + ex.getMessage());
501 | try {
502 | maxIdle = Integer.valueOf(_props
503 | .getProperty(Constants.DATABASES_LIST + "."
504 | + Constants.CONN_MAX_IDLE));
505 | } catch (Exception e) {
506 | SmartLogger.logThis(Level.WARN, "Note: "
507 | + Constants.DATABASES_LIST + "."
508 | + Constants.CONN_MAX_IDLE + " " + e.getMessage());
509 | SmartLogger.logThis(Level.WARN, "Warning I will use default value "
510 | + maxIdle);
511 | }
512 | }
513 | tds.setMaxIdle(maxIdle.intValue());
514 |
515 | SmartLogger.logThis( Level.INFO,"DB Pool created: " + tds);
516 | SmartLogger.logThis( Level.INFO, "URL=" + url.toString() );
517 | SmartLogger.logThis( Level.INFO, "maxPoolSize=" + tds.getMaxActive() );
518 | SmartLogger.logThis( Level.INFO, "maxIdleSize=" + tds.getMaxIdle() );
519 | SmartLogger.logThis( Level.INFO, "maxIdleTime=" + tds.getMinEvictableIdleTimeMillis() + "ms" );
520 | SmartLogger.logThis( Level.INFO, "poolTimeout=" + tds.getMaxWait() );
521 | SmartLogger.logThis( Level.INFO, "timeBetweenEvictionRunsMillis=" + tds.getTimeBetweenEvictionRunsMillis() );
522 | SmartLogger.logThis( Level.INFO, "numTestsPerEvictionRun=" + tds.getNumTestsPerEvictionRun() );
523 |
524 |
525 | tds.setValidationQuery(Constants.ORACLE_VALIDATION_QUERY);
526 | Connection con = null;
527 | con = tds.getConnection();
528 | PreparedStatement p_stmt = null;
529 | p_stmt = con.prepareStatement(Constants.ORACLE_WHOAMI_QUERY);
530 | ResultSet rs = null;
531 | rs = p_stmt.executeQuery();
532 | String tempStr = new String("");
533 | ResultSetMetaData rsmd = rs.getMetaData();
534 | int numColumns = rsmd.getColumnCount();
535 | while (rs.next()) {
536 | for (int r = 1; r < numColumns + 1; r++) {
537 | tempStr = tempStr + rs.getObject(r).toString().trim();
538 | }
539 | }
540 | SmartLogger.logThis(Level.INFO, "Connected as " + tempStr);
541 |
542 | con.close();
543 | con = null;
544 | con = tds.getConnection();
545 | p_stmt = con.prepareStatement(Constants.ORACLE_DBNAME_QUERY);
546 | rs = p_stmt.executeQuery();
547 | rsmd = rs.getMetaData();
548 | numColumns = rsmd.getColumnCount();
549 | tempStr = "";
550 | while (rs.next()) {
551 | for (int r = 1; r < numColumns + 1; r++) {
552 | tempStr = tempStr + rs.getObject(r).toString().trim();
553 | }
554 | }
555 | SmartLogger.logThis(Level.INFO, "--------- on Database -> " + tempStr);
556 | con.close();
557 | con = null;
558 | DBConn mydbconn = new DBConn(tds, dbName.toString());
559 | return mydbconn;
560 |
561 | } catch (Exception ex) {
562 | SmartLogger.logThis(Level.ERROR, "Error on Configurator for database " + dbName
563 | + " -->" + ex.getMessage());
564 | return null;
565 | }
566 | }
567 |
568 | public DBConn[] getConnections() throws Exception {
569 | try {
570 | verifyConfig();
571 | String[] DatabaseList = getDBList();
572 | Collection connections = new ArrayList();
573 | for (int i = 0; i < DatabaseList.length; i++) {
574 | DBConn dbc=this.getConnection(DatabaseList[i]);
575 | if (dbc!=null){
576 | connections.add(dbc);
577 | }else {
578 | SmartLogger.logThis(Level.INFO,"This Database "+DatabaseList[i]+" removed");
579 | }
580 | }
581 | // fis.close();
582 | DBConn[] connArray = (DBConn[]) connections.toArray(new DBConn[0]);
583 | return connArray;
584 | } catch (Exception ex) {
585 | SmartLogger.logThis(Level.ERROR, "Error on Configurator getConnections "
586 | + ex.getMessage());
587 | return null;
588 | }
589 | }
590 |
591 | public String[] getDBList() throws Exception {
592 | try {
593 | verifyConfig();
594 | String dblist = "";
595 | try {
596 | dblist = new String(_props
597 | .getProperty(Constants.DATABASES_LIST));
598 | } catch (Exception e) {
599 | SmartLogger.logThis(Level.ERROR,
600 | "Error on Configurator while retriving the databases list "
601 | + Constants.DATABASES_LIST + " " + e);
602 | }
603 |
604 | StringTokenizer st = new StringTokenizer(dblist,
605 | Constants.DELIMITER);
606 | String[] DatabaseList = new String[st.countTokens()];
607 | int count = 0;
608 | while (st.hasMoreTokens()) {
609 | String token = st.nextToken().toString();
610 | DatabaseList[count] = token;
611 | count++;
612 | }
613 | // fisdb.close();
614 | return DatabaseList;
615 | } catch (Exception ex) {
616 | SmartLogger.logThis(Level.ERROR,
617 | "Error on Configurator while retriving the databases list "
618 | + Constants.DATABASES_LIST + " " + ex);
619 | return null;
620 | }
621 | }
622 |
623 | public Integer getMaxThread() throws Exception {
624 | try {
625 | verifyConfig();
626 | return Integer.valueOf(_props.getProperty(Constants.ORABBIX_DAEMON_THREAD));
627 | } catch (Exception ex) {
628 | SmartLogger.logThis(Level.ERROR, "Error on Configurator while retriving the "
629 | + Constants.ORABBIX_DAEMON_THREAD + " " + ex);
630 | return null;
631 | }
632 | }
633 |
634 | public String getPidFile() throws Exception {
635 | try {
636 | verifyConfig();
637 | String _pidfile = new String(_props
638 | .getProperty(Constants.ORABBIX_PIDFILE));
639 | SmartLogger.logThis(Level.INFO, "PidFile -> " + _pidfile);
640 |
641 | if (_pidfile == "") {
642 | SmartLogger.logThis(Level.ERROR, "Error retrieving pidfile from " + _props);
643 | }
644 | return _pidfile;
645 |
646 | } catch (Exception ex) {
647 |
648 | SmartLogger.logThis(Level.ERROR, "Error on Configurator getPidFile " + ex);
649 | return null;
650 | }
651 | }
652 |
653 | public static String getQueryFile() {
654 | String queryFile = new String(_props
655 | .getProperty(Constants.QUERY_LIST_FILE));
656 | return queryFile;
657 | }
658 |
659 | public static String getQueryFile(String dbName) {
660 | try {
661 | verifyConfig();
662 | if (_props.getProperty(dbName + "." + Constants.QUERY_LIST_FILE) != null) {
663 | return (_props.getProperty(dbName + "."
664 | + Constants.QUERY_LIST_FILE));
665 | }
666 | } catch (Exception ex) {
667 | SmartLogger.logThis(Level.ERROR, "Error on Configurator on getQueryFile("
668 | + dbName + ") " + ex.getMessage());
669 | SmartLogger.logThis(Level.WARN, "I'm going to return getQueryFile() ");
670 | return getQueryFile();
671 | }
672 | return null;
673 | }
674 | public static String getExtraQueryFile(String dbName) {
675 | try {
676 | verifyConfig();
677 | if (_props.getProperty(dbName + "." + Constants.EXTRA_QUERY_LIST_FILE) != null) {
678 | return (_props.getProperty(dbName + "."
679 | + Constants.EXTRA_QUERY_LIST_FILE));
680 | }
681 | } catch (Exception ex) {
682 | SmartLogger.logThis(Level.ERROR, "Error on Configurator on getExtraQueryFile("
683 | + dbName + ") " + ex.getMessage());
684 | }
685 | return null;
686 | }
687 |
688 | public Properties getQueryProp() {
689 | verifyConfig();
690 | Properties propsq = new Properties();
691 | try {
692 | FileInputStream fisq;
693 | String fiqp = new String(_props
694 | .getProperty(Constants.QUERY_LIST_FILE));
695 | File queryFile = new File(fiqp);
696 | fisq = new FileInputStream(new java.io.File(queryFile
697 | .getAbsoluteFile().getCanonicalPath()));
698 | queryFile = null;
699 | propsq.load(fisq);
700 | fisq.close();
701 | } catch (Exception e) {
702 | // TODO Auto-generated catch block
703 | SmartLogger.logThis(Level.ERROR, "Error on Configurator while getting "
704 | + Constants.QUERY_LIST_FILE + " error -> " + e.getMessage());
705 | return null;
706 | }
707 | return propsq;
708 | }
709 |
710 | public Properties getQueryProp(String dbname) {
711 | try {
712 | verifyConfig();
713 | Properties propsq = new Properties();
714 | FileInputStream fisq;
715 | if (dbname != "" && dbname != null) {
716 | // logger.warn("Method called with null or empty string on Configurator "+dbname);
717 | File queryFile = new File(_props.getProperty(dbname + "."
718 | + Constants.QUERY_LIST_FILE));
719 | fisq = new FileInputStream(new java.io.File(queryFile
720 | .getAbsoluteFile().getCanonicalPath()));
721 | queryFile = null;
722 | SmartLogger.logThis(Level.DEBUG, "Debug loaded the " + dbname + "."
723 | + Constants.QUERY_LIST_FILE);
724 | // fisq = new FileInputStream (new java.io.File(
725 | // _props.getProperty(dbname+"."+Constants.QUERY_LIST_FILE)));
726 | } else {
727 | // fisq = new FileInputStream (new java.io.File(
728 | // _props.getProperty(Constants.QUERY_LIST_FILE)));
729 | SmartLogger.logThis(Level.DEBUG, "Debug I'm loading the default "
730 | + Constants.QUERY_LIST_FILE + " " + dbname
731 | + " don't have it's own");
732 | File queryFile = new File(_props
733 | .getProperty(Constants.QUERY_LIST_FILE));
734 | fisq = new FileInputStream(new java.io.File(queryFile
735 | .getAbsoluteFile().getCanonicalPath()));
736 | queryFile = null;
737 | }
738 | propsq.load(fisq);
739 | fisq.close();
740 | return propsq;
741 | } catch (Exception e) {
742 | // TODO Auto-generated catch block
743 | SmartLogger.logThis(Level.ERROR, "Error on Configurator getting "+Constants.QUERY_LIST_FILE +" " + dbname
744 | + e.getMessage());
745 | return null;
746 | }
747 | }
748 |
749 | public String getZabbixServer() throws Exception {
750 | try {
751 | verifyConfig();
752 | return _props.getProperty(Constants.ZABBIX_SERVER_HOST);
753 |
754 | } catch (Exception ex) {
755 | SmartLogger.logThis(Level.ERROR,
756 | "Error on Configurator while retriving zabbix server host "
757 | + Constants.ZABBIX_SERVER_HOST + " or port "
758 | + Constants.ZABBIX_SERVER_PORT + " " + ex);
759 | return null;
760 | }
761 | }
762 |
763 | public int getZabbixServerPort() throws Exception {
764 | try {
765 | verifyConfig();
766 | int port = Integer.parseInt(_props.getProperty(Constants.ZABBIX_SERVER_PORT));
767 | return port;
768 | } catch (Exception ex) {
769 | SmartLogger.logThis(Level.ERROR,
770 | "Error on Configurator while retriving zabbix server port "
771 | + Constants.ZABBIX_SERVER_PORT + " " + ex);
772 | SmartLogger.logThis(Level.WARN, "I will use the default port "
773 | + Constants.ZABBIX_SERVER_DEFAULT_PORT);
774 | return Constants.ZABBIX_SERVER_DEFAULT_PORT;
775 | }
776 | }
777 |
778 | public Hashtable getZabbixServers() throws Exception {
779 | String zxblist = new String();
780 | try {
781 | zxblist = new String(_props
782 | .getProperty(Constants.ZABBIX_SERVER_LIST));
783 | } catch (Exception e) {
784 | SmartLogger.logThis(Level.ERROR, "Error on getZabbixServers while getting "
785 | + Constants.ZABBIX_SERVER_LIST + " " + e.getMessage());
786 | }
787 | StringTokenizer st = new StringTokenizer(zxblist, Constants.DELIMITER);
788 | Hashtable ZabbixServers = new Hashtable();
789 | int count = 0;
790 | while (st.hasMoreTokens()) {
791 | String token = st.nextToken().toString();
792 | String server = new String();
793 | try {
794 | server = new String(_props.getProperty(token + "."
795 | + Constants.ZABBIX_SERVER_HOST));
796 | } catch (Exception e) {
797 | SmartLogger.logThis(Level.ERROR, "Error on getZabbixServers while getting "
798 | + token + "." + Constants.ZABBIX_SERVER_HOST + " "
799 | + e.getMessage());
800 | }
801 | Integer port = Integer.valueOf(Constants.ZABBIX_SERVER_DEFAULT_PORT);
802 | try {
803 | port = Integer.valueOf(_props.getProperty(token + "." + Constants.ZABBIX_SERVER_PORT));
804 | } catch (Exception e) {
805 | SmartLogger.logThis(Level.WARN,
806 | "Warning on getZabbixServers while getting " + token
807 | + "." + Constants.ZABBIX_SERVER_PORT + " "
808 | + e.getMessage());
809 | SmartLogger.logThis(Level.WARN, "Warning I will use the default port"
810 | + port);
811 | }
812 | ZabbixServers.put(server, port);
813 | count++;
814 | }
815 | // fisdb.close();
816 | return ZabbixServers;
817 | }
818 |
819 | public static boolean hasQueryFile(String dbName) {
820 | if (dbName == null) {
821 | return false;
822 | }
823 | try {
824 | verifyConfig();
825 | if (_props.getProperty(dbName + "." + Constants.QUERY_LIST_FILE) != null) {
826 | return true;
827 | }
828 | } catch (Exception ex) {
829 | SmartLogger.logThis(Level.ERROR, "Error on Configurator getting"+ Constants.QUERY_LIST_FILE
830 | + dbName + ex.getMessage());
831 | return false;
832 | }
833 | return false;
834 | }
835 |
836 | public static boolean hasExtraQueryFile(String dbName) {
837 | if (dbName == null) {
838 | return false;
839 | }
840 | try {
841 | verifyConfig();
842 | if (_props.getProperty(dbName + "." + Constants.EXTRA_QUERY_LIST_FILE) != null) {
843 | return true;
844 | }
845 | } catch (Exception ex) {
846 | SmartLogger.logThis(Level.ERROR, "Error on Configurator getting"+ Constants.EXTRA_QUERY_LIST_FILE
847 | + dbName + ex.getMessage());
848 | return false;
849 | }
850 | return false;
851 | }
852 |
853 | public boolean isEqualsDBList(DBConn[] _dbc) throws Exception {
854 | try {
855 | verifyConfig();
856 |
857 | String[] localdblist = this.getDBList();
858 | String[] remotedblist = new String[_dbc.length];
859 | for (int i = 0; i < _dbc.length; i++) {
860 | remotedblist[i] = _dbc[i].getName();
861 | }
862 | return ArrayUtils.isEquals(localdblist, remotedblist);
863 | } catch (Exception ex) {
864 | SmartLogger.logThis(Level.ERROR,
865 | "Error on Configurator while comparing the databases lists on isEqualsDBList "
866 | + ex);
867 | return false;
868 | }
869 | }
870 |
871 | public DBConn[] rebuildDBList(DBConn[] _dbc) {
872 | try {
873 | verifyConfig();
874 | String[] localdblist = this.getDBList();
875 | String[] remotedblist = new String[_dbc.length];
876 | for (int i = 0; i < _dbc.length; i++) {
877 | remotedblist[i] = _dbc[i].getName();
878 | }
879 |
880 | Collection connections = new ArrayList();
881 | for (int j = 0; j < localdblist.length; j++) {
882 | if (ArrayUtils.contains(remotedblist, localdblist[j])) {
883 | DBConn tmpDBConn;
884 | tmpDBConn = _dbc[ArrayUtils.indexOf(remotedblist,
885 | localdblist[j])];
886 | connections.add(tmpDBConn);
887 | }
888 | if (!ArrayUtils.contains(remotedblist, localdblist[j])) {
889 | /*
890 | * adding database
891 | */
892 | SmartLogger.logThis(Level.INFO, "New database founded! "
893 | + localdblist[j]);
894 | DBConn tmpDBConn = this.getConnection(localdblist[j]);
895 | if (tmpDBConn != null) {
896 | connections.add(tmpDBConn);
897 | }
898 | }
899 | }
900 | for (int x = 0; x < _dbc.length; x++) {
901 | if (!ArrayUtils.contains(localdblist, _dbc[x].getName())) {
902 | SmartLogger.logThis(Level.WARN, "Database " + _dbc[x].getName()
903 | + " removed from configuration file");
904 | /**
905 | * removing database
906 | */
907 | // _dbc[x].closeAll();
908 | _dbc[x].getSPDS().close();
909 | SmartLogger.logThis(Level.WARN, "Database " + _dbc[x].getName()
910 | + " conections closed");
911 | _dbc[x] = null;
912 | }
913 | }
914 | DBConn[] connArray = (DBConn[]) connections.toArray(new DBConn[0]);
915 | return connArray;
916 | } catch (Exception ex) {
917 | SmartLogger.logThis(Level.ERROR,
918 | "Error on Configurator while retriving the databases list "
919 | + Constants.DATABASES_LIST + " error:" + ex);
920 | return _dbc;
921 | }
922 |
923 | }
924 | public static Integer getSleep() throws Exception {
925 | try{
926 | verifyConfig();
927 | Integer sleep = Integer.valueOf(5);
928 | try{
929 | sleep = Integer.valueOf(_props.getProperty(Constants.ORABBIX_DAEMON_SLEEP));
930 | }catch (Exception e){
931 | SmartLogger.logThis(Level.WARN,"Warning while getting "+Constants.ORABBIX_DAEMON_SLEEP+" I will use the default "+sleep);
932 | }
933 | return sleep;
934 |
935 | } catch (Exception ex){
936 |
937 | SmartLogger.logThis(Level.ERROR,"Error on Configurator while retriving "+Constants.ORABBIX_DAEMON_SLEEP+" "+ex);
938 | return null;
939 | }
940 | }
941 |
942 | public static boolean propVerify(String _prop) {
943 | // TODO Auto-generated method stub
944 |
945 | if (_prop!= null){
946 | if (!_prop.isEmpty()&&!_prop.equals("")){
947 | Properties props = new Properties();
948 | FileInputStream fisq;
949 | File queryFile = new File(_prop);
950 | try {
951 | fisq = new FileInputStream(new java.io.File(queryFile
952 | .getAbsoluteFile().getCanonicalPath()));
953 | props.load(fisq);
954 | fisq.close();
955 | return true;
956 | }
957 | catch (Exception ex){
958 | SmartLogger.logThis(Level.DEBUG,"Error on Configurator while checking file "+_prop+" "+ex);
959 | return false;
960 | }
961 | }
962 | }
963 | return false;
964 | }
965 |
966 | public static Querybox buildQueryBoxbyDBName(String dbname){
967 | String queryFile =null;
968 | String extraQueryFile=null;
969 |
970 | if (hasQueryFile(dbname)) {
971 | queryFile = getQueryFile(dbname);
972 | } else {
973 | queryFile = getQueryFile();
974 | }
975 |
976 | if (hasExtraQueryFile(dbname)){
977 | extraQueryFile = getExtraQueryFile(dbname);
978 | }
979 |
980 | Querybox qboxtmp = new Querybox(dbname,
981 | queryFile,extraQueryFile);
982 | return qboxtmp;
983 | }
984 |
985 |
986 | }
987 |
--------------------------------------------------------------------------------