Search in sources :

Example 6 with DBUtils

use of org.opennms.core.utils.DBUtils in project opennms by OpenNMS.

the class CategoryModel method getNodeAvailability.

/**
     * Return the availability percentage for all managed services on the given
     * node from the given start time until the given end time. If there are no
     * managed services on this node, then a value of -1 is returned.
     *
     * @param nodeId a int.
     * @param start a {@link java.util.Date} object.
     * @param end a {@link java.util.Date} object.
     * @return a double.
     * @throws java.sql.SQLException if any.
     */
static double getNodeAvailability(int nodeId, Date start, Date end) throws SQLException {
    if (start == null || end == null) {
        throw new IllegalArgumentException("Cannot take null parameters.");
    }
    if (end.before(start)) {
        throw new IllegalArgumentException("Cannot have an end time before the start time.");
    }
    if (end.equals(start)) {
        throw new IllegalArgumentException("Cannot have an end time equal to the start time.");
    }
    double avail = -1;
    final DBUtils d = new DBUtils(CategoryModel.class);
    try {
        Connection conn = DataSourceFactory.getInstance().getConnection();
        d.watch(conn);
        PreparedStatement stmt = conn.prepareStatement("select getManagePercentAvailNodeWindow(?, ?, ?) as avail");
        d.watch(stmt);
        stmt.setInt(1, nodeId);
        // yes, these are supposed to be backwards, the end time first
        stmt.setTimestamp(2, new Timestamp(end.getTime()));
        stmt.setTimestamp(3, new Timestamp(start.getTime()));
        ResultSet rs = stmt.executeQuery();
        d.watch(rs);
        if (rs.next()) {
            avail = rs.getDouble("avail");
        }
    } catch (final SQLException e) {
        LOG.warn("Failed to get node availability for nodeId {}", nodeId, e);
    } finally {
        d.cleanUp();
    }
    return avail;
}
Also used : SQLException(java.sql.SQLException) DBUtils(org.opennms.core.utils.DBUtils) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 7 with DBUtils

use of org.opennms.core.utils.DBUtils in project opennms by OpenNMS.

the class JasperReportService method runAndRender.

/**
     * {@inheritDoc}
     */
@Override
public void runAndRender(final Map<String, Object> reportParms, final String reportId, final ReportFormat format, final OutputStream outputStream) throws ReportException {
    try {
        Logging.withPrefix(LOG4J_CATEGORY, new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                final JasperReport jasperReport = getJasperReport(reportId);
                final Map<String, Object> jrReportParms = buildJRparameters(reportParms, jasperReport.getParameters());
                jrReportParms.putAll(buildSubreport(reportId, jasperReport));
                if ("jdbc".equalsIgnoreCase(m_globalReportRepository.getEngine(reportId))) {
                    final DBUtils db = new DBUtils();
                    try {
                        final Connection connection = DataSourceFactory.getInstance().getConnection();
                        db.watch(connection);
                        final JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, jrReportParms, connection);
                        exportReport(format, jasperPrint, outputStream);
                    } finally {
                        db.cleanUp();
                    }
                } else if ("null".equalsIgnoreCase(m_globalReportRepository.getEngine(reportId))) {
                    final JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, jrReportParms, new JREmptyDataSource());
                    exportReport(format, jasperPrint, outputStream);
                }
                return null;
            }
        });
    } catch (final Exception e) {
        if (e instanceof ReportException)
            throw (ReportException) e;
        throw new ReportException("Failed to run Jasper report " + reportId, e);
    }
}
Also used : JREmptyDataSource(net.sf.jasperreports.engine.JREmptyDataSource) JasperPrint(net.sf.jasperreports.engine.JasperPrint) DBUtils(org.opennms.core.utils.DBUtils) Connection(java.sql.Connection) ReportException(org.opennms.api.reporting.ReportException) JasperReport(net.sf.jasperreports.engine.JasperReport) Map(java.util.Map) HashMap(java.util.HashMap) ReportException(org.opennms.api.reporting.ReportException) JRException(net.sf.jasperreports.engine.JRException)

Example 8 with DBUtils

use of org.opennms.core.utils.DBUtils in project opennms by OpenNMS.

the class ImportAssetsServlet method getCurrentAssetNodesList.

/**
     * <p>getCurrentAssetNodesList</p>
     *
     * @return a {@link java.util.List} object.
     * @throws java.sql.SQLException if any.
     */
public List<Integer> getCurrentAssetNodesList() throws SQLException {
    List<Integer> list = new ArrayList<Integer>();
    final DBUtils d = new DBUtils(getClass());
    try {
        Connection conn = DataSourceFactory.getInstance().getConnection();
        d.watch(conn);
        Statement stmt = conn.createStatement();
        d.watch(stmt);
        ResultSet rs = stmt.executeQuery("SELECT NODEID FROM ASSETS");
        d.watch(rs);
        while (rs.next()) {
            list.add(Integer.valueOf(rs.getInt("NODEID")));
        }
    } finally {
        d.cleanUp();
    }
    return list;
}
Also used : Statement(java.sql.Statement) ArrayList(java.util.ArrayList) DBUtils(org.opennms.core.utils.DBUtils) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet)

Example 9 with DBUtils

use of org.opennms.core.utils.DBUtils in project opennms by OpenNMS.

the class AssetModel method createAsset.

/**
     * <p>createAsset</p>
     *
     * @param asset a {@link org.opennms.web.asset.Asset} object.
     * @throws java.sql.SQLException if any.
     */
public void createAsset(Asset asset) throws SQLException {
    Assert.notNull(asset, "argument asset cannot be null");
    final DBUtils d = new DBUtils(getClass());
    try {
        Connection conn = DataSourceFactory.getInstance().getConnection();
        d.watch(conn);
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO ASSETS (nodeID,category,manufacturer,vendor,modelNumber,serialNumber,description,circuitId,assetNumber,operatingSystem,rack,slot,port,region,division,department,address1,address2,city,state,zip,building,floor,room,vendorPhone,vendorFax,userLastModified,lastModifiedDate,dateInstalled,lease,leaseExpires,supportPhone,maintContract,vendorAssetNumber,maintContractExpires,displayCategory,notifyCategory,pollerCategory,thresholdCategory,comment,username,password,enable,connection,autoenable,cpu,ram,storagectrl,hdd1,hdd2,hdd3,hdd4,hdd5,hdd6,numpowersupplies,inputpower,additionalhardware,admin,snmpcommunity,rackunitheight,longitude,latitude,country) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        d.watch(stmt);
        stmt.setInt(1, asset.nodeId);
        stmt.setString(2, asset.category);
        stmt.setString(3, asset.manufacturer);
        stmt.setString(4, asset.vendor);
        stmt.setString(5, asset.modelNumber);
        stmt.setString(6, asset.serialNumber);
        stmt.setString(7, asset.description);
        stmt.setString(8, asset.circuitId);
        stmt.setString(9, asset.assetNumber);
        stmt.setString(10, asset.operatingSystem);
        stmt.setString(11, asset.rack);
        stmt.setString(12, asset.slot);
        stmt.setString(13, asset.port);
        stmt.setString(14, asset.region);
        stmt.setString(15, asset.division);
        stmt.setString(16, asset.department);
        stmt.setString(17, asset.address1);
        stmt.setString(18, asset.address2);
        stmt.setString(19, asset.city);
        stmt.setString(20, asset.state);
        stmt.setString(21, asset.zip);
        stmt.setString(22, asset.building);
        stmt.setString(23, asset.floor);
        stmt.setString(24, asset.room);
        stmt.setString(25, asset.vendorPhone);
        stmt.setString(26, asset.vendorFax);
        stmt.setString(27, asset.userLastModified);
        stmt.setTimestamp(28, new Timestamp(asset.lastModifiedDate.getTime()));
        stmt.setString(29, asset.dateInstalled);
        stmt.setString(30, asset.lease);
        stmt.setString(31, asset.leaseExpires);
        stmt.setString(32, asset.supportPhone);
        stmt.setString(33, asset.maintContract);
        stmt.setString(34, asset.vendorAssetNumber);
        stmt.setString(35, asset.maintContractExpires);
        stmt.setString(36, asset.displayCategory);
        stmt.setString(37, asset.notifyCategory);
        stmt.setString(38, asset.pollerCategory);
        stmt.setString(39, asset.thresholdCategory);
        stmt.setString(40, asset.comments);
        stmt.setString(41, asset.username);
        stmt.setString(42, asset.password);
        stmt.setString(43, asset.enable);
        stmt.setString(44, asset.connection);
        stmt.setString(45, asset.autoenable);
        stmt.setString(46, asset.cpu);
        stmt.setString(47, asset.ram);
        stmt.setString(48, asset.storagectrl);
        stmt.setString(49, asset.hdd1);
        stmt.setString(50, asset.hdd2);
        stmt.setString(51, asset.hdd3);
        stmt.setString(52, asset.hdd4);
        stmt.setString(53, asset.hdd5);
        stmt.setString(54, asset.hdd6);
        stmt.setString(55, asset.numpowersupplies);
        stmt.setString(56, asset.inputpower);
        stmt.setString(57, asset.additionalhardware);
        stmt.setString(58, asset.admin);
        stmt.setString(59, asset.snmpcommunity);
        stmt.setString(60, asset.rackunitheight);
        stmt.setFloat(61, safeFloat(asset.longitude));
        stmt.setFloat(62, safeFloat(asset.latitude));
        stmt.setString(63, asset.country);
        stmt.execute();
    } finally {
        d.cleanUp();
    }
}
Also used : DBUtils(org.opennms.core.utils.DBUtils) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 10 with DBUtils

use of org.opennms.core.utils.DBUtils in project opennms by OpenNMS.

the class NotificationManager method acknowledgeNotice.

/**
     * <p>acknowledgeNotice</p>
     *
     * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
     * @param uei a {@link java.lang.String} object.
     * @param matchList an array of {@link java.lang.String} objects.
     * @return a {@link java.util.Collection} object.
     * @throws java.sql.SQLException if any.
     * @throws java.io.IOException if any.
     */
public Collection<Integer> acknowledgeNotice(final Event event, final String uei, final String[] matchList) throws SQLException, IOException {
    List<Integer> notifIDs = new LinkedList<Integer>();
    final DBUtils dbUtils = new DBUtils(getClass());
    try {
        // First get most recent event ID from notifications 
        // that match the matchList, then get all notifications
        // with this event ID
        Connection connection = getConnection();
        dbUtils.watch(connection);
        // Verify if parameter matching is required
        boolean matchParameters = false;
        for (int i = 0; i < matchList.length; i++) {
            if (matchList[i].startsWith("parm[")) {
                matchParameters = true;
                break;
            }
        }
        StringBuffer sql = new StringBuffer(matchParameters ? "SELECT n.eventid FROM notifications n, events e WHERE n.eventid = e.eventid AND n.eventuei=? " : "SELECT n.eventid FROM notifications n WHERE n.eventuei=? ");
        for (int i = 0; i < matchList.length; i++) {
            if (matchList[i].startsWith("parm[")) {
                sql.append("AND e.eventparms LIKE ? ");
            } else {
                sql.append("AND n.").append(matchList[i]).append("=? ");
            }
        }
        sql.append("ORDER BY eventid desc limit 1");
        PreparedStatement statement = connection.prepareStatement(sql.toString());
        dbUtils.watch(statement);
        statement.setString(1, uei);
        for (int i = 0; i < matchList.length; i++) {
            if (matchList[i].equals("nodeid")) {
                statement.setLong(i + 2, event.getNodeid());
            }
            if (matchList[i].equals("interfaceid")) {
                statement.setString(i + 2, event.getInterface());
            }
            if (matchList[i].equals("serviceid")) {
                statement.setInt(i + 2, getServiceId(event.getService()));
            }
            if (matchList[i].startsWith("parm[")) {
                String match = matchList[i];
                String key = null;
                String param = null;
                String value = null;
                try {
                    key = match.substring(match.indexOf('[') + 1, match.indexOf(']'));
                } catch (Exception e) {
                }
                if (key != null) {
                    int numkey = 0;
                    if (key.startsWith("#")) {
                        try {
                            numkey = Integer.parseInt(key.substring(1));
                        } catch (Exception e) {
                        }
                    }
                    int idx = 1;
                    for (Parm p : event.getParmCollection()) {
                        if (numkey > 0) {
                            if (numkey == idx) {
                                param = p.getParmName();
                                value = p.getValue().getContent();
                            }
                        } else {
                            if (p.getParmName().equalsIgnoreCase(key)) {
                                param = p.getParmName();
                                value = p.getValue().getContent();
                            }
                        }
                        idx++;
                    }
                }
                statement.setString(i + 2, '%' + param + '=' + value + '%');
            }
        }
        ResultSet results = statement.executeQuery();
        dbUtils.watch(results);
        if (results != null && results.next()) {
            int eventID = results.getInt(1);
            notifIDs = doAcknowledgeNotificationsFromEvent(connection, dbUtils, eventID);
        } else {
            LOG.debug("No matching DOWN eventID found");
        }
    } finally {
        dbUtils.cleanUp();
    }
    return notifIDs;
}
Also used : Connection(java.sql.Connection) Parm(org.opennms.netmgt.xml.event.Parm) PreparedStatement(java.sql.PreparedStatement) LinkedList(java.util.LinkedList) SQLException(java.sql.SQLException) IOException(java.io.IOException) FilterParseException(org.opennms.netmgt.filter.api.FilterParseException) DBUtils(org.opennms.core.utils.DBUtils) ResultSet(java.sql.ResultSet)

Aggregations

DBUtils (org.opennms.core.utils.DBUtils)77 Connection (java.sql.Connection)68 PreparedStatement (java.sql.PreparedStatement)64 ResultSet (java.sql.ResultSet)50 SQLException (java.sql.SQLException)17 ArrayList (java.util.ArrayList)14 Timestamp (java.sql.Timestamp)12 Statement (java.sql.Statement)10 Filter (org.opennms.web.filter.Filter)9 ServletException (javax.servlet.ServletException)5 FilterParseException (org.opennms.netmgt.filter.api.FilterParseException)5 IfIndexFilter (org.opennms.web.event.filter.IfIndexFilter)5 InterfaceFilter (org.opennms.web.event.filter.InterfaceFilter)5 NodeFilter (org.opennms.web.event.filter.NodeFilter)5 ServiceFilter (org.opennms.web.event.filter.ServiceFilter)5 SeverityFilter (org.opennms.web.event.filter.SeverityFilter)5 Date (java.util.Date)4 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)3 InetAddress (java.net.InetAddress)3 RequestDispatcher (javax.servlet.RequestDispatcher)3