diff --git a/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp b/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp index 689aa3ed11..49b03f393d 100644 --- a/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp +++ b/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp @@ -27,31 +27,74 @@ var version = $get("snmpVersion"); if (version == ) { show("version3Fields"); + show("trapSection"); hide("version12Fields"); - } - else { + } else if (version == ) { + hide("version3Fields"); + show("version12Fields"); + hide("trapSection"); + } else { hide("version3Fields"); show("version12Fields"); + show("trapSection"); } + } - + + function securityLevelChange() { + var securityLevel = $get("securityLevel"); + if (securityLevel === "1") { + hide("authFieldsProtocol") + hide("authFieldsPassphrase") + hide("privFieldsProtocol") + hide("privFieldsPassphrase") + } else if (securityLevel === "2") { + show("authFieldsProtocol") + show("authFieldsPassphrase") + hide("privFieldsProtocol") + hide("privFieldsPassphrase") + } else if (securityLevel === "3") { + show("authFieldsProtocol") + show("authFieldsPassphrase") + show("privFieldsProtocol") + show("privFieldsPassphrase") + } + } + function snmpTest() { $set("snmpTestMessage", ""); snmpTestButton(true); - DataSourceEditDwr.snmpGetOid($get("snmpTestOid"), $get("host"), $get("port"), $get("snmpVersion"), - $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"), - $get("privProtocol"), $get("privPassphrase"), $get("engineId"), $get("contextEngineId"), + DataSourceEditDwr.snmpGetOid($get("snmpTestOid"), $get("host"), $get("port"), $get("snmpVersion"), + $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"), + $get("privProtocol"), $get("privPassphrase"), $get("securityLevel"), $get("contextName"), $get("retries"), $get("timeout"), snmpTestCB); } - + + function snmpWalk() { + $set("snmpTestMessage", ""); + snmpWalkButton(true); + DataSourceEditDwr.snmpWalkOid($get("snmpWalkOid"), $get("host"), $get("port"), $get("snmpVersion"), + $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"), + $get("privProtocol"), $get("privPassphrase"), $get("securityLevel"), + $get("contextName"), $get("retries"), $get("timeout"), snmpWalkCB); + } + function snmpTestCB() { setTimeout(snmpTestUpdate, 1000); } - + + function snmpWalkCB() { + setTimeout(snmpWalkUpdate, 1000); + } + function snmpTestUpdate() { DataSourceEditDwr.snmpGetOidUpdate(snmpTestUpdateCB); } - + + function snmpWalkUpdate() { + DataSourceEditDwr.snmpGetWalkUpdate(snmpWalkUpdateCB); + } + function snmpTestUpdateCB(result) { if (result) { $set("snmpTestMessage", result); @@ -60,29 +103,55 @@ else snmpTestCB(); } - + + function snmpWalkUpdateCB(result) { + if (result) { + $set("snmpWalkMessage", result); + snmpWalkButton(false); + } + else + snmpWalkCB(); + } + function snmpTestButton(testing) { setDisabled($("snmpTestBtn"), testing); } + function snmpWalkButton(testing) { + setDisabled($("snmpWalkBtn"), testing); + } + function initImpl() { versionChange(); + securityLevelChange(); snmpTestButton(false); + toggleTrapSetting(); } - + + function toggleTrapSetting() { + var checkbox = document.getElementById("trapEnabled"); + if(checkbox.checked) { + show("trapSectionPort") + show("trapSectionAddress") + } else { + hide("trapSectionPort") + hide("trapSectionAddress") + } + } + function saveDataSourceImpl() { DataSourceEditDwr.saveSnmpDataSource($get("dataSourceName"), $get("dataSourceXid"), $get("updatePeriods"), $get("updatePeriodType"), $get("host"), $get("port"), $get("snmpVersion"), $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"), $get("privProtocol"), - $get("privPassphrase"), $get("engineId"), $get("contextEngineId"), $get("contextName"), $get("retries"), - $get("timeout"), $get("trapPort"), $get("localAddress"), saveDataSourceCB); + $get("privPassphrase"), $get("securityLevel"), $get("contextName"), $get("retries"), + $get("timeout"), $get("trapEnabled"), $get("trapPort"), $get("localAddress"), saveDataSourceCB); } - + function appendPointListColumnFunctions(pointListColumnHeaders, pointListColumnFunctions) { pointListColumnHeaders[pointListColumnHeaders.length] = ""; pointListColumnFunctions[pointListColumnFunctions.length] = function(p) { return p.pointLocator.oid; }; } - + function editPointCBImpl(locator) { $set("oid", locator.oid); $set("dataTypeId", locator.dataTypeId); @@ -91,19 +160,19 @@ $set("trapOnly", locator.trapOnly ? "true" : "false"); dataTypeChanged(); } - + function savePointImpl(locator) { delete locator.settable; - + locator.oid = $get("oid"); locator.dataTypeId = $get("dataTypeId"); locator.binary0Value = $get("binary0Value"); locator.setType = $get("setType"); locator.trapOnly = $get("trapOnly") == "true"; - + DataSourceEditDwr.saveSnmpPointLocator(currentPoint.id, $get("xid"), $get("name"), locator, savePointCB); } - + function dataTypeChanged() { display("binary0ValueRow", $get("dataTypeId") == ); } @@ -121,17 +190,27 @@ - + - + - + + + + + + + + + + + @@ -142,37 +221,53 @@ - + - + + - + + + + + + + + + + + + MD5 SHA + HMAC128 SHA224 + HMAC192 SHA256 + HMAC256 SHA384 + HMAC384 SHA512 - - + + - - + + @@ -181,72 +276,83 @@ AES128 AES192 AES256 + + 3DES + AES192With3DES + AES256With3DES - - + + - - - - - - - - - - - + - - - - - - - - - - + + + + + + - - - + + + - - - + + + - +
- + - + - + + + + <%@ include file="/WEB-INF/jsp/dataSourceEdit/dsFoot.jspf" %> diff --git a/WebContent/WEB-INF/lib/SNMP4J.jar b/WebContent/WEB-INF/lib/SNMP4J.jar deleted file mode 100644 index 0c6c1b063b..0000000000 Binary files a/WebContent/WEB-INF/lib/SNMP4J.jar and /dev/null differ diff --git a/WebContent/WEB-INF/lib/snmp4j-2.8.6.jar b/WebContent/WEB-INF/lib/snmp4j-2.8.6.jar new file mode 100644 index 0000000000..2f3c6c6cb0 Binary files /dev/null and b/WebContent/WEB-INF/lib/snmp4j-2.8.6.jar differ diff --git a/build.xml b/build.xml index e1cc2a4cf7..c7095889b8 100644 --- a/build.xml +++ b/build.xml @@ -82,7 +82,7 @@ - + diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java index 0f6bc262e4..1de498569a 100644 --- a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java +++ b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java @@ -1,34 +1,23 @@ -/* - Mango - Open Source M2M - http://mango.serotoninsoftware.com - Copyright (C) 2006-2011 Serotonin Software Technologies Inc. - @author Matthew Lohbihler - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ package com.serotonin.mango.rt.dataSource.snmp; import java.io.IOException; -import java.net.InetAddress; import java.util.ArrayList; import java.util.List; +import com.serotonin.mango.vo.dataSource.snmp.SnmpDataSourceVO; +import com.serotonin.mango.vo.dataSource.snmp.SnmpPointLocatorVO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.snmp4j.PDU; import org.snmp4j.Snmp; import org.snmp4j.Target; +import org.snmp4j.event.ResponseEvent; +import org.snmp4j.mp.MPv3; +import org.snmp4j.security.SecurityModels; +import org.snmp4j.security.SecurityProtocols; +import org.snmp4j.security.USM; import org.snmp4j.smi.OID; +import org.snmp4j.smi.OctetString; import org.snmp4j.smi.Variable; import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; @@ -39,271 +28,394 @@ import com.serotonin.mango.rt.dataImage.SetPointSource; import com.serotonin.mango.rt.dataSource.DataSourceRT; import com.serotonin.mango.rt.dataSource.PollingDataSource; -import com.serotonin.mango.vo.dataSource.snmp.SnmpDataSourceVO; -import com.serotonin.mango.vo.dataSource.snmp.SnmpPointLocatorVO; + import com.serotonin.web.i18n.LocalizableMessage; /** * @author Matthew Lohbihler - * + * */ public class SnmpDataSourceRT extends PollingDataSource { - public static final int DATA_SOURCE_EXCEPTION_EVENT = 1; - public static final int PDU_EXCEPTION_EVENT = 2; - - private final Log log = LogFactory.getLog(SnmpDataSourceRT.class); - - private final SnmpDataSourceVO vo; - private final Version version; - private String address; - private Target target; - private Snmp snmp; - - public SnmpDataSourceRT(SnmpDataSourceVO vo) { - super(vo); - setPollingPeriod(vo.getUpdatePeriodType(), vo.getUpdatePeriods(), false); - this.vo = vo; - version = Version.getVersion(vo.getSnmpVersion(), vo.getCommunity(), - vo.getSecurityName(), vo.getAuthProtocol(), - vo.getAuthPassphrase(), vo.getPrivProtocol(), - vo.getPrivPassphrase(), vo.getEngineId(), - vo.getContextEngineId(), vo.getContextName()); - } - - @Override - public void setPointValue(DataPointRT dataPoint, PointValueTime valueTime, - SetPointSource source) { - PDU request = version.createPDU(); - SnmpPointLocatorRT locator = dataPoint.getPointLocator(); - request.add(new VariableBinding(getOid(dataPoint), locator - .valueToVariable(valueTime.getValue()))); - PDU response; - try { - response = snmp.set(request, target).getResponse(); - } catch (Exception ex) { - // TODO add error handling - response = null; - } - - LocalizableMessage message = validatePdu(response); - if (message != null) - raiseEvent(PDU_EXCEPTION_EVENT, valueTime.getTime(), false, message); - else - dataPoint.setPointValue(valueTime, source); - } - - @Override - protected void doPoll(long time) { - try { - doPollImpl(time); - } catch (Exception e) { - raiseEvent(PDU_EXCEPTION_EVENT, time, true, - DataSourceRT.getExceptionMessage(e)); - } - } - - private void doPollImpl(long time) throws IOException { - PDU request = version.createPDU(); - PDU response = null; - VariableBinding vb; - - // Make a copy of the oids so that we can check if we got everything we - // asked for, and - // only what we asked for. - List requestPoints = new ArrayList(); - - // Add OID to send in the PDU. - for (DataPointRT dp : dataPoints) { - if (!getLocatorVO(dp).isTrapOnly()) { - request.add(new VariableBinding(getOid(dp))); - requestPoints.add(dp); - } - } - - if (request.getVariableBindings().size() == 0) { - // Nothing to send, so don't bother. - returnToNormal(PDU_EXCEPTION_EVENT, time); - return; - } - - // Get the response. - long responseTime = System.currentTimeMillis(); - response = snmp.get(request, target).getResponse(); - responseTime = System.currentTimeMillis() - responseTime; - log.debug("Snmp request/response time: " + responseTime); - - // Take a look at the response. - LocalizableMessage message = validatePdu(response); - if (message != null) - raiseEvent(PDU_EXCEPTION_EVENT, time, true, message); - else { - boolean error = false; - - DataPointRT dp; - for (int i = 0; i < response.size(); i++) { - vb = response.get(i); - - // Find the command for this binding. - dp = null; - for (DataPointRT requestPoint : requestPoints) { - if (getOid(requestPoint).equals(vb.getOid())) { - dp = requestPoint; - break; - } - } - - if (dp != null) { - requestPoints.remove(dp); - - // Check if this is an error. - Variable variable = vb.getVariable(); - if (vb.getVariable().isException()) { - error = true; - raiseEvent( - PDU_EXCEPTION_EVENT, - time, - true, - new LocalizableMessage("event.snmp.oidError", - address, getOid(dp), variable - .toString())); - } else - updatePoint(dp, variable, time); - } else { - error = true; - raiseEvent( - PDU_EXCEPTION_EVENT, - time, - true, - new LocalizableMessage("event.snmp.unknownOid", vb - .getOid(), address)); - } - } - - for (DataPointRT requestPoint : requestPoints) { - error = true; - raiseEvent(PDU_EXCEPTION_EVENT, time, true, - new LocalizableMessage("event.snmp.noBinding", - getOid(requestPoint), address)); - } - - if (!error) - // Deactivate any existing event. - returnToNormal(PDU_EXCEPTION_EVENT, time); - } - } - - private LocalizableMessage validatePdu(PDU pdu) { - if (pdu == null) - return new LocalizableMessage("event.snmp.noResponse"); - - if (pdu.getErrorIndex() != 0) - return new LocalizableMessage("event.snmp.pduOidError", pdu.get( - pdu.getErrorIndex() - 1).getOid(), pdu.getErrorStatusText()); - - if (pdu.getErrorStatus() != 0) - return new LocalizableMessage("event.snmp.pduErrorStatus", - pdu.getErrorStatus(), pdu.getErrorStatusText()); - - return null; - } - - private OID getOid(DataPointRT dp) { - return ((SnmpPointLocatorRT) dp.getPointLocator()).getOid(); - } - - private SnmpPointLocatorVO getLocatorVO(DataPointRT dp) { - return ((SnmpPointLocatorRT) dp.getPointLocator()).getVO(); - } - - int getTrapPort() { - return vo.getTrapPort(); - } - - String getLocalAddress() { - return vo.getLocalAddress(); - } - - String getAddress() { - return address; - } - - void receivedTrap(PDU trap) { - long time = System.currentTimeMillis(); - VariableBinding vb; - - // Take a look at the response. - LocalizableMessage message = validatePdu(trap); - if (message != null) - raiseEvent(PDU_EXCEPTION_EVENT, time, false, message); - else { - synchronized (pointListChangeLock) { - updateChangedPoints(); - - for (int i = 0; i < trap.size(); i++) { - vb = trap.get(i); - boolean found = false; - - // Find the command for this binding. - for (DataPointRT dp : dataPoints) { - if (getOid(dp).equals(vb.getOid())) { - updatePoint(dp, vb.getVariable(), time); - found = true; - } - } - - if (!found) - log.warn("Trap not handled: " + vb); - } - } - } - } - - private void updatePoint(DataPointRT dp, Variable variable, long time) { - SnmpPointLocatorRT locator = dp.getPointLocator(); - dp.updatePointValue(new PointValueTime(locator - .variableToValue(variable), time)); - } - - // - // / - // / Lifecycle - // / - // - @Override - public void initialize() { - try { - address = InetAddress.getByName(vo.getHost()).getHostAddress(); - target = version.getTarget(vo.getHost(), vo.getPort(), - vo.getRetries(), vo.getTimeout()); - snmp = new Snmp(new DefaultUdpTransportMapping()); - snmp.listen(); - - SnmpTrapRouter.addDataSource(this); - - // Deactivate any existing event. - returnToNormal(DATA_SOURCE_EXCEPTION_EVENT, - System.currentTimeMillis()); - } catch (Exception e) { - raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), - true, DataSourceRT.getExceptionMessage(e)); - log.debug("Error while initializing data source", e); - return; - } - - super.initialize(); - } - - @Override - public void terminate() { - super.terminate(); - - SnmpTrapRouter.removeDataSource(this); - - try { - if (snmp != null) - snmp.close(); - } catch (IOException e) { - throw new ShouldNeverHappenException(e); - } - } -} + + enum MessageType{ + oidError, + unknownOid, + undefined + + } + class SnmpResponses { + PDU request = null; + PDU response = null; + long responseTime; + + SnmpResponses(){} + + public void setRequest(PDU request){ + + this.request = request; + } + public PDU getRequest(){ + + return this.request; + } + public PDU getResponseByGet() { + + try { + startTime(); + response = getResponse(true); + finishTime(); + } catch (IOException e) { + e.printStackTrace(); + } + return response; + } + public PDU getResponseBySet(){ + PDU response = null; + try { + startTime(); + response = getResponse(false); + finishTime(); + } catch (Exception ex) { + // TODO add error handling + response = null; + } + return response; + } + private PDU getResponse(boolean setOrGet) throws IOException { + + return setOrGet?snmp.get(request, target).getResponse():snmp.set(request, target).getResponse(); + + } + private void startTime(){ + + responseTime = System.currentTimeMillis(); + + } + private void finishTime(){ + + responseTime = System.currentTimeMillis() - responseTime; + log.debug("Snmp request/response time: " + responseTime); + + } + } + + public static final int DATA_SOURCE_EXCEPTION_EVENT = 1; + public static final int PDU_EXCEPTION_EVENT = 2; + public static final int TRAP_NOT_HANDLED_EVENT = 3; + + private final Log log = LogFactory.getLog(SnmpDataSourceRT.class); + + private final SnmpDataSourceVO vo; + private final Version version; + private String address; + private Target target; + private Snmp snmp; + private int counterEmptyResponsesOrResponsesWithError; + private boolean deviceDidNotRespondDespiteTheCounterOfRetries = Boolean.FALSE; + private SnmpResponses snmpRequests; + + public Snmp getSnmp() { + return snmp; + } + + public SnmpDataSourceRT(SnmpDataSourceVO vo) { + super(vo); + setPollingPeriod(vo.getUpdatePeriodType(), vo.getUpdatePeriods(), false); + this.vo = vo; + version = Version.getVersion(vo.getSnmpVersion(), vo.getCommunity(), + vo.getSecurityName(), vo.getAuthProtocol(), + vo.getAuthPassphrase(), vo.getPrivProtocol(), + vo.getPrivPassphrase(), vo.getSecurityLevel(), + vo.getContextName()); + snmpRequests = new SnmpResponses(); + } + + @Override + public void setPointValue(DataPointRT dataPoint, PointValueTime valueTime, + SetPointSource source) { + PDU request = version.createPDU(); + SnmpPointLocatorRT locator = dataPoint.getPointLocator(); + request.add(new VariableBinding(getOid(dataPoint), locator + .valueToVariable(valueTime.getValue()))); + snmpRequests.setRequest(request); + PDU response = snmpRequests.getResponseBySet(); + + LocalizableMessage message = validatePdu(response); + if (message != null) + raiseEvent(PDU_EXCEPTION_EVENT, valueTime.getTime(), false, message); + else + dataPoint.setPointValue(valueTime, source); + } + public void setDeviceDidNotRespondDespiteTheCounterOfRetries(boolean deviceDidNotRespondDespiteTheCounterOfRetries) { + this.deviceDidNotRespondDespiteTheCounterOfRetries = deviceDidNotRespondDespiteTheCounterOfRetries; + log.info("Device did not respond despite the counter of retries."); + } + public void createSnmpAndStartListening(){ + try { + initializeComponents(); + + } catch (Exception e) { + log.info(e.getMessage()); + } + } + public boolean isSnmpConnectionIsAlive(){ + if (target.getRetries() == counterEmptyResponsesOrResponsesWithError) { + setDeviceDidNotRespondDespiteTheCounterOfRetries(Boolean.TRUE); + return Boolean.FALSE; + } + else + return Boolean.TRUE; + + } + + @Override + protected void doPoll(long time) { + try { + doPollImpl(time); + } catch (Exception e) { + raiseEvent(PDU_EXCEPTION_EVENT, time, true, + DataSourceRT.getExceptionMessage(e)); + } + } + + private void doPollImpl(long time) throws IOException { + snmpRequests.setRequest(version.createPDU()); + PDU request = snmpRequests.getRequest(); + PDU response = null; + request.setType(PDU.GET); + + VariableBinding vb; + + // Make a copy of the oids so that we can check if we got everything we + // asked for, and + // only what we asked for. + List requestPoints = new ArrayList(); + + // Add OID to send in the PDU. + for (DataPointRT dp : dataPoints) { + if (!getLocatorVO(dp).isTrapOnly()) { + request.add(new VariableBinding(getOid(dp))); + requestPoints.add(dp); + } + } + + ResponseEvent event = snmp.send(request, target); + if(event != null) { + response = event.getResponse(); + LocalizableMessage message = validateResponseAndValidateStateOfConnection(response); + if (time == -1) { + if (!isSnmpConnectionIsAlive()) { + snmp.close(); + } + } else { + if (!isSnmpConnectionIsAlive()) { +// Common.ctx.getRuntimeManager().stopDataSourceAndDontJoinTermination(vo.getId()); + } else if (message != null) { + raiseEvent(PDU_EXCEPTION_EVENT, time, true, message); + } + } + if (response.getErrorStatus() == PDU.noError) { + DataPointRT dp; + for (int i = 0; i < response.size(); i++) { + vb = response.get(i); + dp = setDataPoint(vb,requestPoints); + if (dp != null) { + requestPoints.remove(dp); + updatePoint(dp, vb.getVariable(), time); + } + } + } else { + raiseEvent(PDU_EXCEPTION_EVENT, time, true, validatePdu(response)); + + } + } + + } + private DataPointRT setDataPoint(VariableBinding vb, List requestPoints){ + for (DataPointRT requestPoint : requestPoints) { + if (getOid(requestPoint).equals(vb.getOid())) { + return requestPoint; + } + } + return null; + } + public LocalizableMessage validateResponseAndValidateStateOfConnection(PDU response){ + LocalizableMessage message = validatePdu(response); + + increaseCounterIfErrorExistOrNoResponseAppear(response); + + return message; + } + + /** + * if messageType is different that value 0 or 1 + * then LocalizableMessage is created and is gived to raiseEvent method. + * Then result of this is true,otherwise (messageType == -1) is false. + * + * @param messageType + * @param vb + * @param dp + * @param time + * @return boolean + */ + private boolean logEventsDependsOnMessageType(MessageType messageType, VariableBinding vb, DataPointRT dp, long time){ + LocalizableMessage message=null; + switch(messageType) { + case oidError: + message=new LocalizableMessage( + "event.snmp.oidError", + address, getOid(dp), vb.getVariable()); + break; + case unknownOid: + message=new LocalizableMessage( + "event.snmp.unknownOid", + vb.getOid(), address); + break; + } + + if(messageType!=MessageType.undefined) + raiseEvent(PDU_EXCEPTION_EVENT,time,true,message); + + return messageType!=MessageType.undefined; + } + private LocalizableMessage validatePdu(PDU pdu) { + if (pdu == null) + return new LocalizableMessage("event.snmp.noResponse"); + + if (pdu.getErrorIndex() != 0) + return new LocalizableMessage("event.snmp.pduOidError", pdu.get( + pdu.getErrorIndex() - 1).getOid(), pdu.getErrorStatusText()); + + if (pdu.getErrorStatus() != 0) + return new LocalizableMessage("event.snmp.pduErrorStatus", + pdu.getErrorStatus(), pdu.getErrorStatusText()); + + return null; + } + + private void increaseCounterIfErrorExistOrNoResponseAppear(PDU pdu) { + if ((pdu == null) || (pdu.getErrorIndex() != 0) || (pdu.getErrorStatus() != 0)) { + ++counterEmptyResponsesOrResponsesWithError; + log.info("Counter Empty Responses Or Responses With Error: "+counterEmptyResponsesOrResponsesWithError); + } + } + + + + private OID getOid(DataPointRT dp) { + return ((SnmpPointLocatorRT) dp.getPointLocator()).getOid(); + } + + private SnmpPointLocatorVO getLocatorVO(DataPointRT dp) { + return ((SnmpPointLocatorRT) dp.getPointLocator()).getVO(); + } + + int getTrapPort() { + return vo.getTrapPort(); + } + + boolean isTrapEnabled() { + return vo.isTrapEnabled(); + } + + String getLocalAddress() { + return vo.getLocalAddress(); + } + + String getAddress() { + return address; + } + + Version getVersion() { return this.version; } + + void receivedTrap(PDU trap) { + long time = System.currentTimeMillis(); + VariableBinding vb; + + // Take a look at the response. + LocalizableMessage message = validatePdu(trap); + if (message != null) + raiseEvent(PDU_EXCEPTION_EVENT, time, false, message); + else { + synchronized (pointListChangeLock) { + updateChangedPoints(); + + for (int i = 0; i < trap.getVariableBindings().size(); i++) { + vb = trap.get(i); + boolean found = false; + + // Find the command for this binding. + for (DataPointRT dp : dataPoints) { + if (getOid(dp).equals(vb.getOid())) { + updatePoint(dp, vb.getVariable(), time); + found = true; + } + } + + if (!found) + raiseEvent(TRAP_NOT_HANDLED_EVENT, time, false, new LocalizableMessage("event.snmp.trapNotHandled", vb)); + log.warn("Trap not handled: " + vb); + } + } + } + } + + private void updatePoint(DataPointRT dp, Variable variable, long time) { + SnmpPointLocatorRT locator = dp.getPointLocator(); + dp.updatePointValue(new PointValueTime(locator + .variableToValue(variable), time)); + } + + // + // / + // / Lifecycle + // / + // + @Override + public void initialize() { + try { + initializeComponents(); + counterEmptyResponsesOrResponsesWithError=0; + log.info("Counter Empty Responses Or Responses With Error is set 0."); + + SnmpTrapRouter.addDataSource(this); + + // Deactivate any existing event. + returnToNormal(DATA_SOURCE_EXCEPTION_EVENT, + System.currentTimeMillis()); + } catch (Exception e) { + raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), + true, DataSourceRT.getExceptionMessage(e)); + log.debug("Error while initializing data source", e); + return; + } + + super.initialize(); + } + private void initializeComponents() throws IOException { + snmp = new Snmp(new DefaultUdpTransportMapping()); + + OctetString localEngineId = new OctetString(MPv3.createLocalEngineID()).substring(0,9); + USM usm = new USM(SecurityProtocols.getInstance(), localEngineId, 0); + SecurityModels.getInstance().addSecurityModel(usm); + + version.addUser(snmp); + target = version.getTarget(vo.getHost(), vo.getPort(), vo.getRetries(), vo.getTimeout()); + + snmp.listen(); + + } + @Override + public void terminate() { + super.terminate(); + + SnmpTrapRouter.removeDataSource(this); + + try { + if (snmp != null) + snmp.close(); + } catch (IOException e) { + throw new ShouldNeverHappenException(e); + } + } +} \ No newline at end of file diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java index 1ab9a64316..42e9179d40 100644 --- a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java +++ b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java @@ -2,7 +2,7 @@ Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler - + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or @@ -44,7 +44,7 @@ /** * @author Matthew Lohbihler - * + * */ public class SnmpPointLocatorRT extends PointLocatorRT { private static final Log LOG = LogFactory.getLog(SnmpPointLocatorRT.class); @@ -72,25 +72,25 @@ public SnmpPointLocatorVO getVO() { public MangoValue variableToValue(Variable variable) { switch (vo.getDataTypeId()) { - case DataTypes.BINARY: - return new BinaryValue(StringUtils.isEqual(variable.toString(), vo.getBinary0Value())); - - case DataTypes.MULTISTATE: - return new MultistateValue(variable.toInt()); - - case DataTypes.NUMERIC: - if (variable instanceof OctetString) { - try { - return NumericValue.parseNumeric(variable.toString()); - } - catch (NumberFormatException e) { - // no op + case DataTypes.BINARY: + return new BinaryValue(StringUtils.isEqual(variable.toString(), vo.getBinary0Value())); + + case DataTypes.MULTISTATE: + return new MultistateValue(variable.toInt()); + + case DataTypes.NUMERIC: + if (variable instanceof OctetString) { + try { + return NumericValue.parseNumeric(variable.toString()); + } + catch (NumberFormatException e) { + // no op + } } - } - return new NumericValue(variable.toInt()); + return new NumericValue(variable.toInt()); - case DataTypes.ALPHANUMERIC: - return new AlphanumericValue(variable.toString()); + case DataTypes.ALPHANUMERIC: + return new AlphanumericValue(variable.toString()); } @@ -103,40 +103,40 @@ public Variable valueToVariable(MangoValue value) { public static Variable valueToVariableImpl(MangoValue value, int setType) { switch (setType) { - case SnmpPointLocatorVO.SetTypes.INTEGER_32: - if (value instanceof NumericValue) - return new Integer32(value.getIntegerValue()); - if (value instanceof BinaryValue) - return new Integer32(value.getBooleanValue() ? 1 : 0); + case SnmpPointLocatorVO.SetTypes.INTEGER_32: + if (value instanceof NumericValue) + return new Integer32(value.getIntegerValue()); + if (value instanceof BinaryValue) + return new Integer32(value.getBooleanValue() ? 1 : 0); - LOG.warn("Can't convert value '" + value + "' (" + value.getDataType() + ") to Integer32"); - return new Integer32(0); + LOG.warn("Can't convert value '" + value + "' (" + value.getDataType() + ") to Integer32"); + return new Integer32(0); - case SnmpPointLocatorVO.SetTypes.OCTET_STRING: - return new OctetString(DataTypes.valueToString(value)); + case SnmpPointLocatorVO.SetTypes.OCTET_STRING: + return new OctetString(DataTypes.valueToString(value)); - case SnmpPointLocatorVO.SetTypes.OID: - return new OID(DataTypes.valueToString(value)); + case SnmpPointLocatorVO.SetTypes.OID: + return new OID(DataTypes.valueToString(value)); - case SnmpPointLocatorVO.SetTypes.IP_ADDRESS: - return new IpAddress(DataTypes.valueToString(value)); + case SnmpPointLocatorVO.SetTypes.IP_ADDRESS: + return new IpAddress(DataTypes.valueToString(value)); - case SnmpPointLocatorVO.SetTypes.COUNTER_32: - return new Counter32((long) value.getDoubleValue()); + case SnmpPointLocatorVO.SetTypes.COUNTER_32: + return new Counter32((long) value.getDoubleValue()); - case SnmpPointLocatorVO.SetTypes.GAUGE_32: - return new Gauge32((long) value.getDoubleValue()); + case SnmpPointLocatorVO.SetTypes.GAUGE_32: + return new Gauge32((long) value.getDoubleValue()); - case SnmpPointLocatorVO.SetTypes.TIME_TICKS: - return new TimeTicks((long) value.getDoubleValue()); + case SnmpPointLocatorVO.SetTypes.TIME_TICKS: + return new TimeTicks((long) value.getDoubleValue()); - case SnmpPointLocatorVO.SetTypes.OPAQUE: - return new Opaque(DataTypes.valueToString(value).getBytes()); + case SnmpPointLocatorVO.SetTypes.OPAQUE: + return new Opaque(DataTypes.valueToString(value).getBytes()); - case SnmpPointLocatorVO.SetTypes.COUNTER_64: - return new Counter64((long) value.getDoubleValue()); + case SnmpPointLocatorVO.SetTypes.COUNTER_64: + return new Counter64((long) value.getDoubleValue()); } throw new ShouldNeverHappenException("Unknown set type id: " + setType); } -} +} \ No newline at end of file diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java index e0911e43e4..8ed323951d 100644 --- a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java +++ b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java @@ -25,7 +25,6 @@ import org.snmp4j.CommandResponder; import org.snmp4j.CommandResponderEvent; import org.snmp4j.PDU; -import org.snmp4j.PDUv1; import org.snmp4j.Snmp; import org.snmp4j.mp.CounterSupport; import org.snmp4j.mp.DefaultCounterListener; @@ -33,7 +32,6 @@ import org.snmp4j.transport.DefaultUdpTransportMapping; import com.serotonin.ShouldNeverHappenException; -import com.serotonin.util.StringUtils; /** * @author Matthew Lohbihler @@ -42,11 +40,13 @@ public class SnmpTrapRouter { private static SnmpTrapRouter instance; public synchronized static void addDataSource(SnmpDataSourceRT ds) throws IOException { - if (instance == null) { - CounterSupport.getInstance().addCounterListener(new DefaultCounterListener()); - instance = new SnmpTrapRouter(); + if(ds.isTrapEnabled()) { + if (instance == null) { + CounterSupport.getInstance().addCounterListener(new DefaultCounterListener()); + instance = new SnmpTrapRouter(); + } + instance.addDataSourceImpl(ds); } - instance.addDataSourceImpl(ds); } public synchronized static void removeDataSource(SnmpDataSourceRT ds) { @@ -59,7 +59,9 @@ public synchronized static void removeDataSource(SnmpDataSourceRT ds) { private void addDataSourceImpl(SnmpDataSourceRT ds) throws IOException { PortListener l = getPortListener(ds.getTrapPort()); if (l == null) { - l = new PortListener(ds.getTrapPort()); + String localAddress = ds.getLocalAddress() != null && !ds.getLocalAddress().isEmpty() + ? ds.getLocalAddress() : "0.0.0.0"; + l = new PortListener(ds.getTrapPort(), localAddress); portListeners.add(l); } l.addDataSource(ds); @@ -89,10 +91,10 @@ private class PortListener implements CommandResponder { final int port; final List dataSources = new LinkedList(); - PortListener(int port) throws IOException { + PortListener(int port, String localAddress) throws IOException { this.port = port; - snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress("0.0.0.0/" + port))); + snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress(localAddress + "/" + port))); snmp.addCommandResponder(this); snmp.listen(); } @@ -100,22 +102,10 @@ private class PortListener implements CommandResponder { public synchronized void processPdu(CommandResponderEvent evt) { PDU command = evt.getPDU(); if (command != null) { - // Get the peer address - String peer = evt.getPeerAddress().toString(); - int slash = peer.indexOf('/'); - if (slash > 0) - peer = peer.substring(0, slash); - - String localAddress = ""; - if (command instanceof PDUv1) - localAddress = ((PDUv1) command).getAgentAddress().toString(); // Look for the peer in the data source list. for (SnmpDataSourceRT ds : dataSources) { - if (ds.getAddress().equals(peer)) { - if (StringUtils.isEmpty(ds.getLocalAddress()) || localAddress.equals(ds.getLocalAddress())) - ds.receivedTrap(command); - } + ds.receivedTrap(command); } } } diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/Version.java b/src/com/serotonin/mango/rt/dataSource/snmp/Version.java index 89c679199b..a821181193 100644 --- a/src/com/serotonin/mango/rt/dataSource/snmp/Version.java +++ b/src/com/serotonin/mango/rt/dataSource/snmp/Version.java @@ -34,15 +34,14 @@ */ abstract public class Version { public static Version getVersion(int version, String community, String securityName, String authProtocol, - String authPassphrase, String privProtocol, String privPassphrase, String engineId, String contextEngineId, + String authPassphrase, String privProtocol, String privPassphrase, int securityLevel, String contextName) { if (version == SnmpConstants.version1) return new Version1(community); else if (version == SnmpConstants.version2c) return new Version2c(community); else if (version == SnmpConstants.version3) - return new Version3(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase, engineId, - contextEngineId, contextName); + return new Version3(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase, securityLevel, contextName); else throw new IllegalArgumentException("Invalid version value: " + version); } @@ -59,6 +58,7 @@ public Target getTarget(String host, int port, int retries, int timeout) throws Target target = getTarget(); Address address = new UdpAddress(InetAddress.getByName(host), port); + target.setVersion(getVersionId()); target.setAddress(address); target.setRetries(retries); target.setTimeout(timeout); diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java b/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java index c2bccb13dd..5891f4c4b7 100644 --- a/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java +++ b/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java @@ -1,21 +1,3 @@ -/* - Mango - Open Source M2M - http://mango.serotoninsoftware.com - Copyright (C) 2006-2011 Serotonin Software Technologies Inc. - @author Matthew Lohbihler - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ package com.serotonin.mango.rt.dataSource.snmp; import org.snmp4j.PDU; @@ -23,19 +5,10 @@ import org.snmp4j.Snmp; import org.snmp4j.Target; import org.snmp4j.UserTarget; -import org.snmp4j.mp.MPv3; import org.snmp4j.mp.SnmpConstants; -import org.snmp4j.security.AuthMD5; -import org.snmp4j.security.AuthSHA; -import org.snmp4j.security.PrivAES128; -import org.snmp4j.security.PrivAES192; -import org.snmp4j.security.PrivAES256; -import org.snmp4j.security.PrivDES; -import org.snmp4j.security.SecurityLevel; -import org.snmp4j.security.SecurityModels; -import org.snmp4j.security.SecurityProtocols; -import org.snmp4j.security.USM; -import org.snmp4j.security.UsmUser; +import org.snmp4j.security.*; +import org.snmp4j.security.nonstandard.PrivAES192With3DESKeyExtension; +import org.snmp4j.security.nonstandard.PrivAES256With3DESKeyExtension; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; @@ -43,32 +16,42 @@ /** * @author Matthew Lohbihler - * + * */ public class Version3 extends Version { + + private final int securityLevel; + private final OctetString contextName; private final OctetString securityName; private OID authProtocol; private final OctetString authPassphrase; private OID privProtocol; private final OctetString privPassphrase; - private final OctetString engineId; - private final OctetString contextEngineId; - private final OctetString contextName; public Version3(String securityName, String authProtocol, String authPassphrase, String privProtocol, - String privPassphrase, String engineId, String contextEngineId, String contextName) { - this.securityName = SnmpUtils.createOctetString(securityName); + String privPassphrase, int securityLevel, String contextName) { + + this.securityName = new OctetString(securityName); + this.securityLevel = securityLevel; if (!StringUtils.isEmpty(authProtocol)) { if (authProtocol.equals("MD5")) this.authProtocol = AuthMD5.ID; else if (authProtocol.equals("SHA")) this.authProtocol = AuthSHA.ID; + else if (authProtocol.equals("HMAC128SHA224")) + this.authProtocol = AuthHMAC128SHA224.ID; + else if (authProtocol.equals("HMAC192SHA256")) + this.authProtocol = AuthHMAC192SHA256.ID; + else if (authProtocol.equals("HMAC256SHA384")) + this.authProtocol = AuthHMAC256SHA384.ID; + else if (authProtocol.equals("HMAC384SHA512")) + this.authProtocol = AuthHMAC384SHA512.ID; else throw new IllegalArgumentException("Authentication protocol unsupported: " + authProtocol); } - this.authPassphrase = SnmpUtils.createOctetString(authPassphrase); + this.authPassphrase = new OctetString(authPassphrase); if (!StringUtils.isEmpty(privProtocol)) { if (privProtocol.equals("DES")) @@ -79,14 +62,18 @@ else if (privProtocol.equals("AES192")) this.privProtocol = PrivAES192.ID; else if (privProtocol.equals("AES256")) this.privProtocol = PrivAES256.ID; + else if (privProtocol.equals("3DES")) + this.privProtocol = Priv3DES.ID; + else if (privProtocol.equals("AES192With3DES")) + this.privProtocol = PrivAES192With3DESKeyExtension.ID; + else if (privProtocol.equals("AES256With3DES")) + this.privProtocol = PrivAES256With3DESKeyExtension.ID; else throw new IllegalArgumentException("Privacy protocol " + privProtocol + " not supported"); } - this.privPassphrase = SnmpUtils.createOctetString(privPassphrase); - this.engineId = SnmpUtils.createOctetString(engineId); - this.contextEngineId = SnmpUtils.createOctetString(contextEngineId); - this.contextName = SnmpUtils.createOctetString(contextName); + this.privPassphrase = new OctetString(privPassphrase); + this.contextName = new OctetString(contextName); } @Override @@ -96,10 +83,6 @@ public int getVersionId() { @Override public void addUser(Snmp snmp) { - USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); - SecurityModels.getInstance().addSecurityModel(usm); - if (engineId != null) - snmp.setLocalEngine(engineId.getValue(), 0, 0); snmp.getUSM().addUser(securityName, new UsmUser(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase)); } @@ -107,15 +90,7 @@ public void addUser(Snmp snmp) { @Override public Target getTarget() { UserTarget target = new UserTarget(); - if (authPassphrase != null) { - if (privPassphrase != null) - target.setSecurityLevel(SecurityLevel.AUTH_PRIV); - else - target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV); - } - else - target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV); - + target.setSecurityLevel(securityLevel); target.setSecurityName(securityName); return target; } @@ -123,10 +98,9 @@ public Target getTarget() { @Override public PDU createPDU() { ScopedPDU scopedPDU = new ScopedPDU(); - if (contextEngineId != null) - scopedPDU.setContextEngineID(contextEngineId); if (contextName != null) scopedPDU.setContextName(contextName); return scopedPDU; } -} + +} \ No newline at end of file diff --git a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java index bb5d45fd1d..c837174aba 100644 --- a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java +++ b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java @@ -2,7 +2,7 @@ Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler - + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or @@ -47,7 +47,7 @@ /** * @author Matthew Lohbihler - * + * */ @JsonRemoteEntity public class SnmpDataSourceVO extends DataSourceVO { @@ -57,6 +57,10 @@ public interface AuthProtocols { String NONE = ""; String MD5 = "MD5"; String SHA = "SHA"; + String HMAC128SHA224 = "HMAC128SHA224"; + String HMAC192SHA256 = "HMAC192SHA256"; + String HMAC256SHA384 = "HMAC256SHA384"; + String HMAC384SHA512 = "HMAC384SHA512"; } public interface PrivProtocols { @@ -65,6 +69,9 @@ public interface PrivProtocols { String AES128 = "AES128"; String AES192 = "AES192"; String AES256 = "AES256"; + String DES3 = "3DES"; + String AES192With3DES = "AES192With3DES"; + String AES256With3DES = "AES256With3DES"; } @Override @@ -130,6 +137,8 @@ public SnmpPointLocatorVO createPointLocator() { @JsonRemoteProperty private String privPassphrase; @JsonRemoteProperty + private int securityLevel; + @JsonRemoteProperty private int retries = 2; @JsonRemoteProperty private int timeout = 1000; @@ -137,6 +146,8 @@ public SnmpPointLocatorVO createPointLocator() { @JsonRemoteProperty private int updatePeriods = 5; @JsonRemoteProperty + private boolean trapEnabled; + @JsonRemoteProperty private int trapPort = SnmpConstants.DEFAULT_NOTIFICATION_RECEIVER_PORT; @JsonRemoteProperty private String localAddress; @@ -165,14 +176,6 @@ public void setCommunity(String community) { this.community = community; } - public String getContextEngineId() { - return contextEngineId; - } - - public void setContextEngineId(String contextEngineId) { - this.contextEngineId = contextEngineId; - } - public String getContextName() { return contextName; } @@ -181,14 +184,6 @@ public void setContextName(String contextName) { this.contextName = contextName; } - public String getEngineId() { - return engineId; - } - - public void setEngineId(String engineId) { - this.engineId = engineId; - } - public String getHost() { return host; } @@ -269,6 +264,14 @@ public void setTimeout(int timeout) { this.timeout = timeout; } + public boolean isTrapEnabled() { + return trapEnabled; + } + + public void setTrapEnabled(boolean trapEnabled) { + this.trapEnabled = trapEnabled; + } + public int getTrapPort() { return trapPort; } @@ -285,6 +288,14 @@ public void setLocalAddress(String localAddress) { this.localAddress = localAddress; } + public int getSecurityLevel() { + return securityLevel; + } + + public void setSecurityLevel(int securityLevel) { + this.securityLevel = securityLevel; + } + @Override public void validate(DwrResponseI18n response) { super.validate(response); @@ -330,11 +341,11 @@ protected void addPropertiesImpl(List list) { AuditEventType.addPropertyMessage(list, "dsEdit.snmp.authPassphrase", authPassphrase); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.privProtocol", privProtocol); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.privPassphrase", privPassphrase); - AuditEventType.addPropertyMessage(list, "dsEdit.snmp.engineId", engineId); - AuditEventType.addPropertyMessage(list, "dsEdit.snmp.contextEngine", contextEngineId); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.contextName", contextName); + AuditEventType.addPropertyMessage(list, "dsEdit.snmp.sl.label", securityLevel); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.retries", retries); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.timeout", timeout); + AuditEventType.addPropertyMessage(list, "dsEdit.snmp.trapEnabled", trapEnabled); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.trapPort", trapPort); AuditEventType.addPropertyMessage(list, "dsEdit.snmp.localAddress", localAddress); } @@ -354,12 +365,11 @@ protected void addPropertyChangesImpl(List list, SnmpDataSou AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.privProtocol", from.privProtocol, privProtocol); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.privPassphrase", from.privPassphrase, privPassphrase); - AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.engineId", from.engineId, engineId); - AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.contextEngine", from.contextEngineId, - contextEngineId); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.contextName", from.contextName, contextName); + AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.sl.label", from.securityLevel, securityLevel); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.retries", from.retries, retries); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.timeout", from.timeout, timeout); + AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.trapEnabled", from.trapEnabled, trapEnabled); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.trapPort", from.trapPort, trapPort); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.localAddress", from.localAddress, localAddress); } @@ -370,7 +380,7 @@ protected void addPropertyChangesImpl(List list, SnmpDataSou // / // private static final long serialVersionUID = -1; - private static final int version = 2; + private static final int version = 3; private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(version); @@ -378,18 +388,18 @@ private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(port); out.writeInt(snmpVersion); SerializationHelper.writeSafeUTF(out, community); - SerializationHelper.writeSafeUTF(out, engineId); - SerializationHelper.writeSafeUTF(out, contextEngineId); SerializationHelper.writeSafeUTF(out, contextName); SerializationHelper.writeSafeUTF(out, securityName); SerializationHelper.writeSafeUTF(out, authProtocol); SerializationHelper.writeSafeUTF(out, authPassphrase); SerializationHelper.writeSafeUTF(out, privProtocol); SerializationHelper.writeSafeUTF(out, privPassphrase); + out.writeInt(securityLevel); out.writeInt(retries); out.writeInt(timeout); out.writeInt(updatePeriodType); out.writeInt(updatePeriods); + out.writeBoolean(trapEnabled); out.writeInt(trapPort); SerializationHelper.writeSafeUTF(out, localAddress); } @@ -437,6 +447,25 @@ else if (ver == 2) { updatePeriods = in.readInt(); trapPort = in.readInt(); localAddress = SerializationHelper.readSafeUTF(in); + } else if (ver == 3) { + host = SerializationHelper.readSafeUTF(in); + port = in.readInt(); + snmpVersion = in.readInt(); + community = SerializationHelper.readSafeUTF(in); + contextName = SerializationHelper.readSafeUTF(in); + securityName = SerializationHelper.readSafeUTF(in); + authProtocol = SerializationHelper.readSafeUTF(in); + authPassphrase = SerializationHelper.readSafeUTF(in); + privProtocol = SerializationHelper.readSafeUTF(in); + privPassphrase = SerializationHelper.readSafeUTF(in); + securityLevel = in.readInt(); + retries = in.readInt(); + timeout = in.readInt(); + updatePeriodType = in.readInt(); + updatePeriods = in.readInt(); + trapEnabled = in.readBoolean(); + trapPort = in.readInt(); + localAddress = SerializationHelper.readSafeUTF(in); } } @@ -453,4 +482,4 @@ public void jsonSerialize(Map map) { super.jsonSerialize(map); serializeUpdatePeriodType(map, updatePeriodType); } -} +} \ No newline at end of file diff --git a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java index 8c0c07871f..ae5fd91920 100644 --- a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java +++ b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java @@ -2,7 +2,7 @@ Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler - + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or @@ -44,7 +44,7 @@ /** * @author Matthew Lohbihler - * + * */ @JsonRemoteEntity public class SnmpPointLocatorVO extends AbstractPointLocatorVO implements JsonSerializable { @@ -214,4 +214,4 @@ public void jsonDeserialize(JsonReader reader, JsonObject json) throws JsonExcep public void jsonSerialize(Map map) { serializeDataType(map); } -} +} \ No newline at end of file diff --git a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java index 59d944e1ab..f111e897b8 100644 --- a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java @@ -42,6 +42,7 @@ import javax.management.remote.JMXServiceURL; import javax.script.ScriptException; +import com.serotonin.mango.web.dwr.beans.*; import net.sf.mbus4j.Connection; import net.sf.mbus4j.MBusAddressing; import net.sf.mbus4j.TcpIpConnection; @@ -246,2548 +247,2573 @@ private DwrResponseI18n tryDataSourceSave(DataSourceVO ds) { LOG.debug("Response: " + response.toString()); } - return response; - } - - @MethodFilter - public void cancelTestingUtility() { - Common.getUser().cancelTestingUtility(); - } - - @MethodFilter - public List enableAllPoints() { - User user = Common.getUser(); - if (user == null) - return null; - - DataSourceVO ds = user.getEditDataSource(); - if (ds.getId() == Common.NEW_ID) - return null; - - List points = new DataPointDao().getDataPoints(ds.getId(), - DataPointNameComparator.instance); - for (DataPointVO dataPointVO : points) { - if (!dataPointVO.isEnabled()) { - Permissions.ensureDataSourcePermission(Common.getUser(), - dataPointVO.getDataSourceId()); - - RuntimeManager runtimeManager = Common.ctx.getRuntimeManager(); - dataPointVO.setEnabled(true); - runtimeManager.saveDataPoint(dataPointVO); - } - } - return points; - } - - @MethodFilter - public List getPoints() { - User user = Common.getUser(); - if (user == null) - return null; - - DataSourceVO ds = user.getEditDataSource(); - if (ds.getId() == Common.NEW_ID) - return null; - - List points = new DataPointDao().getDataPoints(ds.getId(), - DataPointNameComparator.instance); - return points; - } - - @MethodFilter - public DataPointVO getPoint(int pointId) { - return getPoint(pointId, null); - } - - private DataPointVO getPoint(int pointId, DataPointDefaulter defaulter) { - DataSourceVO ds = Common.getUser().getEditDataSource(); - - DataPointVO dp; - if (pointId == Common.NEW_ID) { - dp = new DataPointVO(); - dp.setXid(new DataPointDao().generateUniqueXid()); - dp.setDataSourceId(ds.getId()); - dp.setPointLocator(ds.createPointLocator()); - dp.setEventDetectors(new ArrayList(0)); - if (defaulter != null) - defaulter.setDefaultValues(dp); - } else { - dp = new DataPointDao().getDataPoint(pointId); - if (dp != null && dp.getDataSourceId() != ds.getId()) - throw new RuntimeException("Data source id mismatch"); - } - - return dp; - } - - private DwrResponseI18n validatePoint(int id, String xid, String name, - PointLocatorVO locator, DataPointDefaulter defaulter) { - DwrResponseI18n response = new DwrResponseI18n(); - - DataPointVO dp = getPoint(id, defaulter); - dp.setXid(xid); - dp.setName(name); - dp.setPointLocator(locator); - - if (StringUtils.isEmpty(xid)) - response.addContextualMessage("xid", "validate.required"); - else if (!new DataPointDao().isXidUnique(xid, id)) - response.addContextualMessage("xid", "validate.xidUsed"); - else if (StringUtils.isLengthGreaterThan(xid, 50)) - response.addContextualMessage("xid", "validate.notLongerThan", 50); - - if (StringUtils.isEmpty(name)) - response.addContextualMessage("name", "dsEdit.validate.required"); - - locator.validate(response); - - if (!response.getHasMessages()) { - Common.ctx.getRuntimeManager().saveDataPoint(dp); - response.addData("id", dp.getId()); - response.addData("points", getPoints()); - } - - return response; - } - - @MethodFilter - public List deletePoint(int id) { - DataPointVO dp = getPoint(id, null); - if (dp != null) - Common.ctx.getRuntimeManager().deleteDataPoint(dp); - - return getPoints(); - } - - @MethodFilter - public Map toggleEditDataSource() { - DataSourceVO ds = Common.getUser().getEditDataSource(); - return super.toggleDataSource(ds.getId()); - } - - @MethodFilter - public DwrResponseI18n togglePoint(int dataPointId) { - DwrResponseI18n response = super.toggleDataPoint(dataPointId); - response.addData("points", getPoints()); - return response; - } - - @MethodFilter - public List getAlarms() { - DataSourceVO ds = Common.getUser().getEditDataSource(); - List events = new EventDao() - .getPendingEventsForDataSource(ds.getId(), Common.getUser() - .getId()); - Collections.sort(events, new Comparator() { - @Override - public int compare(EventInstance lhs, EventInstance rhs) { - // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending - return lhs.getActiveTimestamp() > rhs.getActiveTimestamp() ? -1 : (lhs.getActiveTimestamp() < rhs.getActiveTimestamp()) ? 1 : 0; - } - }); - List beans = new ArrayList(); - if (events != null) { - for (EventInstance event : events) - beans.add(new EventInstanceBean(event.isActive(), event - .getAlarmLevel(), DateFunctions.getTime(event - .getActiveTimestamp()), getMessage(event.getMessage()))); - } - return beans; - } - - @MethodFilter - public void updateEventAlarmLevel(int eventId, int alarmLevel) { - DataSourceVO ds = Common.getUser().getEditDataSource(); - ds.setAlarmLevel(eventId, alarmLevel); - } - - // - // - // Virtual stuff - // - @MethodFilter - public DwrResponseI18n saveVirtualDataSource(String name, String xid, - int updatePeriods, int updatePeriodType) { - VirtualDataSourceVO ds = (VirtualDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public IntMessagePair[] getChangeTypes(int dataTypeId) { - return ChangeTypeVO.getChangeTypes(dataTypeId); - } - - @MethodFilter - public DwrResponseI18n saveVirtualPointLocator(int id, String xid, - String name, VirtualPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - // - // - // Modbus common stuff - // - @MethodFilter - public Map modbusScanUpdate() { - Map result = new HashMap(); - ModbusNodeScanListener scan = Common.getUser().getTestingUtility( - ModbusNodeScanListener.class); - if (scan == null) - return null; - - result.put("nodes", scan.getNodesFound()); - result.put("message", scan.getMessage()); - result.put("finished", scan.isFinished()); - - return result; - } - - @MethodFilter - public DwrResponseI18n saveModbusPointLocator(int id, String xid, - String name, ModbusPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - private void testModbusPointLocator(ModbusMaster modbusMaster, - ModbusPointLocatorVO locator, boolean serial, - DwrResponseI18n response) { - locator.validate(response); - if (response.getHasMessages()) - return; - - try { - BaseLocator bl = ModbusDataSource.createModbusLocator(locator); - modbusMaster.init(); - Object result = modbusMaster.getValue(bl); - response.addData("result", new LocalizableMessage( - "dsEdit.modbus.locatorTest.result", result)); - } catch (ModbusInitException e) { - if (serial) - response.addMessage(new LocalizableMessage( - "dsEdit.modbus.locatorTestIp.startError", e - .getMessage())); - else - response.addMessage(new LocalizableMessage( - "dsEdit.modbus.locatorTestSerial.startError", e - .getMessage())); - } catch (ErrorResponseException e) { - response.addMessage(new LocalizableMessage("common.default", e - .getErrorResponse().getExceptionMessage())); - } catch (ModbusTransportException e) { - response.addMessage(ModbusDataSource.localExceptionMessage(e)); - } catch (IllegalCharsetNameException e) { - response.addMessage(new LocalizableMessage( - "validate.invalidCharset")); - } finally { - modbusMaster.destroy(); - } - } - - private void testModbusData(ModbusMaster modbusMaster, int slaveId, - int range, int offset, int length, boolean serial, - DwrResponseI18n response) { - boolean binary = range == RegisterRange.COIL_STATUS - || range == RegisterRange.INPUT_STATUS; - if (length > modbusMaster.getMaxReadCount(range)) - length = modbusMaster.getMaxReadCount(range); - if (offset + length > 65536) - length = 65536 - offset; - response.addData("length", length); - - try { - ModbusRequest mreq = new ModbusFactory().createReadRequest(slaveId, - range, offset, length); - - modbusMaster.init(); - ReadResponse mres = (ReadResponse) modbusMaster.send(mreq); - if (mres.isException()) - response.addMessage(new LocalizableMessage("common.default", - mres.getExceptionMessage())); - else { - List results = new ArrayList(); - if (binary) { - boolean[] data = mres.getBooleanData(); - for (int i = 0; i < length; i++) - results.add(Integer.toString(offset + i) + " ==> " - + Boolean.toString(data[i])); - } else { - short[] data = mres.getShortData(); - for (int i = 0; i < length; i++) - results.add(Integer.toString(offset + i) + " ==> " - + StreamUtils.toHex(data[i])); - } - response.addData("results", results); - } - } catch (ModbusIdException e) { - response.addMessage(ModbusDataSource.localExceptionMessage(e)); - } catch (ModbusInitException e) { - if (serial) - response.addMessage(new LocalizableMessage( - "dsEdit.modbus.locatorTestIp.startError", e - .getMessage())); - else - response.addMessage(new LocalizableMessage( - "dsEdit.modbus.locatorTestSerial.startError", e - .getMessage())); - } catch (ModbusTransportException e) { - response.addMessage(ModbusDataSource.localExceptionMessage(e)); - } finally { - modbusMaster.destroy(); - } - } - - // - // - // Modbus serial stuff - // - @MethodFilter - public DwrResponseI18n saveModbusSerialDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, boolean quantize, - int timeout, int retries, boolean contiguousBatches, - boolean createSlaveMonitorPoints, int maxReadBitCount, - int maxReadRegisterCount, int maxWriteRegisterCount, - String commPortId, int baudRate, int flowControlIn, - int flowControlOut, int dataBits, int stopBits, int parity, - String encoding, boolean echo, int concurrency) { - ModbusSerialDataSourceVO ds = (ModbusSerialDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setQuantize(quantize); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setContiguousBatches(contiguousBatches); - ds.setCreateSlaveMonitorPoints(createSlaveMonitorPoints); - ds.setMaxReadBitCount(maxReadBitCount); - ds.setMaxReadRegisterCount(maxReadRegisterCount); - ds.setMaxWriteRegisterCount(maxWriteRegisterCount); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setFlowControlIn(flowControlIn); - ds.setFlowControlOut(flowControlOut); - ds.setDataBits(dataBits); - ds.setStopBits(stopBits); - ds.setParity(parity); - ds.setEncodingStr(encoding); - ds.setEcho(echo); - ds.setConcurrency(concurrency); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public String modbusSerialScan(int timeout, int retries, String commPortId, - int baudRate, int flowControlIn, int flowControlOut, int dataBits, - int stopBits, int parity, String encoding, int concurrency) { - ModbusMaster modbusMaster; - try { - modbusMaster = createModbusSerialMaster(timeout, retries, - commPortId, baudRate, flowControlIn, flowControlOut, - dataBits, stopBits, parity, encoding, concurrency); - } catch (Exception e) { - return getMessage("dsEdit.modbus.scanError"); - } - ModbusNodeScanListener scan = new ModbusNodeScanListener( - getResourceBundle(), modbusMaster, true); - Common.getUser().setTestingUtility(scan); - return null; - } - - @MethodFilter - public DwrResponseI18n testModbusSerialLocator(int timeout, int retries, - String commPortId, int baudRate, int flowControlIn, - int flowControlOut, int dataBits, int stopBits, int parity, - String encoding, int concurrency, ModbusPointLocatorVO locator) { - DwrResponseI18n response = new DwrResponseI18n(); - ModbusMaster modbusMaster; - try { - modbusMaster = createModbusSerialMaster(timeout, retries, - commPortId, baudRate, flowControlIn, flowControlOut, - dataBits, stopBits, parity, encoding, concurrency); - testModbusPointLocator(modbusMaster, locator, true, response); - } catch (Exception e) { - response.addMessage(new LocalizableMessage( - "dsEdit.modbus.scanError")); - } - return response; - } - - @MethodFilter - public DwrResponseI18n testModbusSerialData(int timeout, int retries, - String commPortId, int baudRate, int flowControlIn, - int flowControlOut, int dataBits, int stopBits, int parity, - String encoding, int concurrency, int slaveId, int range, - int offset, int length) { - DwrResponseI18n response = new DwrResponseI18n(); - ModbusMaster modbusMaster; - try { - modbusMaster = createModbusSerialMaster(timeout, retries, - commPortId, baudRate, flowControlIn, flowControlOut, - dataBits, stopBits, parity, encoding, concurrency); - testModbusData(modbusMaster, slaveId, range, offset, length, true, - response); - } catch (Exception e) { - response.addMessage(new LocalizableMessage( - "dsEdit.modbus.scanError")); - } - return response; - } - - private ModbusMaster createModbusSerialMaster(int timeout, int retries, - String commPortId, int baudRate, int flowControlIn, - int flowControlOut, int dataBits, int stopBits, int parity, - String encoding, int concurrency) throws Exception { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - if (StringUtils.isEmpty(commPortId)) - throw new Exception(); - - SerialParameters params = new SerialParameters(); - params.setCommPortId(commPortId); - params.setPortOwnerName("Modbus Serial Data Source Scan"); - params.setBaudRate(baudRate); - params.setFlowControlIn(flowControlIn); - params.setFlowControlOut(flowControlOut); - params.setDataBits(dataBits); - params.setStopBits(stopBits); - params.setParity(parity); - - EncodingType encodingType = EncodingType.valueOf(encoding); - - ModbusMaster modbusMaster; - if (encodingType == EncodingType.ASCII) - modbusMaster = new ModbusFactory().createAsciiMaster(params); - else - modbusMaster = new ModbusFactory().createRtuMaster(params); - modbusMaster.setTimeout(timeout); - modbusMaster.setRetries(retries); - - return modbusMaster; - } - - // - // - // Modbus IP stuff - // - @MethodFilter - public DwrResponseI18n saveModbusIpDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, boolean quantize, - int timeout, int retries, boolean contiguousBatches, - boolean createSlaveMonitorPoints, int maxReadBitCount, - int maxReadRegisterCount, int maxWriteRegisterCount, - String transportType, String host, int port, boolean encapsulated, - boolean createSocketMonitorPoint) { - ModbusIpDataSourceVO ds = (ModbusIpDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setQuantize(quantize); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setContiguousBatches(contiguousBatches); - ds.setCreateSlaveMonitorPoints(createSlaveMonitorPoints); - ds.setMaxReadBitCount(maxReadBitCount); - ds.setMaxReadRegisterCount(maxReadRegisterCount); - ds.setMaxWriteRegisterCount(maxWriteRegisterCount); - ds.setTransportTypeStr(transportType); - ds.setHost(host); - ds.setPort(port); - ds.setEncapsulated(encapsulated); - ds.setCreateSocketMonitorPoint(createSocketMonitorPoint); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public String modbusIpScan(int timeout, int retries, String transport, - String host, int port, boolean encapsulated) { - ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries, - transport, host, port, encapsulated); - ModbusNodeScanListener scan = new ModbusNodeScanListener( - getResourceBundle(), modbusMaster, false); - Common.getUser().setTestingUtility(scan); - return null; - } - - @MethodFilter - public DwrResponseI18n testModbusIpLocator(int timeout, int retries, - String transport, String host, int port, boolean encapsulated, - ModbusPointLocatorVO locator) { - DwrResponseI18n response = new DwrResponseI18n(); - ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries, - transport, host, port, encapsulated); - testModbusPointLocator(modbusMaster, locator, false, response); - return response; - } - - @MethodFilter - public DwrResponseI18n testModbusIpData(int timeout, int retries, - String transport, String host, int port, boolean encapsulated, - int slaveId, int range, int offset, int length) { - DwrResponseI18n response = new DwrResponseI18n(); - ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries, - transport, host, port, encapsulated); - testModbusData(modbusMaster, slaveId, range, offset, length, false, - response); - return response; - } - - private ModbusMaster createModbusIpMaster(int timeout, int retries, - String transport, String host, int port, boolean encapsulated) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - IpParameters params = new IpParameters(); - params.setHost(host); - params.setPort(port); - params.setEncapsulated(encapsulated); - - TransportType transportType = TransportType.valueOf(transport); - - ModbusMaster modbusMaster; - if (transportType == TransportType.TCP_LISTENER) - modbusMaster = new ModbusFactory().createTcpListener(params); - else if (transportType == TransportType.UDP) - modbusMaster = new ModbusFactory().createUdpMaster(params); - else - modbusMaster = new ModbusFactory().createTcpMaster(params, - transportType == TransportType.TCP_KEEP_ALIVE); - modbusMaster.setTimeout(timeout); - modbusMaster.setRetries(retries); - - return modbusMaster; - } - - // - // - // SNMP stuff - // - @MethodFilter - public DwrResponseI18n saveSnmpDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String host, int port, - int snmpVersion, String community, String securityName, - String authProtocol, String authPassphrase, String privProtocol, - String privPassphrase, String engineId, String contextEngineId, - String contextName, int retries, int timeout, int trapPort, - String localAddress) { - SnmpDataSourceVO ds = (SnmpDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setHost(host); - ds.setPort(port); - ds.setSnmpVersion(snmpVersion); - ds.setCommunity(community); - ds.setSecurityName(securityName); - ds.setAuthProtocol(authProtocol); - ds.setAuthPassphrase(authPassphrase); - ds.setPrivProtocol(privProtocol); - ds.setPrivPassphrase(privPassphrase); - ds.setEngineId(engineId); - ds.setContextEngineId(contextEngineId); - ds.setContextName(contextName); - ds.setRetries(retries); - ds.setTimeout(timeout); - ds.setTrapPort(trapPort); - ds.setLocalAddress(localAddress); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveSnmpPointLocator(int id, String xid, - String name, SnmpPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public void snmpGetOid(String oid, String host, int port, int snmpVersion, - String community, String securityName, String authProtocol, - String authPassphrase, String privProtocol, String privPassphrase, - String engineId, String contextEngineId, String contextName, - int retries, int timeout) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - Version version = Version.getVersion(snmpVersion, community, - securityName, authProtocol, authPassphrase, privProtocol, - privPassphrase, engineId, contextEngineId, contextName); - user.setTestingUtility(new SnmpOidGet(getResourceBundle(), host, port, - version, oid, retries, timeout)); - } - - @MethodFilter - public String snmpGetOidUpdate() { - SnmpOidGet snmpOidGet = Common.getUser().getTestingUtility( - SnmpOidGet.class); - if (snmpOidGet == null) - return null; - return snmpOidGet.getResult(); - } - - // - // - // SQL stuff - // - @MethodFilter - public DwrResponseI18n saveSqlDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String driverClassname, - String connectionUrl, String username, String password, - String selectStatement, boolean rowBasedQuery) { - SqlDataSourceVO ds = (SqlDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setDriverClassname(driverClassname); - ds.setConnectionUrl(connectionUrl); - ds.setUsername(username); - ds.setPassword(password); - ds.setSelectStatement(selectStatement); - ds.setRowBasedQuery(rowBasedQuery); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveSqlPointLocator(int id, String xid, String name, - SqlPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public void sqlTestStatement(String driverClassname, String connectionUrl, - String username, String password, String selectStatement, - boolean rowBasedQuery) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - user.setTestingUtility(new SqlStatementTester(getResourceBundle(), - driverClassname, connectionUrl, username, password, - selectStatement, rowBasedQuery)); - } - - @MethodFilter - public Map sqlTestStatementUpdate() { - Map result = new HashMap(); - SqlStatementTester statementTester = Common.getUser() - .getTestingUtility(SqlStatementTester.class); - if (statementTester == null) - return null; - if (!statementTester.isDone()) - return null; - - if (statementTester.getErrorMessage() != null) - result.put("error", statementTester.getErrorMessage()); - else - result.put("resultTable", statementTester.getResultTable()); - return result; - } - - // - // - // HTTP receiver stuff - // - @MethodFilter - public DwrResponseI18n saveHttpReceiverDataSource(String name, String xid, - String[] ipWhiteList, String[] deviceIdWhiteList) { - HttpReceiverDataSourceVO ds = (HttpReceiverDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setIpWhiteList(ipWhiteList); - ds.setDeviceIdWhiteList(deviceIdWhiteList); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveHttpReceiverPointLocator(int id, String xid, - String name, HttpReceiverPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public void httpReceiverListenForData(String[] ipWhiteList, - String[] deviceIdWhiteList) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - user.setTestingUtility(new HttpReceiverDataListener( - getResourceBundle(), ipWhiteList, deviceIdWhiteList)); - } - - @MethodFilter - public Map httpReceiverListenerUpdate() { - Map result = new HashMap(); - HttpReceiverDataListener l = Common.getUser().getTestingUtility( - HttpReceiverDataListener.class); - if (l == null) - return null; - - HttpReceiverData data = l.getData(); - if (data != null) { - result.put("remoteIp", data.getRemoteIp()); - result.put("deviceId", data.getDeviceId()); - result.put("time", DateFunctions.getTime(data.getTime())); - result.put("data", data.getData()); - } - result.put("message", l.getMessage()); - - return result; - } - - @MethodFilter - public String validateIpMask(String ipMask) { - return IpAddressUtils.checkIpMask(ipMask); - } - - // - // - // OneWire stuff - // - @MethodFilter - public DwrResponseI18n saveOneWireDataSource(String name, String xid, - String commPortId, int updatePeriodType, int updatePeriods, - int rescanPeriodType, int rescanPeriods) { - OneWireDataSourceVO ds = (OneWireDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setUpdatePeriodType(updatePeriodType); - ds.setUpdatePeriods(updatePeriods); - ds.setRescanPeriodType(rescanPeriodType); - ds.setRescanPeriods(rescanPeriods); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveOneWirePointLocator(int id, String xid, - String name, OneWirePointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public DwrResponseI18n readOneWireNetwork(String commPointId) { - DwrResponseI18n response = new DwrResponseI18n(); - - Network network = null; - try { - // Check for an RT that already has a network. - OneWireDataSourceVO ds = (OneWireDataSourceVO) Common.getUser() - .getEditDataSource(); - OneWireDataSourceRT rt = (OneWireDataSourceRT) Common.ctx - .getRuntimeManager().getRunningDataSource(ds.getId()); - if (rt != null) - // Use the existing one if it exists (i.e. initialized properly) - network = rt.getNetwork(); - - if (network == null) - // Create a new one. - network = new Network(commPointId); - - try { - network.lock(); - network.quickInitialize(); - - List addresses = network.getAddresses(); - List devices = new ArrayList(); - for (Long address : addresses) { - NetworkPath path = network.getNetworkPath(address); - if (!path.isCoupler()) - devices.add(path.getTargetInfo()); - } - - response.addData("devices", devices); - } finally { - network.unlock(); - } - } catch (Exception e) { - response.addGenericMessage("common.default", e.getMessage()); - } finally { - try { - if (network != null) - network.terminate(); - } catch (OneWireException e) { - // no op - } - } - - return response; - } - - @MethodFilter - public DataPointVO addOneWirePoint(String address) { - DataPointVO dp = getPoint(Common.NEW_ID, null); - OneWirePointLocatorVO locator = dp.getPointLocator(); - locator.setAddress(address); - return dp; - } - - // - // - // Meta stuff - // - @MethodFilter - public DwrResponseI18n saveMetaDataSource(String name, String xid) { - MetaDataSourceVO ds = (MetaDataSourceVO) Common.getUser() - .getEditDataSource(); - ds.setXid(xid); - ds.setName(name); - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveMetaPointLocator(int id, String xid, - String name, MetaPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public DwrResponseI18n validateScript(String script, - List context, int dataTypeId) { - DwrResponseI18n response = new DwrResponseI18n(); - - ScriptExecutor executor = new ScriptExecutor(); - try { - Map convertedContext = executor - .convertContext(context); - PointValueTime pvt = executor.execute(script, convertedContext, - System.currentTimeMillis(), dataTypeId, -1); - if (pvt.getTime() == -1) - response.addContextualMessage("script", - "dsEdit.meta.test.success", pvt.getValue()); - else - response.addContextualMessage("script", - "dsEdit.meta.test.successTs", pvt.getValue(), - DateFunctions.getTime(pvt.getTime())); - } catch (DataPointStateException e) { - response.addMessage("context", e.getLocalizableMessage()); - } catch (ScriptException e) { - response.addContextualMessage("script", - "dsEdit.meta.test.scriptError", e.getMessage()); - } catch (ResultTypeException e) { - response.addMessage("script", e.getLocalizableMessage()); - } - - return response; - } - - // - // - // BACnet I/P stuff - // - @MethodFilter - public DwrResponseI18n saveBACnetIpDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, int deviceId, - String broadcastAddress, int port, int timeout, int segTimeout, - int segWindow, int retries, int covSubscriptionTimeoutMinutes, - int maxReadMultipleReferencesSegmented, - int maxReadMultipleReferencesNonsegmented) { - BACnetIPDataSourceVO ds = (BACnetIPDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setDeviceId(deviceId); - ds.setBroadcastAddress(broadcastAddress); - ds.setPort(port); - ds.setTimeout(timeout); - ds.setSegTimeout(segTimeout); - ds.setSegWindow(segWindow); - ds.setRetries(retries); - ds.setCovSubscriptionTimeoutMinutes(covSubscriptionTimeoutMinutes); - ds.setMaxReadMultipleReferencesSegmented(maxReadMultipleReferencesSegmented); - ds.setMaxReadMultipleReferencesNonsegmented(maxReadMultipleReferencesNonsegmented); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveBACnetIPPointLocator(int id, String xid, - String name, BACnetIPPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public void sendBACnetWhoIs(int deviceId, String broadcastAddress, - int port, int timeout, int segTimeout, int segWindow, int retries, - int whoIsPort, int maxReadMultipleReferencesSegmented, - int maxReadMultipleReferencesNonsegmented) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - BACnetDiscovery whoIs = new BACnetDiscovery(getResourceBundle(), - deviceId, broadcastAddress, port, timeout, segTimeout, - segWindow, retries, whoIsPort, - maxReadMultipleReferencesSegmented, - maxReadMultipleReferencesNonsegmented); - user.setTestingUtility(whoIs); - } - - @MethodFilter - public Map bacnetWhoIsUpdate() { - Map result = new HashMap(); - BACnetDiscovery test = Common.getUser().getTestingUtility( - BACnetDiscovery.class); - if (test == null) - return null; - - test.addUpdateInfo(result); - - return result; - } - - @MethodFilter - public int getBACnetDeviceDetails(int index) { - BACnetDiscovery test = Common.getUser().getTestingUtility( - BACnetDiscovery.class); - if (test == null) - return index; - test.getDeviceDetails(index); - return -1; - } - - @MethodFilter - public DwrResponseI18n sendObjectListRequest(int deviceId, - String broadcastAddress, int port, int timeout, int segTimeout, - int segWindow, int retries, int maxReadMultipleReferencesSegmented, - int maxReadMultipleReferencesNonsegmented, String remoteIp, - int remotePort, int networkNumber, String networkAddress, - int remoteDeviceId) { - LocalDevice localDevice = new LocalDevice(deviceId, broadcastAddress); - localDevice.setPort(port); - localDevice.setTimeout(timeout); - localDevice.setSegTimeout(segTimeout); - localDevice.setSegWindow(segWindow); - localDevice.setRetries(retries); - localDevice - .setMaxReadMultipleReferencesSegmented(maxReadMultipleReferencesSegmented); - localDevice - .setMaxReadMultipleReferencesNonsegmented(maxReadMultipleReferencesNonsegmented); - - DwrResponseI18n result = new DwrResponseI18n(); - try { - localDevice.initialize(); - - Address address = new Address(InetAddress.getByName(remoteIp) - .getAddress(), remotePort); - com.serotonin.bacnet4j.Network network = null; - if (!StringUtils.isEmpty(networkAddress)) - network = new com.serotonin.bacnet4j.Network(networkNumber, - networkAddress); - RemoteDevice d = localDevice.findRemoteDevice(address, network, - remoteDeviceId); - - List details = BACnetDiscovery.getDetails( - localDevice, d); - - result.addData("deviceAddress", d.getAddress().toIpString()); - result.addData("deviceName", d.getName()); - result.addData("deviceIp", d.getAddress().toIpString()); - result.addData("devicePort", d.getAddress().getPort()); - network = d.getNetwork(); - if (network != null) { - result.addData("deviceNetworkNumber", - network.getNetworkNumber()); - result.addData("deviceNetworkAddress", - network.getNetworkAddressDottedString()); - } - result.addData("deviceInstanceNumber", d.getObjectIdentifier() - .getInstanceNumber()); - result.addData("deviceDescription", - BACnetDiscovery.getDeviceDescription(d)); - result.addData("deviceDetails", details); - } catch (Exception e) { - result.addData("error", e.getMessage()); - } finally { - localDevice.terminate(); - } - - return result; - } - - @MethodFilter - public DataPointVO addBacnetPoint(String ip, int port, int networkNumber, - String networkAddress, int deviceInstanceNumber, - BACnetObjectBean bean) { - DataPointVO dp = getPoint(Common.NEW_ID, null); - BACnetIPPointLocatorVO locator = dp.getPointLocator(); - - dp.setName(bean.getObjectName()); - - // Default some of the locator values. - locator.setRemoteDeviceIp(ip); - locator.setRemoteDevicePort(port); - locator.setNetworkNumber(networkNumber); - locator.setNetworkAddress(networkAddress); - locator.setRemoteDeviceInstanceNumber(deviceInstanceNumber); - locator.setObjectTypeId(bean.getObjectTypeId()); - locator.setObjectInstanceNumber(bean.getInstanceNumber()); - locator.setPropertyIdentifierId(PropertyIdentifier.presentValue - .intValue()); - locator.setDataTypeId(bean.getDataTypeId()); - locator.setUseCovSubscription(bean.isCov()); - - // We would like to default text renderer values too, but it's rather - // inconvenient to do. - - return dp; - } - - // - // - // HTTP Retriever stuff - // - @MethodFilter - public DwrResponseI18n saveHttpRetrieverDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String url, - int timeoutSeconds, int retries, boolean stop) { - HttpRetrieverDataSourceVO ds = (HttpRetrieverDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setUrl(url); - ds.setTimeoutSeconds(timeoutSeconds); - ds.setRetries(retries); - ds.setStop(stop); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveHttpRetrieverDataSourceWithReactivationOptions(String name, String xid, - int updatePeriods, int updatePeriodType, String url, - int timeoutSeconds, int retries, boolean stop, boolean sleep, short typeReactivation, short valueReactivation) { - HttpRetrieverDataSourceVO ds = (HttpRetrieverDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setUrl(url); - ds.setTimeoutSeconds(timeoutSeconds); - ds.setRetries(retries); - ds.setStop(stop); - ReactivationDs rDs = new ReactivationDs(sleep, typeReactivation, valueReactivation); - ds.setReactivation(rDs); - - DwrResponseI18n result; - - if (ds.getId() > 0) { - ReactivationManager.getInstance().stopReactivation(ds.getId()); - } - result = tryDataSourceSave(ds); - - if (sleep) { - ReactivationManager.getInstance().startReactivation(ds.getId()); - } - - return result; - } - - - @MethodFilter - public DwrResponseI18n saveHttpRetrieverPointLocator(int id, String xid, - String name, HttpRetrieverPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public String testHttpRetrieverValueParams(String url, int timeoutSeconds, - int retries, String valueRegex, int dataTypeId, String valueFormat) { - try { - String data = HttpRetrieverDataSourceRT.getData(url, - timeoutSeconds, retries); - - Pattern valuePattern = Pattern.compile(valueRegex); - DecimalFormat decimalFormat = null; - if (dataTypeId == DataTypes.NUMERIC - && !StringUtils.isEmpty(valueFormat)) - decimalFormat = new DecimalFormat(valueFormat); - MangoValue value = DataSourceUtils.getValue(valuePattern, data, - dataTypeId, valueFormat, null, decimalFormat, null); - return getMessage("common.result") + ": " + value.toString(); - } catch (LocalizableException e) { - return getMessage(e.getLocalizableMessage()); - } catch (Exception e) { - return e.getMessage(); - } - } - - @MethodFilter - public String testHttpRetrieverTimeParams(String url, int timeoutSeconds, - int retries, String timeRegex, String timeFormat) { - try { - String data = HttpRetrieverDataSourceRT.getData(url, - timeoutSeconds, retries); - - Pattern timePattern = Pattern.compile(timeRegex); - DateFormat dateFormat = new SimpleDateFormat(timeFormat); - long time = DataSourceUtils.getValueTime( - System.currentTimeMillis(), timePattern, data, dateFormat, - null); - return DateFunctions.getTime(time); - } catch (LocalizableException e) { - return getMessage(e.getLocalizableMessage()); - } catch (Exception e) { - return e.getMessage(); - } - } - - // - // - // HTTP Image stuff - // - @MethodFilter - public DwrResponseI18n saveHttpImageDataSource(String name, String xid, - int updatePeriods, int updatePeriodType) { - HttpImageDataSourceVO ds = (HttpImageDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveHttpImagePointLocator(int id, String xid, - String name, HttpImagePointLocatorVO locator) { - return validatePoint(id, xid, name, locator, new DataPointDefaulter() { - @Override - public void setDefaultValues(DataPointVO dp) { - if (dp.isNew()) - dp.setLoggingType(DataPointVO.LoggingTypes.NONE); - } - }); - } - - // - // - // POP3 Email stuff - // - @MethodFilter - public DwrResponseI18n savePop3DataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String pop3Server, - String username, String password) { - Pop3DataSourceVO ds = (Pop3DataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setPop3Server(pop3Server); - ds.setUsername(username); - ds.setPassword(password); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n savePop3PointLocator(int id, String xid, - String name, Pop3PointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public String testPop3ValueParams(String testData, String valueRegex, - int dataTypeId, String valueFormat) { - try { - Pattern valuePattern = Pattern.compile(valueRegex); - DecimalFormat decimalFormat = null; - if (dataTypeId == DataTypes.NUMERIC - && !StringUtils.isEmpty(valueFormat)) - decimalFormat = new DecimalFormat(valueFormat); - MangoValue value = DataSourceUtils.getValue(valuePattern, testData, - dataTypeId, valueFormat, null, decimalFormat, null); - return getMessage("common.result") + ": " + value.toString(); - } catch (LocalizableException e) { - return getMessage(e.getLocalizableMessage()); - } catch (Exception e) { - return e.getMessage(); - } - } - - @MethodFilter - public String testPop3TimeParams(String testData, String timeRegex, - String timeFormat) { - try { - Pattern timePattern = Pattern.compile(timeRegex); - DateFormat dateFormat = new SimpleDateFormat(timeFormat); - long time = DataSourceUtils.getValueTime( - System.currentTimeMillis(), timePattern, testData, - dateFormat, null); - return DateFunctions.getTime(time); - } catch (Exception e) { - return e.getMessage(); - } - } - - // - // - // NMEA stuff - // - @MethodFilter - public DwrResponseI18n saveNmeaDataSource(String name, String xid, - String commPortId, int baudRate, int resetTimeout) { - NmeaDataSourceVO ds = (NmeaDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setResetTimeout(resetTimeout); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveNmeaPointLocator(int id, String xid, - String name, NmeaPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public void nmeaListenForMessages(String commPortId, int baudRate) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - user.setTestingUtility(new NmeaUtilListener(getResourceBundle(), - commPortId, baudRate)); - } - - @MethodFilter - public Map nmeaListenerUpdate() { - NmeaUtilListener l = Common.getUser().getTestingUtility( - NmeaUtilListener.class); - if (l == null) - return null; - - Map result = new HashMap(); - result.put("messages", l.getMessages()); - result.put("message", l.getMessage()); - - return result; - } - - // - // - // Galil stuff - // - @MethodFilter - public DwrResponseI18n saveGalilDataSource(String name, String xid, - String host, int port, int timeout, int retries, int updatePeriods, - int updatePeriodType) { - GalilDataSourceVO ds = (GalilDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setHost(host); - ds.setPort(port); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveGalilPointLocator(int id, String xid, - String name, GalilPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public String galilTestCommand(String host, int port, int timeout, - String command) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - try { - GalilCommandTester tester = new GalilCommandTester( - getResourceBundle(), host, port, timeout, command); - try { - tester.join(); - return tester.getResult(); - } catch (InterruptedException e) { - return e.getMessage(); - } - } catch (IOException e) { - return e.getMessage(); - } - } - - // - // - // EBI25 stuff - // - @MethodFilter - public DwrResponseI18n saveEBI25DataSource(String name, String xid, - int updatePeriods, int updatePeriodType, int timeout, int retries, - String host, int port, boolean keepAlive) { - EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setHost(host); - ds.setPort(port); - ds.setKeepAlive(keepAlive); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public EBI25InterfaceReader ebi25ReadInterface(String host, int port, - boolean keepAlive, int timeout, int retries) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser() - .getEditDataSource(); - - EBI25InterfaceReader reader = new EBI25InterfaceReader( - getResourceBundle(), ds, host, port, keepAlive, timeout, - retries); - - if (reader.getErrorMessage() == null) { - tryDataSourceSave(ds); - reader.setPoints(getPoints()); - } - - return reader; - } - - @MethodFilter - public LocalizableMessage ebi25SyncTime(String host, int port, int timeout, - int retries) { - return new EBI25InterfaceUpdater().updateSysTime(host, port, timeout, - retries); - } - - @MethodFilter - public DwrResponseI18n saveEBI25PointLocator(int id, String xid, - String name, final EBI25PointLocatorVO locator) { - DwrResponseI18n response = new DwrResponseI18n(); - - if (locator.getType() == EBI25PointLocatorVO.TYPE_VALUE) { - EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser() - .getEditDataSource(); - - if (locator.getSampleRate() < 1) - response.addContextualMessage("sampleRate", - "validate.greaterThanZero"); - else { - // Try to update the EBI25 interface - LocalizableMessage errorMessage = new EBI25InterfaceUpdater() - .updateLogger(ds.getHost(), ds.getPort(), - ds.getTimeout(), ds.getRetries(), locator); - - if (errorMessage == null) { - response = validatePoint(id, xid, name, locator, - new DataPointDefaulter() { - @Override - public void setDefaultValues(DataPointVO dp) { - // Update the point's high/low detectors - // with the locator values. - PointEventDetectorVO high = EBI25Constants - .findDetector( - dp.getEventDetectors(), - true); - if (high != null) - high.setLimit(locator.getHighLimit()); - - PointEventDetectorVO low = EBI25Constants - .findDetector( - dp.getEventDetectors(), - false); - if (low != null) - low.setLimit(locator.getLowLimit()); - } - }); - } else - response.addMessage("sampleRate", errorMessage); - } - } else - response = validatePoint(id, xid, name, locator, null); - - return response; - } - - // - // - // VMStat stuff - // - @MethodFilter - public DwrResponseI18n saveVMStatDataSource(String name, String xid, - int pollSeconds, int outputScale) { - VMStatDataSourceVO ds = (VMStatDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setPollSeconds(pollSeconds); - ds.setOutputScale(outputScale); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveVMStatPointLocator(int id, String xid, - String name, VMStatPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - // - // - // Viconics stuff - // - @MethodFilter - public DwrResponseI18n saveViconicsDataSource(String name, String xid, - String commPortId, int panId, int channel, int timeout, - int retries, int networkTimeoutSeconds, - int deviceWarningTimeoutSeconds, int deviceRemoveTimeoutSeconds, - int pointValueMinimumFreshnessSeconds, boolean convertToCelsius) { - ViconicsDataSourceVO ds = (ViconicsDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setPanId(panId); - ds.setChannel(channel); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setNetworkTimeoutSeconds(networkTimeoutSeconds); - ds.setDeviceWarningTimeoutSeconds(deviceWarningTimeoutSeconds); - ds.setDeviceRemoveTimeoutSeconds(deviceRemoveTimeoutSeconds); - ds.setPointValueMinimumFreshnessSeconds(pointValueMinimumFreshnessSeconds); - ds.setConvertToCelsius(convertToCelsius); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveViconicsPointLocator(int id, String xid, - String name, ViconicsPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public DwrResponseI18n getRfModuleInfo() { - ViconicsDataSourceVO ds = (ViconicsDataSourceVO) Common.getUser() - .getEditDataSource(); - - ViconicsDataSourceRT rt = (ViconicsDataSourceRT) Common.ctx - .getRuntimeManager().getRunningDataSource(ds.getId()); - DwrResponseI18n response = new DwrResponseI18n(); - - if (rt == null) - response.addGenericMessage("dsEdit.viconics.dataSourceNotStarted"); - else { - try { - NetworkIdentifyResponse res = rt - .send(new NetworkIdentifyRequest()); - - Map rfm = new HashMap(); - rfm.put("firmware", ViconicsNetwork.getRevisionString(res - .getZigbeeFirmwareRevision())); - rfm.put("networkAddr", - Integer.toString(res.getZigbeeNetworkAddress())); - rfm.put("ieee", ViconicsNetwork.getIeeeString(res.getIeee())); - rfm.put("chipRevision", Integer.toString(res.getChipRevision())); - response.addData("rfm", rfm); - - List> devices = new ArrayList>(); - for (ViconicsDevice device : rt.getDevices()) { - Map dev = new HashMap(); - dev.put("commAddr", - Integer.toString(device.getCommAddress())); - dev.put("modelNumber", device.getConfiguration().getModel()); - dev.put("firmware", ViconicsNetwork - .getRevisionString(device.getFirmwareRevision())); - dev.put("zigbeeFirmware", ViconicsNetwork - .getRevisionString(device - .getZigbeeFirmwareRevision())); - dev.put("zigbeeNetworkAddr", - Integer.toString(device.getZigbeeNetworkAddress())); - dev.put("ieee", - ViconicsNetwork.getIeeeString(device.getIeee())); - dev.put("chipRevision", - Integer.toString(device.getChipRevision())); - dev.put("crss", - Integer.toString(device.getLinkQualityPercent()) - + "%"); - dev.put("trss", - Integer.toString(device.getReturnQualityPercent()) - + "%"); - devices.add(dev); - } - response.addData("devices", devices); - } catch (ViconicsTransportException e) { - response.addGenericMessage( - "dsEdit.viconics.networkIdentifyFailure", - e.getMessage()); - } catch (RequestFailureException e) { - response.addGenericMessage( - "dsEdit.viconics.networkIdentifyFailure", - e.getMessage()); - } - } - - return response; - } - - // - // - // MBus stuff - // - public DwrResponseI18n saveMBusDataSource(String name, String xid, - TcpIpConnection connection, int updatePeriodType, int updatePeriods) { - MBusDataSourceVO ds = (MBusDataSourceVO) Common.getUser() - .getEditDataSource(); - ds.setXid(xid); - ds.setName(name); - ds.setConnection(connection); - ds.setUpdatePeriodType(updatePeriodType); - ds.setUpdatePeriods(updatePeriods); - return tryDataSourceSave(ds); - } - - public DwrResponseI18n saveMBusPointLocator(int id, String xid, - String name, MBusPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - public Connection getMBusConn() { - TcpIpConnection conn = new TcpIpConnection(); - conn.setHost("localhost"); - conn.setPort(2000); - return conn; - } - - public void searchMBus(TcpIpConnection conn, PrimaryAddressingSearch addressing) { - User user = Common.getUser(); - - Permissions.ensureDataSourcePermission(user); - - MBusDiscovery discovery = new MBusDiscovery(getResourceBundle(), conn, - addressing); - discovery.start(); - user.setTestingUtility(discovery); - } - - public void searchMBus(TcpIpConnection conn, SecondaryAddressingSearch addressing) { - User user = Common.getUser(); - - Permissions.ensureDataSourcePermission(user); - - MBusDiscovery discovery = new MBusDiscovery(getResourceBundle(), conn, - addressing); - discovery.start(); - user.setTestingUtility(discovery); - } - - - public Map mBusSearchUpdate() { - Map result = new HashMap(); - MBusDiscovery test = Common.getUser().getTestingUtility( - MBusDiscovery.class); - if (test == null) - return null; - - test.addUpdateInfo(result); - return result; - } - - public Map getMBusResponseFrames(int deviceIndex) { - Map result = new HashMap(); - MBusDiscovery test = Common.getUser().getTestingUtility( - MBusDiscovery.class); - if (test == null) - return null; - - test.getDeviceDetails(deviceIndex, result); - return result; - } - - public DataPointVO addMBusPoint(String addressing, int deviceIndex, - int rsIndex, int dbIndex) { - DataPointVO dp = getPoint(Common.NEW_ID, null); - MBusPointLocatorVO locator = (MBusPointLocatorVO) dp.getPointLocator(); - - MBusDiscovery test = Common.getUser().getTestingUtility( - MBusDiscovery.class); - if (test == null) - return null; - - MBusResponseFramesContainer dev = test.getDevice(deviceIndex); - if (dev.getResponseFrameContainer(rsIndex).getResponseFrame() instanceof UserDataResponse) { - UserDataResponse udr = (UserDataResponse) dev - .getResponseFrameContainer(rsIndex).getResponseFrame(); - DataBlock db = udr.getDataBlock(dbIndex); - - dp.setName(db.getParamDescr()); - - locator.setAddressing(MBusAddressing.valueOf(addressing)); - locator.setAddress(dev.getAddress()); - locator.setMedium(dev.getMedium().getLabel()); - locator.setManufacturer(dev.getManufacturer()); - locator.setVersion(dev.getVersion()); - locator.setIdentNumber(dev.getIdentNumber()); - locator.setResponseFrame(dev.getResponseFrameContainer(rsIndex) - .getName()); - locator.setDeviceUnit(db.getSubUnit()); - locator.setDifCode(db.getDataFieldCode().getLabel()); - locator.setFunctionField(db.getFunctionField().getLabel()); - locator.setStorageNumber(db.getStorageNumber()); - locator.setTariff(db.getTariff()); - locator.setSiPrefix(db.getVif().getSiPrefix() == null ? null : db - .getVif().getSiPrefix().getLabel()); - locator.setUnitOfMeasurement(db.getVif().getUnitOfMeasurement() == null ? null - : db.getVif().getUnitOfMeasurement().getLabel()); - locator.setVifType(db.getVif().getVifType().getLabel()); - locator.setVifLabel(db.getVif().getLabel()); - locator.setExponent(db.getVif().getExponent()); - if (db.getVifes() != null) { - final String[] vifeLabels = new String[db.getVifes().length]; - final String[] vifeTypes = new String[db.getVifes().length]; - for (int i = 0; i < vifeLabels.length; i++) { - vifeTypes[i] = db.getVifes()[i].getVifeType().getLabel(); - vifeLabels[i] = db.getVifes()[i].getLabel(); - } - locator.setVifeTypes(vifeTypes); - locator.setVifeTypes(vifeTypes); - locator.setVifeLabels(vifeLabels); - } else { - locator.setVifeLabels(null); - } - } - return dp; - } - - // - // - // OpenV4J stuff - // - public void searchOpenV4J(String commPortId) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - OpenV4JDiscovery discovery = OpenV4JDiscovery.searchDataPoints( - getResourceBundle(), commPortId); - user.setTestingUtility(discovery); - } - - public void detectOpenV4JDevice(String commPortId) { - User user = Common.getUser(); - Permissions.ensureDataSourcePermission(user); - - OpenV4JDiscovery discovery = OpenV4JDiscovery.detectDevice( - getResourceBundle(), commPortId); - ; - user.setTestingUtility(discovery); - } - - public DwrResponseI18n saveOpenV4JDataSource(String name, String xid, - String commPortId, int updatePeriodType, int updatePeriods, - String device, String protocol) { - OpenV4JDataSourceVO ds = (OpenV4JDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setUpdatePeriodType(updatePeriodType); - ds.setUpdatePeriods(updatePeriods); - ds.setDevice(Devices.valueOf(device)); - ds.setProtocol(Protocol.valueOf(protocol)); - return tryDataSourceSave(ds); - } - - public DwrResponseI18n saveOpenV4JPointLocator(int id, String xid, - String name, OpenV4JPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - public Map openV4JSearchUpdate() { - Map result = new HashMap(); - OpenV4JDiscovery test = Common.getUser().getTestingUtility( - OpenV4JDiscovery.class); - if (test == null) - return null; - - test.addUpdateInfo(result); - return result; - } - - public Map openV4JDetectDeviceUpdate() { - Map result = new HashMap(); - OpenV4JDiscovery test = Common.getUser().getTestingUtility( - OpenV4JDiscovery.class); - if (test == null) - return null; - - test.addDeviceInfo(result); - return result; - } - - public OpenV4JProtocolBean[] getOpenV4jProtocolsOfDevice(String deviceName) { - return OpenV4JProtocolBean.fromDevice(Devices.valueOf(deviceName)); - } - - public OpenV4JDataPointBean[] getOpenV4jDataPointsOfGroup(String groupName) { - Group g = Group.valueOf(groupName); - List result = new ArrayList(); - for (DataPoint dp : DataPoint.values()) { - if (dp.getGroup().equals(g)) { - result.add(new OpenV4JDataPointBean(dp)); - } - } - return result.toArray(new OpenV4JDataPointBean[result.size()]); - } - - public DataPointVO addOpenV4JPoint(String openV4JEnumName) { - DataPointVO result = getPoint(Common.NEW_ID, null); - OpenV4JPointLocatorVO locator = (OpenV4JPointLocatorVO) result - .getPointLocator(); - - OpenV4JDiscovery test = Common.getUser().getTestingUtility( - OpenV4JDiscovery.class); - if (test == null) { - return null; - } - - final DataPoint dp = DataPoint.valueOf(openV4JEnumName); - result.setName(dp.getGroup().getLabel() + " " + dp.getLabel()); - locator.setDataPointName(dp.getName()); - return result; - } - - // - - // - // - // DNP3 stuff - // - @MethodFilter - public DwrResponseI18n saveDNP3IpDataSource(String name, String xid, - int sourceAddress, int slaveAddress, String host, int port, - int staticPollPeriods, int rbePollPeriods, int rbePeriodType, - boolean quantize, int timeout, int retries) { - Dnp3IpDataSourceVO ds = (Dnp3IpDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setSourceAddress(sourceAddress); - ds.setSlaveAddress(slaveAddress); - ds.setHost(host); - ds.setPort(port); - - ds.setStaticPollPeriods(staticPollPeriods); - ds.setRbePeriodType(rbePeriodType); - ds.setRbePollPeriods(rbePollPeriods); - ds.setQuantize(quantize); - ds.setTimeout(timeout); - ds.setRetries(retries); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveDNP3SerialDataSource(String name, String xid, - int sourceAddress, int slaveAddress, String commPortId, - int baudRate, int staticPollPeriods, int rbePollPeriods, - int rbePeriodType, boolean quantize, int timeout, int retries) { - Dnp3SerialDataSourceVO ds = (Dnp3SerialDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setSourceAddress(sourceAddress); - ds.setSlaveAddress(slaveAddress); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setStaticPollPeriods(staticPollPeriods); - ds.setRbePeriodType(rbePeriodType); - ds.setRbePollPeriods(rbePollPeriods); - ds.setQuantize(quantize); - ds.setTimeout(timeout); - ds.setRetries(retries); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveDnp3PointLocator(int id, String xid, - String name, Dnp3PointLocatorVO locator) { - DwrResponseI18n response = new DwrResponseI18n(); - - if (locator.getTimeOn() < 0) - response.addContextualMessage("timeOn", - "reports.validate.lessThan0"); - if (locator.getTimeOff() < 0) - response.addContextualMessage("timeOff", - "reports.validate.lessThan0"); - - List points = getPoints(); - Iterator itr = points.iterator(); - while (itr.hasNext()) { - DataPointVO vo = (DataPointVO) itr.next(); - Dnp3PointLocatorVO loc = (Dnp3PointLocatorVO) vo.getPointLocator(); - if (loc.getDnp3DataType() == ((Dnp3PointLocatorVO) locator) - .getDnp3DataType() - && loc.getIndex() == ((Dnp3PointLocatorVO) locator) - .getIndex() && id != vo.getId()) { - response.addContextualMessage("index", - "dsEdit.dnp3.validate.indexUsed"); - } - } - - if (!response.getHasMessages()) - return validatePoint(id, xid, name, locator, null); - return response; - } - - @MethodFilter - public DwrResponseI18n saveMultipleDnp3PointLocator(String[] names, - int[] index, Dnp3PointLocatorVO[] locators) { - return validateMultipleDnp3Points(names, index, locators, null); - } - - private DwrResponseI18n validateMultipleDnp3Points(String[] names, - int[] index, Dnp3PointLocatorVO[] locators, - DataPointDefaulter defaulter) { - DwrResponseI18n response = new DwrResponseI18n(); - - if (locators[0].getClass().equals(Dnp3PointLocatorVO.class)) { - if (locators[0].getTimeOn() < 0) - response.addContextualMessage("timeOn", - "reports.validate.lessThan0"); - if (locators[0].getTimeOff() < 0) - response.addContextualMessage("timeOff", - "reports.validate.lessThan0"); - } - - for (int i = 0; i < names.length; i++) { - locators[i].setIndex(index[i]); - - List points = getPoints(); - Iterator itr = points.iterator(); - while (itr.hasNext()) { - Dnp3PointLocatorVO loc = (Dnp3PointLocatorVO) itr.next() - .getPointLocator(); - if (loc.getDnp3DataType() == ((Dnp3PointLocatorVO) locators[i]) - .getDnp3DataType() - && loc.getIndex() == ((Dnp3PointLocatorVO) locators[i]) - .getIndex()) { - response.addContextualMessage("index", - "dsEdit.dnp3.validate.someIndexUsed"); - } - } - } - - if (response.getHasMessages()) - return response; - - for (int i = 0; i < names.length; i++) { - DataPointVO dp = getPoint(Common.NEW_ID, defaulter); - dp.setName(names[i]); - locators[i].setIndex(index[i]); - dp.setPointLocator(locators[i]); - - if (StringUtils.isEmpty(dp.getXid())) - response.addContextualMessage("xid", "validate.required"); - else if (!new DataPointDao() - .isXidUnique(dp.getXid(), Common.NEW_ID)) - response.addContextualMessage("xid", "validate.xidUsed"); - else if (StringUtils.isLengthGreaterThan(dp.getXid(), 50)) - response.addContextualMessage("xid", "validate.notLongerThan", - 50); - - locators[i].validate(response); - - if (!response.getHasMessages()) { - Common.ctx.getRuntimeManager().saveDataPoint(dp); - response.addData("id", dp.getId()); - response.addData("points", getPoints()); - } - } - return response; - } - - // - // / - // / OPC DA stuff - // / - // - @MethodFilter - public DwrResponseI18n saveOPCDataSource(String name, String xid, - String host, String domain, String user, String password, - String server, int updatePeriods, int updatePeriodType, - boolean quantize) { - OPCDataSourceVO ds = (OPCDataSourceVO) Common.getUser() - .getEditDataSource(); - ds.setXid(xid); - ds.setName(name); - ds.setHost(host); - ds.setDomain(domain); - ds.setUser(user); - ds.setPassword(password); - ds.setServer(server); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveOPCPointLocator(int id, String xid, String name, - VirtualPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - public ArrayList searchOpcServer(String host, String domain, - String user, String password) { - - Logger log = JISystem.getLogger(); - log.setLevel(Level.OFF); - - ArrayList serverList = new ArrayList(); - try { - serverList = new RealOPCMaster().listOPCServers(user, password, - host, domain); - } catch (Exception e) { - serverList.add("-1"); - serverList.add(e.getMessage()); - } - return serverList; - } - - public ArrayList listOPCTags(String host, String domain, - String user, String password, String serverName) { - - LOG.debug("List OPC Tags: " + host + ", " + domain + ", " + user + ", " - + serverName); - - ArrayList opcItems = new ArrayList(); - - try { - opcItems = new RealOPCMaster().browseOPCTags(user, password, host, - domain, serverName); - } catch (Exception e) { - LOG.warn("Error retriving OPC tags: " + e.getLocalizedMessage()); - } - - return opcItems; - } - - public OPCItem validateOPCTag(String tag, String user, String password, - String host, String domain, String servername) { - - Logger log = JISystem.getLogger(); - log.setLevel(Level.OFF); - - OPCItem opcItem = new OPCItem(tag, 0, false); - - OPCUtils utils = new OPCUtils(); - - opcItem = utils.validateTag(tag, user, password, host, domain, - servername); - return opcItem; - - } - - // public void saveOPCTags(OPCItem[] opcItems) { - // for (int i = 0; i < opcItems.length; i++) { - // OPCItem opcItem = new OPCItem("", 0, false); - // } - // } - - public DwrResponseI18n saveMultipleOPCPointLocator(String[] tags, - int[] dataTypes, boolean[] settables, OPCPointLocatorVO[] locators, - String context) { - - return validateMultipleOPCPoints(tags, dataTypes, settables, locators, - context, null); - } - - private DwrResponseI18n validateMultipleOPCPoints(String[] tags, - int[] dataTypes, boolean[] settables, OPCPointLocatorVO[] locators, - String context, DataPointDefaulter defaulter) { - DwrResponseI18n response = new DwrResponseI18n(); - OPCDataSourceVO ds = (OPCDataSourceVO) Common.getUser() - .getEditDataSource(); - if (ds.isNew()) { - response.addContextualMessage(context, - "dsEdit.opc.validate.dataSourceNotSaved"); - return response; - } - for (int i = 0; i < locators.length; i++) { - DataPointVO dp = getPoint(Common.NEW_ID, defaulter); - dp.setName(tags[i]); - locators[i].setTag(tags[i]); - locators[i].setDataTypeId(dataTypes[i]); - locators[i].setSettable(settables[i]); - dp.setPointLocator(locators[i]); - - if (StringUtils.isEmpty(dp.getXid())) - response.addContextualMessage("xid", "validate.required"); - else if (!new DataPointDao() - .isXidUnique(dp.getXid(), Common.NEW_ID)) - response.addContextualMessage("xid", "validate.xidUsed"); - else if (StringUtils.isLengthGreaterThan(dp.getXid(), 50)) - response.addContextualMessage("xid", "validate.notLongerThan", - 50); - - // locators[i].validate(response); - if (!response.getHasMessages()) { - Common.ctx.getRuntimeManager().saveDataPoint(dp); - response.addData("id", dp.getId()); - response.addData("points", getPoints()); - } - } - return response; - } - - // //// - // ASCII File Reader - // //// - - public DwrResponseI18n saveASCIIFileDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String filePath, - boolean quantize) { - - ASCIIFileDataSourceVO ds = (ASCIIFileDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setFilePath(filePath); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveASCIIFilePointLocator(int id, String xid, - String name, ASCIIFilePointLocatorVO locator) { - locator.setSettable(false); - return validatePoint(id, xid, name, locator, null); - } - - public boolean checkFile(String filePath) { - return new File(filePath).exists(); - } - - // //// - // DR_STORAGE_HT5B - // //// - - public DwrResponseI18n saveDrStorageHt5bDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String commPortId, - int baudRate, int dataBits, int stopBits, int parity, int timeout, - int retries, String initString, boolean quantize) { - - DrStorageHt5bDataSourceVO ds = (DrStorageHt5bDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setDataBits(dataBits); - ds.setStopBits(stopBits); - ds.setParity(parity); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setInitString(initString); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveDrStorageHt5bPointLocator(int id, String xid, - String name, DrStorageHt5bPointLocatorVO locator) { - locator.setSettable(false); - return validatePoint(id, xid, name, locator, null); - } - - // //// - // ASCII Serial - // //// - - public DwrResponseI18n saveASCIISerialDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String commPortId, - int baudRate, int dataBits, int stopBits, int parity, int timeout, - int retries, int stopMode, int nChar, int charStopMode, - String charX, String hexValue, int stopTimeout, String initString, - int bufferSize, boolean quantize) { - - ASCIISerialDataSourceVO ds = (ASCIISerialDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setDataBits(dataBits); - ds.setStopBits(stopBits); - ds.setParity(parity); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setStopMode(stopMode); - ds.setnChar(nChar); - ds.setCharStopMode(charStopMode); - ds.setCharX(charX); - ds.setHexValue(hexValue); - ds.setStopTimeout(stopTimeout); - ds.setInitString(initString); - ds.setBufferSize(bufferSize); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveASCIISerialPointLocator(int id, String xid, - String name, ASCIISerialPointLocatorVO locator) { - locator.setSettable(false); - return validatePoint(id, xid, name, locator, null); - } - - // - // / - // / IEC101 Serial stuff - // / - // - @MethodFilter - public DwrResponseI18n saveIEC101SerialDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, int giRelativePeriod, - int clockSynchRelativePeriod, int linkLayerAddressSize, - int linkLayerAddress, int asduAddressSize, int asduAddress, - int cotSize, int objectAddressSize, int timeout, int retries, - String commPortId, int baudRate, int dataBits, int stopBits, - int parity, boolean quantize) { - - IEC101SerialDataSourceVO ds = (IEC101SerialDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setGiRelativePeriod(giRelativePeriod); - ds.setClockSynchRelativePeriod(clockSynchRelativePeriod); - ds.setLinkLayerAddressSize(linkLayerAddressSize); - ds.setLinkLayerAddress(linkLayerAddress); - ds.setAsduAddressSize(asduAddressSize); - ds.setAsduAddress(asduAddress); - ds.setCotSize(cotSize); - ds.setObjectAddressSize(objectAddressSize); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setDataBits(dataBits); - ds.setStopBits(stopBits); - ds.setParity(parity); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveIEC101EthernetDataSource(String name, - String xid, int updatePeriods, int updatePeriodType, - int giRelativePeriod, int clockSynchRelativePeriod, - int linkLayerAddressSize, int linkLayerAddress, - int asduAddressSize, int asduAddress, int cotSize, - int objectAddressSize, int timeout, int retries, String host, - int port, boolean quantize) { - - IEC101EthernetDataSourceVO ds = (IEC101EthernetDataSourceVO) Common - .getUser().getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setGiRelativePeriod(giRelativePeriod); - ds.setClockSynchRelativePeriod(clockSynchRelativePeriod); - ds.setLinkLayerAddressSize(linkLayerAddressSize); - ds.setLinkLayerAddress(linkLayerAddress); - ds.setAsduAddressSize(asduAddressSize); - ds.setAsduAddress(asduAddress); - ds.setCotSize(cotSize); - ds.setObjectAddressSize(objectAddressSize); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setHost(host); - ds.setPort(port); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveIEC101PointLocator(int id, String xid, - String name, IEC101PointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - // - // - // Pachube stuff - // - @MethodFilter - public DwrResponseI18n savePachubeDataSource(String name, String xid, - String apiKey, int updatePeriods, int updatePeriodType, - int timeoutSeconds, int retries) { - PachubeDataSourceVO ds = (PachubeDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setApiKey(apiKey); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setTimeoutSeconds(timeoutSeconds); - ds.setRetries(retries); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n savePachubePointLocator(int id, String xid, - String name, PachubePointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public String testPachubeValueParams(String apiKey, int timeoutSeconds, - int retries, int feedId, String dataStreamId, int dataTypeId, - String binary0Value) { - try { - Map data = PachubeDataSourceRT.getData( - PachubeDataSourceRT.createHttpClient(timeoutSeconds, - retries), feedId, apiKey); - - PachubeValue pachubeValue = data.get(dataStreamId); - if (pachubeValue == null) - return getMessage(new LocalizableMessage( - "event.pachube.dataStreamNotFound", dataStreamId, - feedId)); - - MangoValue value = DataSourceUtils.getValue( - pachubeValue.getValue(), dataTypeId, binary0Value, null, - null, null); - return getMessage("common.result") + ": " + value.toString(); - } catch (LocalizableException e) { - return getMessage(e.getLocalizableMessage()); - } catch (Exception e) { - return e.getMessage(); - } - } - - // - // - // JMX stuff - // - @MethodFilter - public DwrResponseI18n saveJmxDataSource(String name, String xid, - boolean useLocalServer, String remoteServerAddr, - int updatePeriodType, int updatePeriods, boolean quantize) { - JmxDataSourceVO ds = (JmxDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUseLocalServer(useLocalServer); - ds.setRemoteServerAddr(remoteServerAddr); - ds.setUpdatePeriodType(updatePeriodType); - ds.setUpdatePeriods(updatePeriods); - ds.setQuantize(quantize); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveJmxPointLocator(int id, String xid, String name, - JmxPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - @MethodFilter - public DwrResponseI18n getJmxObjectNames(boolean useLocalServer, - String remoteServerAddr) { - DwrResponseI18n response = new DwrResponseI18n(); - JMXConnector connector = null; - - try { - MBeanServerConnection server = null; - if (useLocalServer) - server = ManagementFactory.getPlatformMBeanServer(); - else { - String url = "service:jmx:rmi:///jndi/rmi://" - + remoteServerAddr + "/jmxrmi"; - try { - connector = JMXConnectorFactory.connect(new JMXServiceURL( - url), null); - server = connector.getMBeanServerConnection(); - } catch (MalformedURLException e) { - response.addGenericMessage("dsEdit.jmx.badUrl", - e.getMessage()); - } catch (IOException e) { - response.addGenericMessage("dsEdit.jmx.connectionError", - e.getMessage()); - } - } - - if (!response.getHasMessages()) { - try { - Map names = new TreeMap(); - response.addData("names", names); - - for (ObjectName on : server.queryNames(null, null)) { - List> objectAttributesList = new ArrayList>(); - names.put(on.getCanonicalName(), objectAttributesList); - - for (MBeanAttributeInfo attr : server.getMBeanInfo(on) - .getAttributes()) { - if (attr.getType() == null) - continue; - - Map objectAttributes = new HashMap(); - try { - objectAttributes.put("name", attr.getName()); - if (attr.getType() - .equals("javax.management.openmbean.CompositeData")) { - objectAttributes.put("type", "Composite"); - CompositeData cd = (CompositeData) server - .getAttribute(on, attr.getName()); - if (cd != null) { - List> compositeItemsList = new ArrayList>(); - objectAttributes.put("items", - compositeItemsList); - for (String key : cd.getCompositeType() - .keySet()) { - Map compositeItems = new HashMap(); - compositeItemsList - .add(compositeItems); - compositeItems.put("name", key); - compositeItems - .put("type", cd - .getCompositeType() - .getType(key) - .getTypeName()); - } - } - } else - objectAttributes - .put("type", attr.getType()); - objectAttributesList.add(objectAttributes); - } catch (RuntimeMBeanException e) { - // ignore - } - } - } - } catch (Exception e) { - response.addGenericMessage("dsEdit.jmx.readError", - e.getMessage()); - LOG.warn("", e); - } - } - } finally { - try { - if (connector != null) - connector.close(); - } catch (IOException e) { - // no op - } - } - - return response; - } - - // - // - // Persistent stuff - // - @MethodFilter - public DwrResponseI18n savePersistentDataSource(String name, String xid, - int port, String authorizationKey, boolean acceptPointUpdates) { - PersistentDataSourceVO ds = (PersistentDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setPort(port); - ds.setAuthorizationKey(authorizationKey); - ds.setAcceptPointUpdates(acceptPointUpdates); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n savePersistentPointLocator(int id, String xid, - String name, PersistentPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - public DwrResponseI18n saveNodaveS7DataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String filePath, - boolean quantize, String nodaveWriteBaseCmd) { - - NodaveS7DataSourceVO ds = (NodaveS7DataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setFilePath(filePath); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setQuantize(quantize); - ds.setNodaveWriteBaseCmd(nodaveWriteBaseCmd); - - return tryDataSourceSave(ds); - - } - - @MethodFilter - public DwrResponseI18n saveNodaveS7PointLocator(int id, String xid, - String name, NodaveS7PointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - public DwrResponseI18n saveAlpha2DataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String commPortId, - int baudRate, int dataBits, int stopBits, int parity, int timeout, - int retries, int station) { - - Alpha2DataSourceVO ds = (Alpha2DataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setDataBits(dataBits); - ds.setStopBits(stopBits); - ds.setParity(parity); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - ds.setStation(station); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveAlpha2PointLocator(int id, String xid, - String name, Alpha2PointLocatorVO locator) { - - return validatePoint(id, xid, name, locator, null); - } - - // - // - // Internal stuff - // - @MethodFilter - public DwrResponseI18n saveInternalDataSource(String name, String xid, - int updatePeriods, int updatePeriodType) { - InternalDataSourceVO ds = (InternalDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveInternalPointLocator(int id, String xid, - String name, InternalPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } - - public DwrResponseI18n saveRadiuinoDataSource(String name, String xid, - int updatePeriods, int updatePeriodType, String commPortId, - int baudRate, int dataBits, int stopBits, int parity, - boolean pollingMode, int timeout, int retries) { - - RadiuinoDataSourceVO ds = (RadiuinoDataSourceVO) Common.getUser() - .getEditDataSource(); - - ds.setXid(xid); - ds.setName(name); - ds.setCommPortId(commPortId); - ds.setBaudRate(baudRate); - ds.setDataBits(dataBits); - ds.setStopBits(stopBits); - ds.setParity(parity); - ds.setPollingMode(pollingMode); - ds.setTimeout(timeout); - ds.setRetries(retries); - ds.setUpdatePeriods(updatePeriods); - ds.setUpdatePeriodType(updatePeriodType); - - return tryDataSourceSave(ds); - } - - @MethodFilter - public DwrResponseI18n saveRadiuinoPointLocator(int id, String xid, - String name, RadiuinoPointLocatorVO locator) { - return validatePoint(id, xid, name, locator, null); - } + return response; + } + + @MethodFilter + public void cancelTestingUtility() { + Common.getUser().cancelTestingUtility(); + } + + @MethodFilter + public List enableAllPoints() { + User user = Common.getUser(); + if (user == null) + return null; + + DataSourceVO ds = user.getEditDataSource(); + if (ds.getId() == Common.NEW_ID) + return null; + + List points = new DataPointDao().getDataPoints(ds.getId(), + DataPointNameComparator.instance); + for (DataPointVO dataPointVO : points) { + if (!dataPointVO.isEnabled()) { + Permissions.ensureDataSourcePermission(Common.getUser(), + dataPointVO.getDataSourceId()); + + RuntimeManager runtimeManager = Common.ctx.getRuntimeManager(); + dataPointVO.setEnabled(true); + runtimeManager.saveDataPoint(dataPointVO); + } + } + return points; + } + + @MethodFilter + public List getPoints() { + User user = Common.getUser(); + if (user == null) + return null; + + DataSourceVO ds = user.getEditDataSource(); + if (ds.getId() == Common.NEW_ID) + return null; + + List points = new DataPointDao().getDataPoints(ds.getId(), + DataPointNameComparator.instance); + return points; + } + + @MethodFilter + public DataPointVO getPoint(int pointId) { + return getPoint(pointId, null); + } + + private DataPointVO getPoint(int pointId, DataPointDefaulter defaulter) { + DataSourceVO ds = Common.getUser().getEditDataSource(); + + DataPointVO dp; + if (pointId == Common.NEW_ID) { + dp = new DataPointVO(); + dp.setXid(new DataPointDao().generateUniqueXid()); + dp.setDataSourceId(ds.getId()); + dp.setPointLocator(ds.createPointLocator()); + dp.setEventDetectors(new ArrayList(0)); + if (defaulter != null) + defaulter.setDefaultValues(dp); + } else { + dp = new DataPointDao().getDataPoint(pointId); + if (dp != null && dp.getDataSourceId() != ds.getId()) + throw new RuntimeException("Data source id mismatch"); + } + + return dp; + } + + private DwrResponseI18n validatePoint(int id, String xid, String name, + PointLocatorVO locator, DataPointDefaulter defaulter) { + DwrResponseI18n response = new DwrResponseI18n(); + + DataPointVO dp = getPoint(id, defaulter); + dp.setXid(xid); + dp.setName(name); + dp.setPointLocator(locator); + + if (StringUtils.isEmpty(xid)) + response.addContextualMessage("xid", "validate.required"); + else if (!new DataPointDao().isXidUnique(xid, id)) + response.addContextualMessage("xid", "validate.xidUsed"); + else if (StringUtils.isLengthGreaterThan(xid, 50)) + response.addContextualMessage("xid", "validate.notLongerThan", 50); + + if (StringUtils.isEmpty(name)) + response.addContextualMessage("name", "dsEdit.validate.required"); + + locator.validate(response); + + if (!response.getHasMessages()) { + Common.ctx.getRuntimeManager().saveDataPoint(dp); + response.addData("id", dp.getId()); + response.addData("points", getPoints()); + } + + return response; + } + + @MethodFilter + public List deletePoint(int id) { + DataPointVO dp = getPoint(id, null); + if (dp != null) + Common.ctx.getRuntimeManager().deleteDataPoint(dp); + + return getPoints(); + } + + @MethodFilter + public Map toggleEditDataSource() { + DataSourceVO ds = Common.getUser().getEditDataSource(); + return super.toggleDataSource(ds.getId()); + } + + @MethodFilter + public DwrResponseI18n togglePoint(int dataPointId) { + DwrResponseI18n response = super.toggleDataPoint(dataPointId); + response.addData("points", getPoints()); + return response; + } + + @MethodFilter + public List getAlarms() { + DataSourceVO ds = Common.getUser().getEditDataSource(); + List events = new EventDao() + .getPendingEventsForDataSource(ds.getId(), Common.getUser() + .getId()); + Collections.sort(events, new Comparator() { + @Override + public int compare(EventInstance lhs, EventInstance rhs) { + // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending + return lhs.getActiveTimestamp() > rhs.getActiveTimestamp() ? -1 : (lhs.getActiveTimestamp() < rhs.getActiveTimestamp()) ? 1 : 0; + } + }); + List beans = new ArrayList(); + if (events != null) { + for (EventInstance event : events) + beans.add(new EventInstanceBean(event.isActive(), event + .getAlarmLevel(), DateFunctions.getTime(event + .getActiveTimestamp()), getMessage(event.getMessage()))); + } + return beans; + } + + @MethodFilter + public void updateEventAlarmLevel(int eventId, int alarmLevel) { + DataSourceVO ds = Common.getUser().getEditDataSource(); + ds.setAlarmLevel(eventId, alarmLevel); + } + + // + // + // Virtual stuff + // + @MethodFilter + public DwrResponseI18n saveVirtualDataSource(String name, String xid, + int updatePeriods, int updatePeriodType) { + VirtualDataSourceVO ds = (VirtualDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public IntMessagePair[] getChangeTypes(int dataTypeId) { + return ChangeTypeVO.getChangeTypes(dataTypeId); + } + + @MethodFilter + public DwrResponseI18n saveVirtualPointLocator(int id, String xid, + String name, VirtualPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + // + // + // Modbus common stuff + // + @MethodFilter + public Map modbusScanUpdate() { + Map result = new HashMap(); + ModbusNodeScanListener scan = Common.getUser().getTestingUtility( + ModbusNodeScanListener.class); + if (scan == null) + return null; + + result.put("nodes", scan.getNodesFound()); + result.put("message", scan.getMessage()); + result.put("finished", scan.isFinished()); + + return result; + } + + @MethodFilter + public DwrResponseI18n saveModbusPointLocator(int id, String xid, + String name, ModbusPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + private void testModbusPointLocator(ModbusMaster modbusMaster, + ModbusPointLocatorVO locator, boolean serial, + DwrResponseI18n response) { + locator.validate(response); + if (response.getHasMessages()) + return; + + try { + BaseLocator bl = ModbusDataSource.createModbusLocator(locator); + modbusMaster.init(); + Object result = modbusMaster.getValue(bl); + response.addData("result", new LocalizableMessage( + "dsEdit.modbus.locatorTest.result", result)); + } catch (ModbusInitException e) { + if (serial) + response.addMessage(new LocalizableMessage( + "dsEdit.modbus.locatorTestIp.startError", e + .getMessage())); + else + response.addMessage(new LocalizableMessage( + "dsEdit.modbus.locatorTestSerial.startError", e + .getMessage())); + } catch (ErrorResponseException e) { + response.addMessage(new LocalizableMessage("common.default", e + .getErrorResponse().getExceptionMessage())); + } catch (ModbusTransportException e) { + response.addMessage(ModbusDataSource.localExceptionMessage(e)); + } catch (IllegalCharsetNameException e) { + response.addMessage(new LocalizableMessage( + "validate.invalidCharset")); + } finally { + modbusMaster.destroy(); + } + } + + private void testModbusData(ModbusMaster modbusMaster, int slaveId, + int range, int offset, int length, boolean serial, + DwrResponseI18n response) { + boolean binary = range == RegisterRange.COIL_STATUS + || range == RegisterRange.INPUT_STATUS; + if (length > modbusMaster.getMaxReadCount(range)) + length = modbusMaster.getMaxReadCount(range); + if (offset + length > 65536) + length = 65536 - offset; + response.addData("length", length); + + try { + ModbusRequest mreq = new ModbusFactory().createReadRequest(slaveId, + range, offset, length); + + modbusMaster.init(); + ReadResponse mres = (ReadResponse) modbusMaster.send(mreq); + if (mres.isException()) + response.addMessage(new LocalizableMessage("common.default", + mres.getExceptionMessage())); + else { + List results = new ArrayList(); + if (binary) { + boolean[] data = mres.getBooleanData(); + for (int i = 0; i < length; i++) + results.add(Integer.toString(offset + i) + " ==> " + + Boolean.toString(data[i])); + } else { + short[] data = mres.getShortData(); + for (int i = 0; i < length; i++) + results.add(Integer.toString(offset + i) + " ==> " + + StreamUtils.toHex(data[i])); + } + response.addData("results", results); + } + } catch (ModbusIdException e) { + response.addMessage(ModbusDataSource.localExceptionMessage(e)); + } catch (ModbusInitException e) { + if (serial) + response.addMessage(new LocalizableMessage( + "dsEdit.modbus.locatorTestIp.startError", e + .getMessage())); + else + response.addMessage(new LocalizableMessage( + "dsEdit.modbus.locatorTestSerial.startError", e + .getMessage())); + } catch (ModbusTransportException e) { + response.addMessage(ModbusDataSource.localExceptionMessage(e)); + } finally { + modbusMaster.destroy(); + } + } + + // + // + // Modbus serial stuff + // + @MethodFilter + public DwrResponseI18n saveModbusSerialDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, boolean quantize, + int timeout, int retries, boolean contiguousBatches, + boolean createSlaveMonitorPoints, int maxReadBitCount, + int maxReadRegisterCount, int maxWriteRegisterCount, + String commPortId, int baudRate, int flowControlIn, + int flowControlOut, int dataBits, int stopBits, int parity, + String encoding, boolean echo, int concurrency) { + ModbusSerialDataSourceVO ds = (ModbusSerialDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setQuantize(quantize); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setContiguousBatches(contiguousBatches); + ds.setCreateSlaveMonitorPoints(createSlaveMonitorPoints); + ds.setMaxReadBitCount(maxReadBitCount); + ds.setMaxReadRegisterCount(maxReadRegisterCount); + ds.setMaxWriteRegisterCount(maxWriteRegisterCount); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setFlowControlIn(flowControlIn); + ds.setFlowControlOut(flowControlOut); + ds.setDataBits(dataBits); + ds.setStopBits(stopBits); + ds.setParity(parity); + ds.setEncodingStr(encoding); + ds.setEcho(echo); + ds.setConcurrency(concurrency); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public String modbusSerialScan(int timeout, int retries, String commPortId, + int baudRate, int flowControlIn, int flowControlOut, int dataBits, + int stopBits, int parity, String encoding, int concurrency) { + ModbusMaster modbusMaster; + try { + modbusMaster = createModbusSerialMaster(timeout, retries, + commPortId, baudRate, flowControlIn, flowControlOut, + dataBits, stopBits, parity, encoding, concurrency); + } catch (Exception e) { + return getMessage("dsEdit.modbus.scanError"); + } + ModbusNodeScanListener scan = new ModbusNodeScanListener( + getResourceBundle(), modbusMaster, true); + Common.getUser().setTestingUtility(scan); + return null; + } + + @MethodFilter + public DwrResponseI18n testModbusSerialLocator(int timeout, int retries, + String commPortId, int baudRate, int flowControlIn, + int flowControlOut, int dataBits, int stopBits, int parity, + String encoding, int concurrency, ModbusPointLocatorVO locator) { + DwrResponseI18n response = new DwrResponseI18n(); + ModbusMaster modbusMaster; + try { + modbusMaster = createModbusSerialMaster(timeout, retries, + commPortId, baudRate, flowControlIn, flowControlOut, + dataBits, stopBits, parity, encoding, concurrency); + testModbusPointLocator(modbusMaster, locator, true, response); + } catch (Exception e) { + response.addMessage(new LocalizableMessage( + "dsEdit.modbus.scanError")); + } + return response; + } + + @MethodFilter + public DwrResponseI18n testModbusSerialData(int timeout, int retries, + String commPortId, int baudRate, int flowControlIn, + int flowControlOut, int dataBits, int stopBits, int parity, + String encoding, int concurrency, int slaveId, int range, + int offset, int length) { + DwrResponseI18n response = new DwrResponseI18n(); + ModbusMaster modbusMaster; + try { + modbusMaster = createModbusSerialMaster(timeout, retries, + commPortId, baudRate, flowControlIn, flowControlOut, + dataBits, stopBits, parity, encoding, concurrency); + testModbusData(modbusMaster, slaveId, range, offset, length, true, + response); + } catch (Exception e) { + response.addMessage(new LocalizableMessage( + "dsEdit.modbus.scanError")); + } + return response; + } + + private ModbusMaster createModbusSerialMaster(int timeout, int retries, + String commPortId, int baudRate, int flowControlIn, + int flowControlOut, int dataBits, int stopBits, int parity, + String encoding, int concurrency) throws Exception { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + if (StringUtils.isEmpty(commPortId)) + throw new Exception(); + + SerialParameters params = new SerialParameters(); + params.setCommPortId(commPortId); + params.setPortOwnerName("Mango Modbus Serial Data Source Scan"); + params.setBaudRate(baudRate); + params.setFlowControlIn(flowControlIn); + params.setFlowControlOut(flowControlOut); + params.setDataBits(dataBits); + params.setStopBits(stopBits); + params.setParity(parity); + + EncodingType encodingType = EncodingType.valueOf(encoding); + + ModbusMaster modbusMaster; + if (encodingType == EncodingType.ASCII) + modbusMaster = new ModbusFactory().createAsciiMaster(params); + else + modbusMaster = new ModbusFactory().createRtuMaster(params); + modbusMaster.setTimeout(timeout); + modbusMaster.setRetries(retries); + + return modbusMaster; + } + + // + // + // Modbus IP stuff + // + @MethodFilter + public DwrResponseI18n saveModbusIpDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, boolean quantize, + int timeout, int retries, boolean contiguousBatches, + boolean createSlaveMonitorPoints, int maxReadBitCount, + int maxReadRegisterCount, int maxWriteRegisterCount, + String transportType, String host, int port, boolean encapsulated, + boolean createSocketMonitorPoint) { + ModbusIpDataSourceVO ds = (ModbusIpDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setQuantize(quantize); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setContiguousBatches(contiguousBatches); + ds.setCreateSlaveMonitorPoints(createSlaveMonitorPoints); + ds.setMaxReadBitCount(maxReadBitCount); + ds.setMaxReadRegisterCount(maxReadRegisterCount); + ds.setMaxWriteRegisterCount(maxWriteRegisterCount); + ds.setTransportTypeStr(transportType); + ds.setHost(host); + ds.setPort(port); + ds.setEncapsulated(encapsulated); + ds.setCreateSocketMonitorPoint(createSocketMonitorPoint); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public String modbusIpScan(int timeout, int retries, String transport, + String host, int port, boolean encapsulated) { + ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries, + transport, host, port, encapsulated); + ModbusNodeScanListener scan = new ModbusNodeScanListener( + getResourceBundle(), modbusMaster, false); + Common.getUser().setTestingUtility(scan); + return null; + } + + @MethodFilter + public DwrResponseI18n testModbusIpLocator(int timeout, int retries, + String transport, String host, int port, boolean encapsulated, + ModbusPointLocatorVO locator) { + DwrResponseI18n response = new DwrResponseI18n(); + ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries, + transport, host, port, encapsulated); + testModbusPointLocator(modbusMaster, locator, false, response); + return response; + } + + @MethodFilter + public DwrResponseI18n testModbusIpData(int timeout, int retries, + String transport, String host, int port, boolean encapsulated, + int slaveId, int range, int offset, int length) { + DwrResponseI18n response = new DwrResponseI18n(); + ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries, + transport, host, port, encapsulated); + testModbusData(modbusMaster, slaveId, range, offset, length, false, + response); + return response; + } + + private ModbusMaster createModbusIpMaster(int timeout, int retries, + String transport, String host, int port, boolean encapsulated) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + IpParameters params = new IpParameters(); + params.setHost(host); + params.setPort(port); + params.setEncapsulated(encapsulated); + + TransportType transportType = TransportType.valueOf(transport); + + ModbusMaster modbusMaster; + if (transportType == TransportType.TCP_LISTENER) + modbusMaster = new ModbusFactory().createTcpListener(params); + else if (transportType == TransportType.UDP) + modbusMaster = new ModbusFactory().createUdpMaster(params); + else + modbusMaster = new ModbusFactory().createTcpMaster(params, + transportType == TransportType.TCP_KEEP_ALIVE); + modbusMaster.setTimeout(timeout); + modbusMaster.setRetries(retries); + + return modbusMaster; + } + + // + // + // SNMP stuff + // + @MethodFilter + public DwrResponseI18n saveSnmpDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String host, int port, + int snmpVersion, String community, String securityName, + String authProtocol, String authPassphrase, String privProtocol, + String privPassphrase, int securityLevel, String contextName, + int retries, int timeout, boolean trapEnabled, int trapPort, + String localAddress) { + SnmpDataSourceVO ds = (SnmpDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setHost(host); + ds.setPort(port); + ds.setSnmpVersion(snmpVersion); + ds.setCommunity(community); + ds.setSecurityName(securityName); + ds.setAuthProtocol(authProtocol); + ds.setAuthPassphrase(authPassphrase); + ds.setPrivProtocol(privProtocol); + ds.setPrivPassphrase(privPassphrase); + ds.setSecurityLevel(securityLevel); + ds.setContextName(contextName); + ds.setRetries(retries); + ds.setTimeout(timeout); + ds.setTrapEnabled(trapEnabled); + ds.setTrapPort(trapPort); + ds.setLocalAddress(localAddress); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveSnmpPointLocator(int id, String xid, + String name, SnmpPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public void snmpGetOid(String oid, String host, int port, int snmpVersion, + String community, String securityName, String authProtocol, + String authPassphrase, String privProtocol, String privPassphrase, + int securityLevel, String contextName, + int retries, int timeout) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + Version version = Version.getVersion(snmpVersion, community, + securityName, authProtocol, authPassphrase, privProtocol, + privPassphrase, securityLevel, contextName); + user.setTestingUtility(new SnmpOidGet(getResourceBundle(), host, port, + version, oid, retries, timeout)); + } + + @MethodFilter + public void snmpWalkOid(String oid, String host, int port, int snmpVersion, + String community, String securityName, String authProtocol, + String authPassphrase, String privProtocol, String privPassphrase, + int securityLevel, String contextName, + int retries, int timeout) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + Version version = Version.getVersion(snmpVersion, community, + securityName, authProtocol, authPassphrase, privProtocol, + privPassphrase, securityLevel, contextName); +// user.setTestingUtility(new SnmpOidWalk(getResourceBundle(), host, port, +// version, oid, retries, timeout)); + } + + @MethodFilter + public String snmpGetOidUpdate() { + SnmpOidGet snmpOidGet = Common.getUser().getTestingUtility( + SnmpOidGet.class); + if (snmpOidGet == null) + return null; + return snmpOidGet.getResult(); + } + +// @MethodFilter +// public String snmpGetWalkUpdate() { +// SnmpOidWalk snmpOidWalk = Common.getUser().getTestingUtility( +// SnmpOidWalk.class); +// if (snmpOidWalk == null) +// return null; +// return snmpOidWalk.getResult(); +// } + + // + // + // SQL stuff + // + @MethodFilter + public DwrResponseI18n saveSqlDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String driverClassname, + String connectionUrl, String username, String password, + String selectStatement, boolean rowBasedQuery) { + SqlDataSourceVO ds = (SqlDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setDriverClassname(driverClassname); + ds.setConnectionUrl(connectionUrl); + ds.setUsername(username); + ds.setPassword(password); + ds.setSelectStatement(selectStatement); + ds.setRowBasedQuery(rowBasedQuery); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveSqlPointLocator(int id, String xid, String name, + SqlPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public void sqlTestStatement(String driverClassname, String connectionUrl, + String username, String password, String selectStatement, + boolean rowBasedQuery) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + user.setTestingUtility(new SqlStatementTester(getResourceBundle(), + driverClassname, connectionUrl, username, password, + selectStatement, rowBasedQuery)); + } + + @MethodFilter + public Map sqlTestStatementUpdate() { + Map result = new HashMap(); + SqlStatementTester statementTester = Common.getUser() + .getTestingUtility(SqlStatementTester.class); + if (statementTester == null) + return null; + if (!statementTester.isDone()) + return null; + + if (statementTester.getErrorMessage() != null) + result.put("error", statementTester.getErrorMessage()); + else + result.put("resultTable", statementTester.getResultTable()); + return result; + } + + // + // + // HTTP receiver stuff + // + @MethodFilter + public DwrResponseI18n saveHttpReceiverDataSource(String name, String xid, + String[] ipWhiteList, String[] deviceIdWhiteList) { + HttpReceiverDataSourceVO ds = (HttpReceiverDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setIpWhiteList(ipWhiteList); + ds.setDeviceIdWhiteList(deviceIdWhiteList); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveHttpReceiverPointLocator(int id, String xid, + String name, HttpReceiverPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public void httpReceiverListenForData(String[] ipWhiteList, + String[] deviceIdWhiteList) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + user.setTestingUtility(new HttpReceiverDataListener( + getResourceBundle(), ipWhiteList, deviceIdWhiteList)); + } + + @MethodFilter + public Map httpReceiverListenerUpdate() { + Map result = new HashMap(); + HttpReceiverDataListener l = Common.getUser().getTestingUtility( + HttpReceiverDataListener.class); + if (l == null) + return null; + + HttpReceiverData data = l.getData(); + if (data != null) { + result.put("remoteIp", data.getRemoteIp()); + result.put("deviceId", data.getDeviceId()); + result.put("time", DateFunctions.getTime(data.getTime())); + result.put("data", data.getData()); + } + result.put("message", l.getMessage()); + + return result; + } + + @MethodFilter + public String validateIpMask(String ipMask) { + return IpAddressUtils.checkIpMask(ipMask); + } + + // + // + // OneWire stuff + // + @MethodFilter + public DwrResponseI18n saveOneWireDataSource(String name, String xid, + String commPortId, int updatePeriodType, int updatePeriods, + int rescanPeriodType, int rescanPeriods) { + OneWireDataSourceVO ds = (OneWireDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setUpdatePeriodType(updatePeriodType); + ds.setUpdatePeriods(updatePeriods); + ds.setRescanPeriodType(rescanPeriodType); + ds.setRescanPeriods(rescanPeriods); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveOneWirePointLocator(int id, String xid, + String name, OneWirePointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public DwrResponseI18n readOneWireNetwork(String commPointId) { + DwrResponseI18n response = new DwrResponseI18n(); + + Network network = null; + try { + // Check for an RT that already has a network. + OneWireDataSourceVO ds = (OneWireDataSourceVO) Common.getUser() + .getEditDataSource(); + OneWireDataSourceRT rt = (OneWireDataSourceRT) Common.ctx + .getRuntimeManager().getRunningDataSource(ds.getId()); + if (rt != null) + // Use the existing one if it exists (i.e. initialized properly) + network = rt.getNetwork(); + + if (network == null) + // Create a new one. + network = new Network(commPointId); + + try { + network.lock(); + network.quickInitialize(); + + List addresses = network.getAddresses(); + List devices = new ArrayList(); + for (Long address : addresses) { + NetworkPath path = network.getNetworkPath(address); + if (!path.isCoupler()) + devices.add(path.getTargetInfo()); + } + + response.addData("devices", devices); + } finally { + network.unlock(); + } + } catch (Exception e) { + response.addGenericMessage("common.default", e.getMessage()); + } finally { + try { + if (network != null) + network.terminate(); + } catch (OneWireException e) { + // no op + } + } + + return response; + } + + @MethodFilter + public DataPointVO addOneWirePoint(String address) { + DataPointVO dp = getPoint(Common.NEW_ID, null); + OneWirePointLocatorVO locator = dp.getPointLocator(); + locator.setAddress(address); + return dp; + } + + // + // + // Meta stuff + // + @MethodFilter + public DwrResponseI18n saveMetaDataSource(String name, String xid) { + MetaDataSourceVO ds = (MetaDataSourceVO) Common.getUser() + .getEditDataSource(); + ds.setXid(xid); + ds.setName(name); + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveMetaPointLocator(int id, String xid, + String name, MetaPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public DwrResponseI18n validateScript(String script, + List context, int dataTypeId) { + DwrResponseI18n response = new DwrResponseI18n(); + + ScriptExecutor executor = new ScriptExecutor(); + try { + Map convertedContext = executor + .convertContext(context); + PointValueTime pvt = executor.execute(script, convertedContext, + System.currentTimeMillis(), dataTypeId, -1); + if (pvt.getTime() == -1) + response.addContextualMessage("script", + "dsEdit.meta.test.success", pvt.getValue()); + else + response.addContextualMessage("script", + "dsEdit.meta.test.successTs", pvt.getValue(), + DateFunctions.getTime(pvt.getTime())); + } catch (DataPointStateException e) { + response.addMessage("context", e.getLocalizableMessage()); + } catch (ScriptException e) { + response.addContextualMessage("script", + "dsEdit.meta.test.scriptError", e.getMessage()); + } catch (ResultTypeException e) { + response.addMessage("script", e.getLocalizableMessage()); + } + + return response; + } + + // + // + // BACnet I/P stuff + // + @MethodFilter + public DwrResponseI18n saveBACnetIpDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, int deviceId, + String broadcastAddress, int port, int timeout, int segTimeout, + int segWindow, int retries, int covSubscriptionTimeoutMinutes, + int maxReadMultipleReferencesSegmented, + int maxReadMultipleReferencesNonsegmented) { + BACnetIPDataSourceVO ds = (BACnetIPDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setDeviceId(deviceId); + ds.setBroadcastAddress(broadcastAddress); + ds.setPort(port); + ds.setTimeout(timeout); + ds.setSegTimeout(segTimeout); + ds.setSegWindow(segWindow); + ds.setRetries(retries); + ds.setCovSubscriptionTimeoutMinutes(covSubscriptionTimeoutMinutes); + ds.setMaxReadMultipleReferencesSegmented(maxReadMultipleReferencesSegmented); + ds.setMaxReadMultipleReferencesNonsegmented(maxReadMultipleReferencesNonsegmented); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveBACnetIPPointLocator(int id, String xid, + String name, BACnetIPPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public void sendBACnetWhoIs(int deviceId, String broadcastAddress, + int port, int timeout, int segTimeout, int segWindow, int retries, + int whoIsPort, int maxReadMultipleReferencesSegmented, + int maxReadMultipleReferencesNonsegmented) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + BACnetDiscovery whoIs = new BACnetDiscovery(getResourceBundle(), + deviceId, broadcastAddress, port, timeout, segTimeout, + segWindow, retries, whoIsPort, + maxReadMultipleReferencesSegmented, + maxReadMultipleReferencesNonsegmented); + user.setTestingUtility(whoIs); + } + + @MethodFilter + public Map bacnetWhoIsUpdate() { + Map result = new HashMap(); + BACnetDiscovery test = Common.getUser().getTestingUtility( + BACnetDiscovery.class); + if (test == null) + return null; + + test.addUpdateInfo(result); + + return result; + } + + @MethodFilter + public int getBACnetDeviceDetails(int index) { + BACnetDiscovery test = Common.getUser().getTestingUtility( + BACnetDiscovery.class); + if (test == null) + return index; + test.getDeviceDetails(index); + return -1; + } + + @MethodFilter + public DwrResponseI18n sendObjectListRequest(int deviceId, + String broadcastAddress, int port, int timeout, int segTimeout, + int segWindow, int retries, int maxReadMultipleReferencesSegmented, + int maxReadMultipleReferencesNonsegmented, String remoteIp, + int remotePort, int networkNumber, String networkAddress, + int remoteDeviceId) { + LocalDevice localDevice = new LocalDevice(deviceId, broadcastAddress); + localDevice.setPort(port); + localDevice.setTimeout(timeout); + localDevice.setSegTimeout(segTimeout); + localDevice.setSegWindow(segWindow); + localDevice.setRetries(retries); + localDevice + .setMaxReadMultipleReferencesSegmented(maxReadMultipleReferencesSegmented); + localDevice + .setMaxReadMultipleReferencesNonsegmented(maxReadMultipleReferencesNonsegmented); + + DwrResponseI18n result = new DwrResponseI18n(); + try { + localDevice.initialize(); + + Address address = new Address(InetAddress.getByName(remoteIp) + .getAddress(), remotePort); + com.serotonin.bacnet4j.Network network = null; + if (!StringUtils.isEmpty(networkAddress)) + network = new com.serotonin.bacnet4j.Network(networkNumber, + networkAddress); + RemoteDevice d = localDevice.findRemoteDevice(address, network, + remoteDeviceId); + + List details = BACnetDiscovery.getDetails( + localDevice, d); + + result.addData("deviceAddress", d.getAddress().toIpString()); + result.addData("deviceName", d.getName()); + result.addData("deviceIp", d.getAddress().toIpString()); + result.addData("devicePort", d.getAddress().getPort()); + network = d.getNetwork(); + if (network != null) { + result.addData("deviceNetworkNumber", + network.getNetworkNumber()); + result.addData("deviceNetworkAddress", + network.getNetworkAddressDottedString()); + } + result.addData("deviceInstanceNumber", d.getObjectIdentifier() + .getInstanceNumber()); + result.addData("deviceDescription", + BACnetDiscovery.getDeviceDescription(d)); + result.addData("deviceDetails", details); + } catch (Exception e) { + result.addData("error", e.getMessage()); + } finally { + localDevice.terminate(); + } + + return result; + } + + @MethodFilter + public DataPointVO addBacnetPoint(String ip, int port, int networkNumber, + String networkAddress, int deviceInstanceNumber, + BACnetObjectBean bean) { + DataPointVO dp = getPoint(Common.NEW_ID, null); + BACnetIPPointLocatorVO locator = dp.getPointLocator(); + + dp.setName(bean.getObjectName()); + + // Default some of the locator values. + locator.setRemoteDeviceIp(ip); + locator.setRemoteDevicePort(port); + locator.setNetworkNumber(networkNumber); + locator.setNetworkAddress(networkAddress); + locator.setRemoteDeviceInstanceNumber(deviceInstanceNumber); + locator.setObjectTypeId(bean.getObjectTypeId()); + locator.setObjectInstanceNumber(bean.getInstanceNumber()); + locator.setPropertyIdentifierId(PropertyIdentifier.presentValue + .intValue()); + locator.setDataTypeId(bean.getDataTypeId()); + locator.setUseCovSubscription(bean.isCov()); + + // We would like to default text renderer values too, but it's rather + // inconvenient to do. + + return dp; + } + + // + // + // HTTP Retriever stuff + // + @MethodFilter + public DwrResponseI18n saveHttpRetrieverDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String url, + int timeoutSeconds, int retries, boolean stop) { + HttpRetrieverDataSourceVO ds = (HttpRetrieverDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setUrl(url); + ds.setTimeoutSeconds(timeoutSeconds); + ds.setRetries(retries); + ds.setStop(stop); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveHttpRetrieverDataSourceWithReactivationOptions(String name, String xid, + int updatePeriods, int updatePeriodType, String url, + int timeoutSeconds, int retries, boolean stop, boolean sleep, short typeReactivation, short valueReactivation) { + HttpRetrieverDataSourceVO ds = (HttpRetrieverDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setUrl(url); + ds.setTimeoutSeconds(timeoutSeconds); + ds.setRetries(retries); + ds.setStop(stop); + ReactivationDs rDs = new ReactivationDs(sleep, typeReactivation, valueReactivation); + ds.setReactivation(rDs); + + DwrResponseI18n result; + + if (ds.getId() > 0) { + ReactivationManager.getInstance().stopReactivation(ds.getId()); + } + result = tryDataSourceSave(ds); + + if (sleep) { + ReactivationManager.getInstance().startReactivation(ds.getId()); + } + + return result; + } + + + @MethodFilter + public DwrResponseI18n saveHttpRetrieverPointLocator(int id, String xid, + String name, HttpRetrieverPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public String testHttpRetrieverValueParams(String url, int timeoutSeconds, + int retries, String valueRegex, int dataTypeId, String valueFormat) { + try { + String data = HttpRetrieverDataSourceRT.getData(url, + timeoutSeconds, retries); + + Pattern valuePattern = Pattern.compile(valueRegex); + DecimalFormat decimalFormat = null; + if (dataTypeId == DataTypes.NUMERIC + && !StringUtils.isEmpty(valueFormat)) + decimalFormat = new DecimalFormat(valueFormat); + MangoValue value = DataSourceUtils.getValue(valuePattern, data, + dataTypeId, valueFormat, null, decimalFormat, null); + return getMessage("common.result") + ": " + value.toString(); + } catch (LocalizableException e) { + return getMessage(e.getLocalizableMessage()); + } catch (Exception e) { + return e.getMessage(); + } + } + + @MethodFilter + public String testHttpRetrieverTimeParams(String url, int timeoutSeconds, + int retries, String timeRegex, String timeFormat) { + try { + String data = HttpRetrieverDataSourceRT.getData(url, + timeoutSeconds, retries); + + Pattern timePattern = Pattern.compile(timeRegex); + DateFormat dateFormat = new SimpleDateFormat(timeFormat); + long time = DataSourceUtils.getValueTime( + System.currentTimeMillis(), timePattern, data, dateFormat, + null); + return DateFunctions.getTime(time); + } catch (LocalizableException e) { + return getMessage(e.getLocalizableMessage()); + } catch (Exception e) { + return e.getMessage(); + } + } + + // + // + // HTTP Image stuff + // + @MethodFilter + public DwrResponseI18n saveHttpImageDataSource(String name, String xid, + int updatePeriods, int updatePeriodType) { + HttpImageDataSourceVO ds = (HttpImageDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveHttpImagePointLocator(int id, String xid, + String name, HttpImagePointLocatorVO locator) { + return validatePoint(id, xid, name, locator, new DataPointDefaulter() { + @Override + public void setDefaultValues(DataPointVO dp) { + if (dp.isNew()) + dp.setLoggingType(DataPointVO.LoggingTypes.NONE); + } + }); + } + + // + // + // POP3 Email stuff + // + @MethodFilter + public DwrResponseI18n savePop3DataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String pop3Server, + String username, String password) { + Pop3DataSourceVO ds = (Pop3DataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setPop3Server(pop3Server); + ds.setUsername(username); + ds.setPassword(password); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n savePop3PointLocator(int id, String xid, + String name, Pop3PointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public String testPop3ValueParams(String testData, String valueRegex, + int dataTypeId, String valueFormat) { + try { + Pattern valuePattern = Pattern.compile(valueRegex); + DecimalFormat decimalFormat = null; + if (dataTypeId == DataTypes.NUMERIC + && !StringUtils.isEmpty(valueFormat)) + decimalFormat = new DecimalFormat(valueFormat); + MangoValue value = DataSourceUtils.getValue(valuePattern, testData, + dataTypeId, valueFormat, null, decimalFormat, null); + return getMessage("common.result") + ": " + value.toString(); + } catch (LocalizableException e) { + return getMessage(e.getLocalizableMessage()); + } catch (Exception e) { + return e.getMessage(); + } + } + + @MethodFilter + public String testPop3TimeParams(String testData, String timeRegex, + String timeFormat) { + try { + Pattern timePattern = Pattern.compile(timeRegex); + DateFormat dateFormat = new SimpleDateFormat(timeFormat); + long time = DataSourceUtils.getValueTime( + System.currentTimeMillis(), timePattern, testData, + dateFormat, null); + return DateFunctions.getTime(time); + } catch (Exception e) { + return e.getMessage(); + } + } + + // + // + // NMEA stuff + // + @MethodFilter + public DwrResponseI18n saveNmeaDataSource(String name, String xid, + String commPortId, int baudRate, int resetTimeout) { + NmeaDataSourceVO ds = (NmeaDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setResetTimeout(resetTimeout); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveNmeaPointLocator(int id, String xid, + String name, NmeaPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public void nmeaListenForMessages(String commPortId, int baudRate) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + user.setTestingUtility(new NmeaUtilListener(getResourceBundle(), + commPortId, baudRate)); + } + + @MethodFilter + public Map nmeaListenerUpdate() { + NmeaUtilListener l = Common.getUser().getTestingUtility( + NmeaUtilListener.class); + if (l == null) + return null; + + Map result = new HashMap(); + result.put("messages", l.getMessages()); + result.put("message", l.getMessage()); + + return result; + } + + // + // + // Galil stuff + // + @MethodFilter + public DwrResponseI18n saveGalilDataSource(String name, String xid, + String host, int port, int timeout, int retries, int updatePeriods, + int updatePeriodType) { + GalilDataSourceVO ds = (GalilDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setHost(host); + ds.setPort(port); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveGalilPointLocator(int id, String xid, + String name, GalilPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public String galilTestCommand(String host, int port, int timeout, + String command) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + try { + GalilCommandTester tester = new GalilCommandTester( + getResourceBundle(), host, port, timeout, command); + try { + tester.join(); + return tester.getResult(); + } catch (InterruptedException e) { + return e.getMessage(); + } + } catch (IOException e) { + return e.getMessage(); + } + } + + // + // + // EBI25 stuff + // + @MethodFilter + public DwrResponseI18n saveEBI25DataSource(String name, String xid, + int updatePeriods, int updatePeriodType, int timeout, int retries, + String host, int port, boolean keepAlive) { + EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setHost(host); + ds.setPort(port); + ds.setKeepAlive(keepAlive); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public EBI25InterfaceReader ebi25ReadInterface(String host, int port, + boolean keepAlive, int timeout, int retries) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser() + .getEditDataSource(); + + EBI25InterfaceReader reader = new EBI25InterfaceReader( + getResourceBundle(), ds, host, port, keepAlive, timeout, + retries); + + if (reader.getErrorMessage() == null) { + tryDataSourceSave(ds); + reader.setPoints(getPoints()); + } + + return reader; + } + + @MethodFilter + public LocalizableMessage ebi25SyncTime(String host, int port, int timeout, + int retries) { + return new EBI25InterfaceUpdater().updateSysTime(host, port, timeout, + retries); + } + + @MethodFilter + public DwrResponseI18n saveEBI25PointLocator(int id, String xid, + String name, final EBI25PointLocatorVO locator) { + DwrResponseI18n response = new DwrResponseI18n(); + + if (locator.getType() == EBI25PointLocatorVO.TYPE_VALUE) { + EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser() + .getEditDataSource(); + + if (locator.getSampleRate() < 1) + response.addContextualMessage("sampleRate", + "validate.greaterThanZero"); + else { + // Try to update the EBI25 interface + LocalizableMessage errorMessage = new EBI25InterfaceUpdater() + .updateLogger(ds.getHost(), ds.getPort(), + ds.getTimeout(), ds.getRetries(), locator); + + if (errorMessage == null) { + response = validatePoint(id, xid, name, locator, + new DataPointDefaulter() { + @Override + public void setDefaultValues(DataPointVO dp) { + // Update the point's high/low detectors + // with the locator values. + PointEventDetectorVO high = EBI25Constants + .findDetector( + dp.getEventDetectors(), + true); + if (high != null) + high.setLimit(locator.getHighLimit()); + + PointEventDetectorVO low = EBI25Constants + .findDetector( + dp.getEventDetectors(), + false); + if (low != null) + low.setLimit(locator.getLowLimit()); + } + }); + } else + response.addMessage("sampleRate", errorMessage); + } + } else + response = validatePoint(id, xid, name, locator, null); + + return response; + } + + // + // + // VMStat stuff + // + @MethodFilter + public DwrResponseI18n saveVMStatDataSource(String name, String xid, + int pollSeconds, int outputScale) { + VMStatDataSourceVO ds = (VMStatDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setPollSeconds(pollSeconds); + ds.setOutputScale(outputScale); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveVMStatPointLocator(int id, String xid, + String name, VMStatPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + // + // + // Viconics stuff + // + @MethodFilter + public DwrResponseI18n saveViconicsDataSource(String name, String xid, + String commPortId, int panId, int channel, int timeout, + int retries, int networkTimeoutSeconds, + int deviceWarningTimeoutSeconds, int deviceRemoveTimeoutSeconds, + int pointValueMinimumFreshnessSeconds, boolean convertToCelsius) { + ViconicsDataSourceVO ds = (ViconicsDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setPanId(panId); + ds.setChannel(channel); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setNetworkTimeoutSeconds(networkTimeoutSeconds); + ds.setDeviceWarningTimeoutSeconds(deviceWarningTimeoutSeconds); + ds.setDeviceRemoveTimeoutSeconds(deviceRemoveTimeoutSeconds); + ds.setPointValueMinimumFreshnessSeconds(pointValueMinimumFreshnessSeconds); + ds.setConvertToCelsius(convertToCelsius); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveViconicsPointLocator(int id, String xid, + String name, ViconicsPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public DwrResponseI18n getRfModuleInfo() { + ViconicsDataSourceVO ds = (ViconicsDataSourceVO) Common.getUser() + .getEditDataSource(); + + ViconicsDataSourceRT rt = (ViconicsDataSourceRT) Common.ctx + .getRuntimeManager().getRunningDataSource(ds.getId()); + DwrResponseI18n response = new DwrResponseI18n(); + + if (rt == null) + response.addGenericMessage("dsEdit.viconics.dataSourceNotStarted"); + else { + try { + NetworkIdentifyResponse res = rt + .send(new NetworkIdentifyRequest()); + + Map rfm = new HashMap(); + rfm.put("firmware", ViconicsNetwork.getRevisionString(res + .getZigbeeFirmwareRevision())); + rfm.put("networkAddr", + Integer.toString(res.getZigbeeNetworkAddress())); + rfm.put("ieee", ViconicsNetwork.getIeeeString(res.getIeee())); + rfm.put("chipRevision", Integer.toString(res.getChipRevision())); + response.addData("rfm", rfm); + + List> devices = new ArrayList>(); + for (ViconicsDevice device : rt.getDevices()) { + Map dev = new HashMap(); + dev.put("commAddr", + Integer.toString(device.getCommAddress())); + dev.put("modelNumber", device.getConfiguration().getModel()); + dev.put("firmware", ViconicsNetwork + .getRevisionString(device.getFirmwareRevision())); + dev.put("zigbeeFirmware", ViconicsNetwork + .getRevisionString(device + .getZigbeeFirmwareRevision())); + dev.put("zigbeeNetworkAddr", + Integer.toString(device.getZigbeeNetworkAddress())); + dev.put("ieee", + ViconicsNetwork.getIeeeString(device.getIeee())); + dev.put("chipRevision", + Integer.toString(device.getChipRevision())); + dev.put("crss", + Integer.toString(device.getLinkQualityPercent()) + + "%"); + dev.put("trss", + Integer.toString(device.getReturnQualityPercent()) + + "%"); + devices.add(dev); + } + response.addData("devices", devices); + } catch (ViconicsTransportException e) { + response.addGenericMessage( + "dsEdit.viconics.networkIdentifyFailure", + e.getMessage()); + } catch (RequestFailureException e) { + response.addGenericMessage( + "dsEdit.viconics.networkIdentifyFailure", + e.getMessage()); + } + } + + return response; + } + + // + // + // MBus stuff + // + public DwrResponseI18n saveMBusDataSource(String name, String xid, + TcpIpConnection connection, int updatePeriodType, int updatePeriods) { + MBusDataSourceVO ds = (MBusDataSourceVO) Common.getUser() + .getEditDataSource(); + ds.setXid(xid); + ds.setName(name); + ds.setConnection(connection); + ds.setUpdatePeriodType(updatePeriodType); + ds.setUpdatePeriods(updatePeriods); + return tryDataSourceSave(ds); + } + + public DwrResponseI18n saveMBusPointLocator(int id, String xid, + String name, MBusPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + public Connection getMBusConn() { + TcpIpConnection conn = new TcpIpConnection(); + conn.setHost("localhost"); + conn.setPort(2000); + return conn; + } + + public void searchMBus(TcpIpConnection conn, PrimaryAddressingSearch addressing) { + User user = Common.getUser(); + + Permissions.ensureDataSourcePermission(user); + + MBusDiscovery discovery = new MBusDiscovery(getResourceBundle(), conn, + addressing); + discovery.start(); + user.setTestingUtility(discovery); + } + + public void searchMBus(TcpIpConnection conn, SecondaryAddressingSearch addressing) { + User user = Common.getUser(); + + Permissions.ensureDataSourcePermission(user); + + MBusDiscovery discovery = new MBusDiscovery(getResourceBundle(), conn, + addressing); + discovery.start(); + user.setTestingUtility(discovery); + } + + + public Map mBusSearchUpdate() { + Map result = new HashMap(); + MBusDiscovery test = Common.getUser().getTestingUtility( + MBusDiscovery.class); + if (test == null) + return null; + + test.addUpdateInfo(result); + return result; + } + + public Map getMBusResponseFrames(int deviceIndex) { + Map result = new HashMap(); + MBusDiscovery test = Common.getUser().getTestingUtility( + MBusDiscovery.class); + if (test == null) + return null; + + test.getDeviceDetails(deviceIndex, result); + return result; + } + + public DataPointVO addMBusPoint(String addressing, int deviceIndex, + int rsIndex, int dbIndex) { + DataPointVO dp = getPoint(Common.NEW_ID, null); + MBusPointLocatorVO locator = (MBusPointLocatorVO) dp.getPointLocator(); + + MBusDiscovery test = Common.getUser().getTestingUtility( + MBusDiscovery.class); + if (test == null) + return null; + + MBusResponseFramesContainer dev = test.getDevice(deviceIndex); + if (dev.getResponseFrameContainer(rsIndex).getResponseFrame() instanceof UserDataResponse) { + UserDataResponse udr = (UserDataResponse) dev + .getResponseFrameContainer(rsIndex).getResponseFrame(); + DataBlock db = udr.getDataBlock(dbIndex); + + dp.setName(db.getParamDescr()); + + locator.setAddressing(MBusAddressing.valueOf(addressing)); + locator.setAddress(dev.getAddress()); + locator.setMedium(dev.getMedium().getLabel()); + locator.setManufacturer(dev.getManufacturer()); + locator.setVersion(dev.getVersion()); + locator.setIdentNumber(dev.getIdentNumber()); + locator.setResponseFrame(dev.getResponseFrameContainer(rsIndex) + .getName()); + locator.setDeviceUnit(db.getSubUnit()); + locator.setDifCode(db.getDataFieldCode().getLabel()); + locator.setFunctionField(db.getFunctionField().getLabel()); + locator.setStorageNumber(db.getStorageNumber()); + locator.setTariff(db.getTariff()); + locator.setSiPrefix(db.getVif().getSiPrefix() == null ? null : db + .getVif().getSiPrefix().getLabel()); + locator.setUnitOfMeasurement(db.getVif().getUnitOfMeasurement() == null ? null + : db.getVif().getUnitOfMeasurement().getLabel()); + locator.setVifType(db.getVif().getVifType().getLabel()); + locator.setVifLabel(db.getVif().getLabel()); + locator.setExponent(db.getVif().getExponent()); + if (db.getVifes() != null) { + final String[] vifeLabels = new String[db.getVifes().length]; + final String[] vifeTypes = new String[db.getVifes().length]; + for (int i = 0; i < vifeLabels.length; i++) { + vifeTypes[i] = db.getVifes()[i].getVifeType().getLabel(); + vifeLabels[i] = db.getVifes()[i].getLabel(); + } + locator.setVifeTypes(vifeTypes); + locator.setVifeTypes(vifeTypes); + locator.setVifeLabels(vifeLabels); + } else { + locator.setVifeLabels(null); + } + } + return dp; + } + + // + // + // OpenV4J stuff + // + public void searchOpenV4J(String commPortId) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + OpenV4JDiscovery discovery = OpenV4JDiscovery.searchDataPoints( + getResourceBundle(), commPortId); + user.setTestingUtility(discovery); + } + + public void detectOpenV4JDevice(String commPortId) { + User user = Common.getUser(); + Permissions.ensureDataSourcePermission(user); + + OpenV4JDiscovery discovery = OpenV4JDiscovery.detectDevice( + getResourceBundle(), commPortId); + ; + user.setTestingUtility(discovery); + } + + public DwrResponseI18n saveOpenV4JDataSource(String name, String xid, + String commPortId, int updatePeriodType, int updatePeriods, + String device, String protocol) { + OpenV4JDataSourceVO ds = (OpenV4JDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setUpdatePeriodType(updatePeriodType); + ds.setUpdatePeriods(updatePeriods); + ds.setDevice(Devices.valueOf(device)); + ds.setProtocol(Protocol.valueOf(protocol)); + return tryDataSourceSave(ds); + } + + public DwrResponseI18n saveOpenV4JPointLocator(int id, String xid, + String name, OpenV4JPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + public Map openV4JSearchUpdate() { + Map result = new HashMap(); + OpenV4JDiscovery test = Common.getUser().getTestingUtility( + OpenV4JDiscovery.class); + if (test == null) + return null; + + test.addUpdateInfo(result); + return result; + } + + public Map openV4JDetectDeviceUpdate() { + Map result = new HashMap(); + OpenV4JDiscovery test = Common.getUser().getTestingUtility( + OpenV4JDiscovery.class); + if (test == null) + return null; + + test.addDeviceInfo(result); + return result; + } + + public OpenV4JProtocolBean[] getOpenV4jProtocolsOfDevice(String deviceName) { + return OpenV4JProtocolBean.fromDevice(Devices.valueOf(deviceName)); + } + + public OpenV4JDataPointBean[] getOpenV4jDataPointsOfGroup(String groupName) { + Group g = Group.valueOf(groupName); + List result = new ArrayList(); + for (DataPoint dp : DataPoint.values()) { + if (dp.getGroup().equals(g)) { + result.add(new OpenV4JDataPointBean(dp)); + } + } + return result.toArray(new OpenV4JDataPointBean[result.size()]); + } + + public DataPointVO addOpenV4JPoint(String openV4JEnumName) { + DataPointVO result = getPoint(Common.NEW_ID, null); + OpenV4JPointLocatorVO locator = (OpenV4JPointLocatorVO) result + .getPointLocator(); + + OpenV4JDiscovery test = Common.getUser().getTestingUtility( + OpenV4JDiscovery.class); + if (test == null) { + return null; + } + + final DataPoint dp = DataPoint.valueOf(openV4JEnumName); + result.setName(dp.getGroup().getLabel() + " " + dp.getLabel()); + locator.setDataPointName(dp.getName()); + return result; + } + + // + + // + // + // DNP3 stuff + // + @MethodFilter + public DwrResponseI18n saveDNP3IpDataSource(String name, String xid, + int sourceAddress, int slaveAddress, String host, int port, + int staticPollPeriods, int rbePollPeriods, int rbePeriodType, + boolean quantize, int timeout, int retries) { + Dnp3IpDataSourceVO ds = (Dnp3IpDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setSourceAddress(sourceAddress); + ds.setSlaveAddress(slaveAddress); + ds.setHost(host); + ds.setPort(port); + + ds.setStaticPollPeriods(staticPollPeriods); + ds.setRbePeriodType(rbePeriodType); + ds.setRbePollPeriods(rbePollPeriods); + ds.setQuantize(quantize); + ds.setTimeout(timeout); + ds.setRetries(retries); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveDNP3SerialDataSource(String name, String xid, + int sourceAddress, int slaveAddress, String commPortId, + int baudRate, int staticPollPeriods, int rbePollPeriods, + int rbePeriodType, boolean quantize, int timeout, int retries) { + Dnp3SerialDataSourceVO ds = (Dnp3SerialDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setSourceAddress(sourceAddress); + ds.setSlaveAddress(slaveAddress); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setStaticPollPeriods(staticPollPeriods); + ds.setRbePeriodType(rbePeriodType); + ds.setRbePollPeriods(rbePollPeriods); + ds.setQuantize(quantize); + ds.setTimeout(timeout); + ds.setRetries(retries); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveDnp3PointLocator(int id, String xid, + String name, Dnp3PointLocatorVO locator) { + DwrResponseI18n response = new DwrResponseI18n(); + + if (locator.getTimeOn() < 0) + response.addContextualMessage("timeOn", + "reports.validate.lessThan0"); + if (locator.getTimeOff() < 0) + response.addContextualMessage("timeOff", + "reports.validate.lessThan0"); + + List points = getPoints(); + Iterator itr = points.iterator(); + while (itr.hasNext()) { + DataPointVO vo = (DataPointVO) itr.next(); + Dnp3PointLocatorVO loc = (Dnp3PointLocatorVO) vo.getPointLocator(); + if (loc.getDnp3DataType() == ((Dnp3PointLocatorVO) locator) + .getDnp3DataType() + && loc.getIndex() == ((Dnp3PointLocatorVO) locator) + .getIndex() && id != vo.getId()) { + response.addContextualMessage("index", + "dsEdit.dnp3.validate.indexUsed"); + } + } + + if (!response.getHasMessages()) + return validatePoint(id, xid, name, locator, null); + return response; + } + + @MethodFilter + public DwrResponseI18n saveMultipleDnp3PointLocator(String[] names, + int[] index, Dnp3PointLocatorVO[] locators) { + return validateMultipleDnp3Points(names, index, locators, null); + } + + private DwrResponseI18n validateMultipleDnp3Points(String[] names, + int[] index, Dnp3PointLocatorVO[] locators, + DataPointDefaulter defaulter) { + DwrResponseI18n response = new DwrResponseI18n(); + + if (locators[0].getClass().equals(Dnp3PointLocatorVO.class)) { + if (locators[0].getTimeOn() < 0) + response.addContextualMessage("timeOn", + "reports.validate.lessThan0"); + if (locators[0].getTimeOff() < 0) + response.addContextualMessage("timeOff", + "reports.validate.lessThan0"); + } + + for (int i = 0; i < names.length; i++) { + locators[i].setIndex(index[i]); + + List points = getPoints(); + Iterator itr = points.iterator(); + while (itr.hasNext()) { + Dnp3PointLocatorVO loc = (Dnp3PointLocatorVO) itr.next() + .getPointLocator(); + if (loc.getDnp3DataType() == ((Dnp3PointLocatorVO) locators[i]) + .getDnp3DataType() + && loc.getIndex() == ((Dnp3PointLocatorVO) locators[i]) + .getIndex()) { + response.addContextualMessage("index", + "dsEdit.dnp3.validate.someIndexUsed"); + } + } + } + + if (response.getHasMessages()) + return response; + + for (int i = 0; i < names.length; i++) { + DataPointVO dp = getPoint(Common.NEW_ID, defaulter); + dp.setName(names[i]); + locators[i].setIndex(index[i]); + dp.setPointLocator(locators[i]); + + if (StringUtils.isEmpty(dp.getXid())) + response.addContextualMessage("xid", "validate.required"); + else if (!new DataPointDao() + .isXidUnique(dp.getXid(), Common.NEW_ID)) + response.addContextualMessage("xid", "validate.xidUsed"); + else if (StringUtils.isLengthGreaterThan(dp.getXid(), 50)) + response.addContextualMessage("xid", "validate.notLongerThan", + 50); + + locators[i].validate(response); + + if (!response.getHasMessages()) { + Common.ctx.getRuntimeManager().saveDataPoint(dp); + response.addData("id", dp.getId()); + response.addData("points", getPoints()); + } + } + return response; + } + + // + // / + // / OPC DA stuff + // / + // + @MethodFilter + public DwrResponseI18n saveOPCDataSource(String name, String xid, + String host, String domain, String user, String password, + String server, int updatePeriods, int updatePeriodType, + boolean quantize) { + OPCDataSourceVO ds = (OPCDataSourceVO) Common.getUser() + .getEditDataSource(); + ds.setXid(xid); + ds.setName(name); + ds.setHost(host); + ds.setDomain(domain); + ds.setUser(user); + ds.setPassword(password); + ds.setServer(server); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveOPCPointLocator(int id, String xid, String name, + VirtualPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + public ArrayList searchOpcServer(String host, String domain, + String user, String password) { + + Logger log = JISystem.getLogger(); + log.setLevel(Level.OFF); + + ArrayList serverList = new ArrayList(); + try { + serverList = new RealOPCMaster().listOPCServers(user, password, + host, domain); + } catch (Exception e) { + serverList.add("-1"); + serverList.add(e.getMessage()); + } + return serverList; + } + + public ArrayList listOPCTags(String host, String domain, + String user, String password, String serverName) { + + LOG.debug("List OPC Tags: " + host + ", " + domain + ", " + user + ", " + + serverName); + + ArrayList opcItems = new ArrayList(); + + try { + opcItems = new RealOPCMaster().browseOPCTags(user, password, host, + domain, serverName); + } catch (Exception e) { + LOG.warn("Error retriving OPC tags: " + e.getLocalizedMessage()); + } + + return opcItems; + } + + public OPCItem validateOPCTag(String tag, String user, String password, + String host, String domain, String servername) { + + Logger log = JISystem.getLogger(); + log.setLevel(Level.OFF); + + OPCItem opcItem = new OPCItem(tag, 0, false); + + OPCUtils utils = new OPCUtils(); + + opcItem = utils.validateTag(tag, user, password, host, domain, + servername); + return opcItem; + + } + + // public void saveOPCTags(OPCItem[] opcItems) { + // for (int i = 0; i < opcItems.length; i++) { + // OPCItem opcItem = new OPCItem("", 0, false); + // } + // } + + public DwrResponseI18n saveMultipleOPCPointLocator(String[] tags, + int[] dataTypes, boolean[] settables, OPCPointLocatorVO[] locators, + String context) { + + return validateMultipleOPCPoints(tags, dataTypes, settables, locators, + context, null); + } + + private DwrResponseI18n validateMultipleOPCPoints(String[] tags, + int[] dataTypes, boolean[] settables, OPCPointLocatorVO[] locators, + String context, DataPointDefaulter defaulter) { + DwrResponseI18n response = new DwrResponseI18n(); + OPCDataSourceVO ds = (OPCDataSourceVO) Common.getUser() + .getEditDataSource(); + if (ds.isNew()) { + response.addContextualMessage(context, + "dsEdit.opc.validate.dataSourceNotSaved"); + return response; + } + for (int i = 0; i < locators.length; i++) { + DataPointVO dp = getPoint(Common.NEW_ID, defaulter); + dp.setName(tags[i]); + locators[i].setTag(tags[i]); + locators[i].setDataTypeId(dataTypes[i]); + locators[i].setSettable(settables[i]); + dp.setPointLocator(locators[i]); + + if (StringUtils.isEmpty(dp.getXid())) + response.addContextualMessage("xid", "validate.required"); + else if (!new DataPointDao() + .isXidUnique(dp.getXid(), Common.NEW_ID)) + response.addContextualMessage("xid", "validate.xidUsed"); + else if (StringUtils.isLengthGreaterThan(dp.getXid(), 50)) + response.addContextualMessage("xid", "validate.notLongerThan", + 50); + + // locators[i].validate(response); + if (!response.getHasMessages()) { + Common.ctx.getRuntimeManager().saveDataPoint(dp); + response.addData("id", dp.getId()); + response.addData("points", getPoints()); + } + } + return response; + } + + // //// + // ASCII File Reader + // //// + + public DwrResponseI18n saveASCIIFileDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String filePath, + boolean quantize) { + + ASCIIFileDataSourceVO ds = (ASCIIFileDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setFilePath(filePath); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveASCIIFilePointLocator(int id, String xid, + String name, ASCIIFilePointLocatorVO locator) { + locator.setSettable(false); + return validatePoint(id, xid, name, locator, null); + } + + public boolean checkFile(String filePath) { + return new File(filePath).exists(); + } + + // //// + // DR_STORAGE_HT5B + // //// + + public DwrResponseI18n saveDrStorageHt5bDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String commPortId, + int baudRate, int dataBits, int stopBits, int parity, int timeout, + int retries, String initString, boolean quantize) { + + DrStorageHt5bDataSourceVO ds = (DrStorageHt5bDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setDataBits(dataBits); + ds.setStopBits(stopBits); + ds.setParity(parity); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setInitString(initString); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveDrStorageHt5bPointLocator(int id, String xid, + String name, DrStorageHt5bPointLocatorVO locator) { + locator.setSettable(false); + return validatePoint(id, xid, name, locator, null); + } + + // //// + // ASCII Serial + // //// + + public DwrResponseI18n saveASCIISerialDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String commPortId, + int baudRate, int dataBits, int stopBits, int parity, int timeout, + int retries, int stopMode, int nChar, int charStopMode, + String charX, String hexValue, int stopTimeout, String initString, + int bufferSize, boolean quantize) { + + ASCIISerialDataSourceVO ds = (ASCIISerialDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setDataBits(dataBits); + ds.setStopBits(stopBits); + ds.setParity(parity); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setStopMode(stopMode); + ds.setnChar(nChar); + ds.setCharStopMode(charStopMode); + ds.setCharX(charX); + ds.setHexValue(hexValue); + ds.setStopTimeout(stopTimeout); + ds.setInitString(initString); + ds.setBufferSize(bufferSize); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveASCIISerialPointLocator(int id, String xid, + String name, ASCIISerialPointLocatorVO locator) { + locator.setSettable(false); + return validatePoint(id, xid, name, locator, null); + } + + // + // / + // / IEC101 Serial stuff + // / + // + @MethodFilter + public DwrResponseI18n saveIEC101SerialDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, int giRelativePeriod, + int clockSynchRelativePeriod, int linkLayerAddressSize, + int linkLayerAddress, int asduAddressSize, int asduAddress, + int cotSize, int objectAddressSize, int timeout, int retries, + String commPortId, int baudRate, int dataBits, int stopBits, + int parity, boolean quantize) { + + IEC101SerialDataSourceVO ds = (IEC101SerialDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setGiRelativePeriod(giRelativePeriod); + ds.setClockSynchRelativePeriod(clockSynchRelativePeriod); + ds.setLinkLayerAddressSize(linkLayerAddressSize); + ds.setLinkLayerAddress(linkLayerAddress); + ds.setAsduAddressSize(asduAddressSize); + ds.setAsduAddress(asduAddress); + ds.setCotSize(cotSize); + ds.setObjectAddressSize(objectAddressSize); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setDataBits(dataBits); + ds.setStopBits(stopBits); + ds.setParity(parity); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveIEC101EthernetDataSource(String name, + String xid, int updatePeriods, int updatePeriodType, + int giRelativePeriod, int clockSynchRelativePeriod, + int linkLayerAddressSize, int linkLayerAddress, + int asduAddressSize, int asduAddress, int cotSize, + int objectAddressSize, int timeout, int retries, String host, + int port, boolean quantize) { + + IEC101EthernetDataSourceVO ds = (IEC101EthernetDataSourceVO) Common + .getUser().getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setGiRelativePeriod(giRelativePeriod); + ds.setClockSynchRelativePeriod(clockSynchRelativePeriod); + ds.setLinkLayerAddressSize(linkLayerAddressSize); + ds.setLinkLayerAddress(linkLayerAddress); + ds.setAsduAddressSize(asduAddressSize); + ds.setAsduAddress(asduAddress); + ds.setCotSize(cotSize); + ds.setObjectAddressSize(objectAddressSize); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setHost(host); + ds.setPort(port); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveIEC101PointLocator(int id, String xid, + String name, IEC101PointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + // + // + // Pachube stuff + // + @MethodFilter + public DwrResponseI18n savePachubeDataSource(String name, String xid, + String apiKey, int updatePeriods, int updatePeriodType, + int timeoutSeconds, int retries) { + PachubeDataSourceVO ds = (PachubeDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setApiKey(apiKey); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setTimeoutSeconds(timeoutSeconds); + ds.setRetries(retries); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n savePachubePointLocator(int id, String xid, + String name, PachubePointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public String testPachubeValueParams(String apiKey, int timeoutSeconds, + int retries, int feedId, String dataStreamId, int dataTypeId, + String binary0Value) { + try { + Map data = PachubeDataSourceRT.getData( + PachubeDataSourceRT.createHttpClient(timeoutSeconds, + retries), feedId, apiKey); + + PachubeValue pachubeValue = data.get(dataStreamId); + if (pachubeValue == null) + return getMessage(new LocalizableMessage( + "event.pachube.dataStreamNotFound", dataStreamId, + feedId)); + + MangoValue value = DataSourceUtils.getValue( + pachubeValue.getValue(), dataTypeId, binary0Value, null, + null, null); + return getMessage("common.result") + ": " + value.toString(); + } catch (LocalizableException e) { + return getMessage(e.getLocalizableMessage()); + } catch (Exception e) { + return e.getMessage(); + } + } + + // + // + // JMX stuff + // + @MethodFilter + public DwrResponseI18n saveJmxDataSource(String name, String xid, + boolean useLocalServer, String remoteServerAddr, + int updatePeriodType, int updatePeriods, boolean quantize) { + JmxDataSourceVO ds = (JmxDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUseLocalServer(useLocalServer); + ds.setRemoteServerAddr(remoteServerAddr); + ds.setUpdatePeriodType(updatePeriodType); + ds.setUpdatePeriods(updatePeriods); + ds.setQuantize(quantize); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveJmxPointLocator(int id, String xid, String name, + JmxPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + @MethodFilter + public DwrResponseI18n getJmxObjectNames(boolean useLocalServer, + String remoteServerAddr) { + DwrResponseI18n response = new DwrResponseI18n(); + JMXConnector connector = null; + + try { + MBeanServerConnection server = null; + if (useLocalServer) + server = ManagementFactory.getPlatformMBeanServer(); + else { + String url = "service:jmx:rmi:///jndi/rmi://" + + remoteServerAddr + "/jmxrmi"; + try { + connector = JMXConnectorFactory.connect(new JMXServiceURL( + url), null); + server = connector.getMBeanServerConnection(); + } catch (MalformedURLException e) { + response.addGenericMessage("dsEdit.jmx.badUrl", + e.getMessage()); + } catch (IOException e) { + response.addGenericMessage("dsEdit.jmx.connectionError", + e.getMessage()); + } + } + + if (!response.getHasMessages()) { + try { + Map names = new TreeMap(); + response.addData("names", names); + + for (ObjectName on : server.queryNames(null, null)) { + List> objectAttributesList = new ArrayList>(); + names.put(on.getCanonicalName(), objectAttributesList); + + for (MBeanAttributeInfo attr : server.getMBeanInfo(on) + .getAttributes()) { + if (attr.getType() == null) + continue; + + Map objectAttributes = new HashMap(); + try { + objectAttributes.put("name", attr.getName()); + if (attr.getType() + .equals("javax.management.openmbean.CompositeData")) { + objectAttributes.put("type", "Composite"); + CompositeData cd = (CompositeData) server + .getAttribute(on, attr.getName()); + if (cd != null) { + List> compositeItemsList = new ArrayList>(); + objectAttributes.put("items", + compositeItemsList); + for (String key : cd.getCompositeType() + .keySet()) { + Map compositeItems = new HashMap(); + compositeItemsList + .add(compositeItems); + compositeItems.put("name", key); + compositeItems + .put("type", cd + .getCompositeType() + .getType(key) + .getTypeName()); + } + } + } else + objectAttributes + .put("type", attr.getType()); + objectAttributesList.add(objectAttributes); + } catch (RuntimeMBeanException e) { + // ignore + } + } + } + } catch (Exception e) { + response.addGenericMessage("dsEdit.jmx.readError", + e.getMessage()); + LOG.warn("", e); + } + } + } finally { + try { + if (connector != null) + connector.close(); + } catch (IOException e) { + // no op + } + } + + return response; + } + + // + // + // Persistent stuff + // + @MethodFilter + public DwrResponseI18n savePersistentDataSource(String name, String xid, + int port, String authorizationKey, boolean acceptPointUpdates) { + PersistentDataSourceVO ds = (PersistentDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setPort(port); + ds.setAuthorizationKey(authorizationKey); + ds.setAcceptPointUpdates(acceptPointUpdates); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n savePersistentPointLocator(int id, String xid, + String name, PersistentPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + public DwrResponseI18n saveNodaveS7DataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String filePath, + boolean quantize, String nodaveWriteBaseCmd) { + + NodaveS7DataSourceVO ds = (NodaveS7DataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setFilePath(filePath); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setQuantize(quantize); + ds.setNodaveWriteBaseCmd(nodaveWriteBaseCmd); + + return tryDataSourceSave(ds); + + } + + @MethodFilter + public DwrResponseI18n saveNodaveS7PointLocator(int id, String xid, + String name, NodaveS7PointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + public DwrResponseI18n saveAlpha2DataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String commPortId, + int baudRate, int dataBits, int stopBits, int parity, int timeout, + int retries, int station) { + + Alpha2DataSourceVO ds = (Alpha2DataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setDataBits(dataBits); + ds.setStopBits(stopBits); + ds.setParity(parity); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + ds.setStation(station); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveAlpha2PointLocator(int id, String xid, + String name, Alpha2PointLocatorVO locator) { + + return validatePoint(id, xid, name, locator, null); + } + + // + // + // Internal stuff + // + @MethodFilter + public DwrResponseI18n saveInternalDataSource(String name, String xid, + int updatePeriods, int updatePeriodType) { + InternalDataSourceVO ds = (InternalDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveInternalPointLocator(int id, String xid, + String name, InternalPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } + + public DwrResponseI18n saveRadiuinoDataSource(String name, String xid, + int updatePeriods, int updatePeriodType, String commPortId, + int baudRate, int dataBits, int stopBits, int parity, + boolean pollingMode, int timeout, int retries) { + + RadiuinoDataSourceVO ds = (RadiuinoDataSourceVO) Common.getUser() + .getEditDataSource(); + + ds.setXid(xid); + ds.setName(name); + ds.setCommPortId(commPortId); + ds.setBaudRate(baudRate); + ds.setDataBits(dataBits); + ds.setStopBits(stopBits); + ds.setParity(parity); + ds.setPollingMode(pollingMode); + ds.setTimeout(timeout); + ds.setRetries(retries); + ds.setUpdatePeriods(updatePeriods); + ds.setUpdatePeriodType(updatePeriodType); + + return tryDataSourceSave(ds); + } + + @MethodFilter + public DwrResponseI18n saveRadiuinoPointLocator(int id, String xid, + String name, RadiuinoPointLocatorVO locator) { + return validatePoint(id, xid, name, locator, null); + } } \ No newline at end of file diff --git a/src/com/serotonin/mango/web/dwr/beans/SnmpOidGet.java b/src/com/serotonin/mango/web/dwr/beans/SnmpOidGet.java index f878e2aa82..a88ce6ff9d 100644 --- a/src/com/serotonin/mango/web/dwr/beans/SnmpOidGet.java +++ b/src/com/serotonin/mango/web/dwr/beans/SnmpOidGet.java @@ -23,7 +23,14 @@ import org.snmp4j.PDU; import org.snmp4j.Snmp; +import org.snmp4j.Target; +import org.snmp4j.event.ResponseEvent; +import org.snmp4j.mp.MPv3; +import org.snmp4j.security.SecurityModels; +import org.snmp4j.security.SecurityProtocols; +import org.snmp4j.security.USM; import org.snmp4j.smi.OID; +import org.snmp4j.smi.OctetString; import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; @@ -60,19 +67,37 @@ public SnmpOidGet(ResourceBundle bundle, String host, int port, Version version, public void run() { Snmp snmp = null; try { + snmp = new Snmp(new DefaultUdpTransportMapping()); + + OctetString localEngineId = new OctetString(MPv3.createLocalEngineID()).substring(0,9); + USM usm = new USM(SecurityProtocols.getInstance(), localEngineId, 0); + SecurityModels.getInstance().addSecurityModel(usm); + version.addUser(snmp); + + Target target = version.getTarget(host, port, retries, timeout); + snmp.listen(); PDU pdu = version.createPDU(); - pdu.setType(PDU.GET); pdu.add(new VariableBinding(new OID(oid))); + pdu.setType(PDU.GET); + + ResponseEvent event = snmp.send(pdu, target); + + if(event != null) { + if(event.getResponse() != null) { + if(pdu.getErrorStatus() == PDU.noError) { + result = event.getResponse().get(0).getVariable().toString(); + } else { + result = I18NUtils.getMessage(bundle, "dsEdit.snmp.tester.noResponse"); + } + } else { + result = I18NUtils.getMessage(bundle, "dsEdit.snmp.tester.noResponse"); + } + } - PDU response = snmp.send(pdu, version.getTarget(host, port, retries, timeout)).getResponse(); - if (response == null) - result = I18NUtils.getMessage(bundle, "dsEdit.snmp.tester.noResponse"); - else - result = response.get(0).getVariable().toString(); } catch (IOException e) { result = e.getMessage(); diff --git a/src/org/scada_lts/ds/snmp/SnmpDataSourceRT.java b/src/org/scada_lts/ds/snmp/SnmpDataSourceRT.java new file mode 100644 index 0000000000..de896dcede --- /dev/null +++ b/src/org/scada_lts/ds/snmp/SnmpDataSourceRT.java @@ -0,0 +1,75 @@ +//package org.scada_lts.ds.snmp; +// +//import com.serotonin.ShouldNeverHappenException; +//import com.serotonin.mango.rt.dataImage.DataPointRT; +//import com.serotonin.mango.rt.dataImage.PointValueTime; +//import com.serotonin.mango.rt.dataImage.SetPointSource; +//import com.serotonin.mango.rt.dataSource.EventDataSource; +//import com.serotonin.mango.rt.dataSource.snmp.Version; +//import com.serotonin.mango.vo.dataSource.DataSourceVO; +//import com.serotonin.mango.vo.dataSource.snmp.SnmpDataSourceVO; +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +//import org.snmp4j.Snmp; +//import org.snmp4j.Target; +//import org.snmp4j.transport.DefaultUdpTransportMapping; +// +//import java.io.IOException; +//import java.net.InetAddress; +//import java.net.SocketException; +//import java.net.UnknownHostException; +// +//public class SnmpDataSourceRT extends EventDataSource { +// +// private final Log log = LogFactory.getLog(SnmpDataSourceRT.class); +// +// private SnmpDataSourceVO vo; +// private String address; +// private Target target; +// private Version version; +// private Snmp snmp; +// +// public SnmpDataSourceRT(SnmpDataSourceVO vo) { +// super(vo); +// this.vo = vo; +// version = Version.getVersion(vo.getSnmpVersion(), vo.getCommunity(), +// vo.getSecurityName(), vo.getAuthProtocol(), +// vo.getAuthPassphrase(), vo.getPrivProtocol(), +// vo.getPrivPassphrase(), vo.getEngineId(), +// vo.getContextEngineId(), vo.getContextName()); +// } +// +// @Override +// public void initialize() { +// try { +// address = InetAddress.getByName(vo.getHost()).getHostAddress(); +// target = version.getTarget(vo.getHost(), vo.getPort(), vo.getRetries(), vo.getTimeout()); +// snmp = new Snmp(new DefaultUdpTransportMapping()); +// snmp.listen(); +// super.initialize(); +// } catch (UnknownHostException | SocketException e) { +// e.printStackTrace(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// } +// +// @Override +// public void terminate() { +// super.terminate(); +// try { +// if(snmp != null) { +// snmp.close(); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// +// @Override +// public void setPointValue(DataPointRT dataPoint, PointValueTime valueTime, SetPointSource source) { +// +// +// } +//} diff --git a/webapp-resources/messages_de.properties b/webapp-resources/messages_de.properties index 9e4c3a9dc1..61ae33dae9 100644 --- a/webapp-resources/messages_de.properties +++ b/webapp-resources/messages_de.properties @@ -1055,10 +1055,8 @@ dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.authProtocol=Auth protocol dsEdit.snmp.binary0Value=Binary 0 value dsEdit.snmp.community=Community -dsEdit.snmp.contextEngine=Context engine dsEdit.snmp.contextName=Context name dsEdit.snmp.desc=SNMP properties -dsEdit.snmp.engineId=Engine ID dsEdit.snmp.gettingValue=Getting value... dsEdit.snmp.host=Host dsEdit.snmp.localAddress=Local address @@ -3178,4 +3176,12 @@ dox.collectInactiveMsg=Collect inactive msg dox.smsEventHandlers=SMS event handler ftl.activeAt=active at ftl.subject.limit=Scada-LTS event limit notification -ftl.subject.pointname.timestamp={0} - active at {1} \ No newline at end of file +ftl.subject.pointname.timestamp={0} - active at {1} +dsEdit.snmp.sl.label= +dsEdit.snmp.sl.authpriv= +dsEdit.snmp.sl.noauthnopriv= +dsEdit.snmp.sl.authnopriv= +dsEdit.snmp.walking= +dsEdit.snmp.oidWalk= +dsEdit.snmp.walk= +dsEdit.snmp.trapPortEnabled= \ No newline at end of file diff --git a/webapp-resources/messages_en.properties b/webapp-resources/messages_en.properties index 74ccd075a9..7e7a805e89 100644 --- a/webapp-resources/messages_en.properties +++ b/webapp-resources/messages_en.properties @@ -1055,10 +1055,8 @@ dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.authProtocol=Auth protocol dsEdit.snmp.binary0Value=Binary 0 value dsEdit.snmp.community=Community -dsEdit.snmp.contextEngine=Context engine dsEdit.snmp.contextName=Context name dsEdit.snmp.desc=SNMP properties -dsEdit.snmp.engineId=Engine ID dsEdit.snmp.gettingValue=Getting value... dsEdit.snmp.host=Host dsEdit.snmp.localAddress=Local address @@ -3183,4 +3181,12 @@ dox.collectInactiveMsg=Collect inactive msg dox.smsEventHandlers=SMS event handler ftl.activeAt=active at ftl.subject.limit=Scada-LTS event limit notification -ftl.subject.pointname.timestamp={0} - active at {1} \ No newline at end of file +ftl.subject.pointname.timestamp={0} - active at {1} +dsEdit.snmp.sl.label=Security level +dsEdit.snmp.sl.authpriv=Authentication and Encryption +dsEdit.snmp.sl.noauthnopriv=Dissable authentication and encryption +dsEdit.snmp.sl.authnopriv=Only authentication +dsEdit.snmp.walking=SNMP Walk testing +dsEdit.snmp.oidWalk=OID to Walk +dsEdit.snmp.walk=Perform walk +dsEdit.snmp.trapPortEnabled=Traps enabled \ No newline at end of file diff --git a/webapp-resources/messages_es.properties b/webapp-resources/messages_es.properties index a2cbda0a3e..3c34250e80 100644 --- a/webapp-resources/messages_es.properties +++ b/webapp-resources/messages_es.properties @@ -1040,10 +1040,8 @@ dsEdit.snmp.authPassphrase=Contrase\u00f1a de autenticaci\u00f3n dsEdit.snmp.authProtocol=Protocolo de autenticaci\u00f3n dsEdit.snmp.binary0Value=Valor Binario 0 dsEdit.snmp.community=Comunidad -dsEdit.snmp.contextEngine=Motor de contexto dsEdit.snmp.contextName=Nombre de contexto dsEdit.snmp.desc=Propiedades SNMP -dsEdit.snmp.engineId=ID de Motor dsEdit.snmp.gettingValue=Obteniendo valor... dsEdit.snmp.host=Servidor dsEdit.snmp.localAddress=Direcci\u00f3n Local @@ -3103,4 +3101,4 @@ dox.collectInactiveMsg=Collect inactive msg dox.smsEventHandlers=SMS event handler ftl.activeAt=active at ftl.subject.limit=Scada-LTS event limit notification -ftl.subject.pointname.timestamp={0} - active at {1} \ No newline at end of file +ftl.subject.pointname.timestamp={0} - active at {1} diff --git a/webapp-resources/messages_fi.properties b/webapp-resources/messages_fi.properties index 758f602300..90892e14b7 100644 --- a/webapp-resources/messages_fi.properties +++ b/webapp-resources/messages_fi.properties @@ -854,8 +854,6 @@ dsEdit.snmp.none=(none) dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.privProtocol=Priv protocol dsEdit.snmp.privPassphrase=Priv passphrase -dsEdit.snmp.engineId=Engine ID -dsEdit.snmp.contextEngine=Context engine dsEdit.snmp.contextName=Context name dsEdit.snmp.retries=Retries dsEdit.snmp.timeout=Timeout (ms) diff --git a/webapp-resources/messages_fr.properties b/webapp-resources/messages_fr.properties index 1539c0ec4c..04a0bd2aa2 100644 --- a/webapp-resources/messages_fr.properties +++ b/webapp-resources/messages_fr.properties @@ -972,10 +972,8 @@ dsEdit.snmp.authPassphrase=Passage de phrase Auth snmp dsEdit.snmp.authProtocol=Protocole Auth snmp dsEdit.snmp.binary0Value=Valeur 0 binaire snmp dsEdit.snmp.community=Communauté snmp -dsEdit.snmp.contextEngine=Moteur de contexte snmp dsEdit.snmp.contextName=Nom de contexte snmp dsEdit.snmp.desc=Propriétés SNMP -dsEdit.snmp.engineId=ID moteur snmp dsEdit.snmp.gettingValue=Obtenant valeur… snmp dsEdit.snmp.host=Hôte snmp dsEdit.snmp.localAddress=Adresse locale snmp diff --git a/webapp-resources/messages_lu.properties b/webapp-resources/messages_lu.properties index cdcee5d785..2fe029046e 100644 --- a/webapp-resources/messages_lu.properties +++ b/webapp-resources/messages_lu.properties @@ -1074,10 +1074,8 @@ dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.authProtocol=Auth protocol dsEdit.snmp.binary0Value=Binary 0 value dsEdit.snmp.community=Community -dsEdit.snmp.contextEngine=Context engine dsEdit.snmp.contextName=Context name dsEdit.snmp.desc=SNMP properties -dsEdit.snmp.engineId=Engine ID dsEdit.snmp.gettingValue=Getting value... dsEdit.snmp.host=Host dsEdit.snmp.localAddress=Local address diff --git a/webapp-resources/messages_nl.properties b/webapp-resources/messages_nl.properties index e695ad94e5..5af80244d9 100644 --- a/webapp-resources/messages_nl.properties +++ b/webapp-resources/messages_nl.properties @@ -835,8 +835,6 @@ dsEdit.snmp.none=(geen) dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.privProtocol=Priv protocol dsEdit.snmp.privPassphrase=Priv passphrase -dsEdit.snmp.engineId=Engine ID -dsEdit.snmp.contextEngine=Context engine dsEdit.snmp.contextName=Context name dsEdit.snmp.retries=Retries dsEdit.snmp.timeout=Timeout (ms) diff --git a/webapp-resources/messages_pl.properties b/webapp-resources/messages_pl.properties index bf478f287d..1af5781247 100644 --- a/webapp-resources/messages_pl.properties +++ b/webapp-resources/messages_pl.properties @@ -871,8 +871,6 @@ dsEdit.snmp.none=(none) dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.privProtocol=Priv protocol dsEdit.snmp.privPassphrase=Priv passphrase -dsEdit.snmp.engineId=Engine ID -dsEdit.snmp.contextEngine=Context engine dsEdit.snmp.contextName=Context name dsEdit.snmp.retries=Retries dsEdit.snmp.timeout=Timeout (ms) diff --git a/webapp-resources/messages_pt.properties b/webapp-resources/messages_pt.properties index df6439fac6..7df25bccf3 100644 --- a/webapp-resources/messages_pt.properties +++ b/webapp-resources/messages_pt.properties @@ -881,8 +881,6 @@ dsEdit.snmp.none=(nenhum) dsEdit.snmp.authPassphrase=senten\u00e7a de autentica\u00e7\u00e3o dsEdit.snmp.privProtocol=Protocolo priv dsEdit.snmp.privPassphrase=Senten\u00e7a de priv -dsEdit.snmp.engineId=Engine ID -dsEdit.snmp.contextEngine=Mecanismo de contexto dsEdit.snmp.contextName=Nome do contexto dsEdit.snmp.retries=Retentativas dsEdit.snmp.timeout=Timeout (ms) diff --git a/webapp-resources/messages_ru.properties b/webapp-resources/messages_ru.properties index 4ec4d017a3..4c12b88fca 100644 --- a/webapp-resources/messages_ru.properties +++ b/webapp-resources/messages_ru.properties @@ -855,8 +855,6 @@ dsEdit.snmp.none=(\u043d\u0435\u0442) dsEdit.snmp.authPassphrase=\u0424\u0440\u0430\u0437\u0430-\u043f\u0430\u0440\u043e\u043b\u044c \u0430\u0432\u0442\u043e\u0440\u0438\u0437\u0430\u0446\u0438\u0438 dsEdit.snmp.privProtocol= Priv protocol dsEdit.snmp.privPassphrase=Priv passphrase -dsEdit.snmp.engineId=\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 (ID) \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440\u0430 -dsEdit.snmp.contextEngine=\u041f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440 \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0430 dsEdit.snmp.contextName=\u0418\u043c\u044f \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0430 dsEdit.snmp.retries=\u041f\u043e\u0432\u0442\u043e\u0440\u044b dsEdit.snmp.timeout=\u0412\u0440\u0435\u043c\u044f \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f (\u043c\u0441) diff --git a/webapp-resources/messages_zh.properties b/webapp-resources/messages_zh.properties index 05251d6135..b889a2f065 100644 --- a/webapp-resources/messages_zh.properties +++ b/webapp-resources/messages_zh.properties @@ -743,8 +743,6 @@ dsEdit.snmp.none=(\u65e0) dsEdit.snmp.authPassphrase=Auth passphrase dsEdit.snmp.privProtocol=Priv protocol dsEdit.snmp.privPassphrase=Priv passphrase -dsEdit.snmp.engineId=\u5f15\u64ce\u6807\u8bc6\u53f7 -dsEdit.snmp.contextEngine=\u4e0a\u4e0b\u6587\u5f15\u64ce dsEdit.snmp.contextName=\u4e0a\u4e0b\u6587\u540d\u79f0 dsEdit.snmp.retries=\u91cd\u8bd5 dsEdit.snmp.timeout=\u8d85\u65f6 (\u6beb\u79d2)
" onclick="snmpTest();"/>