/** ** Main client thread loop */ public void run() { this.setRunStatus(THREAD_RUNNING); this.threadStarted(); try { this.openSocket(); this.inputThread = new InputThread(this.socket, this.readTimeout, this.ioThreadLock); this.outputThread = new OutputThread(this.socket, this.ioThreadLock); this.inputThread.start(); this.outputThread.start(); synchronized (this.ioThreadLock) { while (this.inputThread.isRunning() || this.outputThread.isRunning()) { try { this.ioThreadLock.wait(); } catch (Throwable t) { } } } } catch (NoRouteToHostException nrthe) { Print.logInfo("Client:ControlThread - Unable to reach " + this.host + ":" + this.port); nrthe.printStackTrace(); } catch (Throwable t) { Print.logInfo("Client:ControlThread - " + t); t.printStackTrace(); } finally { this.closeSocket(); } this.setRunStatus(THREAD_STOPPED); this.threadStopped(); }
public void run() { StringBuffer data = new StringBuffer(); Print.logDebug("Client:InputThread started"); while (true) { data.setLength(0); boolean timeout = false; try { if (this.readTimeout > 0L) { this.socket.setSoTimeout((int) this.readTimeout); } ClientSocketThread.socketReadLine(this.socket, -1, data); } catch (InterruptedIOException ee) { // SocketTimeoutException ee) { // error("Read interrupted (timeout) ..."); if (getRunStatus() != THREAD_RUNNING) { break; } timeout = true; // continue; } catch (Throwable t) { Print.logError("Client:InputThread - " + t); t.printStackTrace(); break; } if (!timeout || (data.length() > 0)) { ClientSocketThread.this.handleMessage(data.toString()); } } synchronized (this.threadLock) { this.isRunning = false; Print.logDebug("Client:InputThread stopped"); this.threadLock.notify(); } }
/* start UDP listener */ private ServerSocketThread _startUDP(int port) throws Throwable { ServerSocketThread sst = null; /* create server socket */ try { sst = new ServerSocketThread(ServerSocketThread.createDatagramSocket(port)); } catch (Throwable t) { // trap any server exception Print.logException("ServerSocket error", t); throw t; } /* initialize */ sst.setTextPackets(Constants.ASCII_PACKETS); sst.setBackspaceChar(null); // no backspaces allowed sst.setLineTerminatorChar(Constants.ASCII_LINE_TERMINATOR); sst.setIgnoreChar(Constants.ASCII_IGNORE_CHARS); sst.setMaximumPacketLength(Constants.MAX_PACKET_LENGTH); sst.setMinimumPacketLength(Constants.MIN_PACKET_LENGTH); sst.setIdleTimeout(TrackServer.udpTimeout_idle); sst.setPacketTimeout(TrackServer.udpTimeout_packet); sst.setSessionTimeout(TrackServer.udpTimeout_session); sst.setTerminateOnTimeout(Constants.TERMINATE_ON_TIMEOUT); sst.setClientPacketHandlerClass(TrackClientPacketHandler.class); /* start thread */ Print.logInfo( "Starting UDP listener thread on port " + port + " [timeout=" + sst.getSessionTimeout() + "ms] ..."); sst.start(); this.udpThread.add(sst); return sst; }
public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); InitJ1587DescriptionProvider(); RTProperties cmdLineProps = RTConfig.getCommandLineProperties(); long fault = EncodeFault(cmdLineProps); Print.sysPrintln("Fault : " + fault + " [0x" + StringTools.toHexString(fault) + "]"); Print.sysPrintln("String: " + GetPropertyString(fault)); Print.sysPrintln("Desc : " + GetFaultDescription(fault, null)); }
protected DCServerFactory.ResultCode sendEmail( String frEmail, String toEmail, String subj, String body) { if (StringTools.isBlank(frEmail)) { Print.logError("'From' Email address not specified"); return DCServerFactory.ResultCode.TRANSMIT_FAIL; } else if (StringTools.isBlank(toEmail) || !CommandPacketHandler.validateAddress(toEmail)) { Print.logError("'To' SMS Email address invalid, or not specified"); return DCServerFactory.ResultCode.TRANSMIT_FAIL; } else if (StringTools.isBlank(subj) && StringTools.isBlank(body)) { Print.logError("Command string not specified"); return DCServerFactory.ResultCode.INVALID_ARG; } else { try { Print.logInfo("SMS email: to <" + toEmail + ">"); Print.logDebug(" From : " + frEmail); Print.logDebug(" To : " + toEmail); Print.logDebug(" Subject: " + subj); Print.logDebug(" Message: " + body); SendMail.send(frEmail, toEmail, null, null, subj, body, null); return DCServerFactory.ResultCode.SUCCESS; } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException // this will fail if JavaMail support for SendMail is not available. Print.logWarn("SendMail error: " + t); return DCServerFactory.ResultCode.TRANSMIT_FAIL; } } }
/** * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web * service ** @return The virtual DBRecord (cannot be saved or reloaded) */ @SuppressWarnings("unchecked") public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException { String CMD_dbget = DBFactory.CMD_dbget; String TAG_Response = servReq.getTagResponse(); String TAG_Record = DBFactory.TAG_Record; String ATTR_command = servReq.getAttrCommand(); String ATTR_result = servReq.getAttrResult(); /* send request / get response */ Document xmlDoc = null; try { xmlDoc = servReq.sendRequest( CMD_dbget, new ServiceRequest.RequestBody() { public StringBuffer appendRequestBody(StringBuffer sb, int indent) { return DBRecordKey.this.toRequestXML(sb, indent); } }); } catch (IOException ioe) { Print.logException("Error", ioe); throw new DBException("Request read error", ioe); } /* parse 'GTSResponse' */ Element gtsResponse = xmlDoc.getDocumentElement(); if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) { Print.logError("Request XML does not start with '%s'", TAG_Response); throw new DBException("Response XML does not begin eith '" + TAG_Response + "'"); } /* request command/argument */ String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command)); String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result)); if (StringTools.isBlank(result)) { result = StringTools.trim(gtsResponse.getAttribute("type")); } if (!result.equalsIgnoreCase("success")) { Print.logError("Response indicates failure"); throw new DBException("Response does not indicate 'success'"); } /* Record */ NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record); if (rcdList.getLength() <= 0) { Print.logError("No 'Record' tags"); throw new DBException("GTSResponse does not contain any 'Record' tags"); } Element rcdElem = (Element) rcdList.item(0); /* return DBRecord */ gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem); dbr.setVirtual(true); return dbr; }
public final User getUser() { if (this.user == null) { String userID = this.getUserID(); Print.logDebug("[Optimize] Retrieving User record: " + userID); try { this.user = User.getUser(this.getAccount(), userID); // 'this.asset' may still be null if the asset was not found } catch (DBException dbe) { // may be caused by "java.net.ConnectException: Connection refused: connect" Print.logError("User not found: " + this.getAccountID() + "/" + userID); this.user = null; } } return this.user; }
private static void usage() { Print.logInfo("Usage:"); Print.logInfo(" java ... " + StatusCode.class.getName() + " {options}"); Print.logInfo("Options:"); Print.logInfo(" -account=<id> Account ID owning StatusCode"); Print.logInfo(" -device=<id> Device ID owning StatusCode (use '/' for ALL)"); Print.logInfo(" -code=<id> StatusCode to create/delete/edit"); Print.logInfo(" -create Create a new StatusCode"); Print.logInfo(" -edit To edit an existing StatusCode"); Print.logInfo(" -delete Delete specified StatusCode"); System.exit(1); }
private static void usage() { Print.logInfo("Usage:"); Print.logInfo(" java ... " + ClientSocketThread.class.getName() + " {options}"); Print.logInfo("'Send' Options:"); Print.logInfo(" -host=<host> The destination host"); Print.logInfo(" -port=<port> The destination port"); Print.logInfo(" -send=<data> The data to send (prefix with '0x' for hex data)"); Print.logInfo("'Receive' Options (not yet implemented):"); Print.logInfo(" -port=<port> The port on which to listen for incoming data"); Print.logInfo(" -recv Set to 'receive' mode"); System.exit(1); }
public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); long now = DateTime.getCurrentTimeSec(); long sts = now - DateTime.DaySeconds(3); long ets = now; GoogleChartTemperature gct = new GoogleChartTemperature(); try { gct.setSize(700, 400); gct.setTitle(Color.black, 16, "Temperature"); gct.setTemperatureRange(1, F2C(0.0), F2C(130.0), 10); gct.setDateRange(new DateTime(sts), new DateTime(ets), 8); gct.setDateFormat("MM/dd"); gct.setTimeFormat("HH:mm:ss"); int setCount = 3; int tempCount = 15; gct._addRandomSampleData(setCount, tempCount); System.out.println(gct.toString()); } catch (Throwable th) { Print.logException("Error", th); System.exit(1); } }
/* validate the syntax of the specified list of multiple email addresses */ public static boolean validateAddresses(String addrs, boolean acceptSMS) { if (StringTools.isBlank(addrs)) { // blank is ok in this case return true; } else if (acceptSMS) { // allow "sms:123456789" format String addrArry[] = StringTools.parseStringArray(addrs, ','); if (addrArry.length == 0) { return false; } for (int i = 0; i < addrArry.length; i++) { String em = addrArry[i].trim(); if (StringTools.isBlank(em)) { // individual addresses not allowed return false; } else if (SMSOutboundGateway.StartsWithSMS(em)) { // TODO: for now, accept as-is } else if (!validateAddress(em)) { return false; } } return true; } else { // true email addresses only try { return SendMail.validateAddresses(addrs); } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException // this will fail if JavaMail support for SendMail is not available. Print.logError("*** SendMail error: " + t); return false; } } }
protected boolean _setDevice(Device device, String ipAddress, int clientPort) { /* valid device? */ if (device == null) { return false; } /* validate ID address */ DataTransport dataXPort = device.getDataTransport(); if ((ipAddress != null) && !dataXPort.isValidIPAddress(ipAddress)) { Print.logError( "Invalid IPAddr: " + device.getAccountID() + "/" + device.getDeviceID() + " Found=" + ipAddress + " Expect=" + dataXPort.getIpAddressValid()); return false; } /* update device */ this.device = device; this.dataXPort = dataXPort; this.dataXPort.setIpAddressCurrent(ipAddress); // FLD_ipAddressCurrent this.dataXPort.setRemotePortCurrent(clientPort); // FLD_remotePortCurrent this.dataXPort.setDeviceCode(this.getDeviceCode()); // FLD_deviceCode this.device.setLastTotalConnectTime(DateTime.getCurrentTimeSec()); // FLD_lastTotalConnectTime /* ok */ return true; }
protected String getStringProperty(Device device, String key, String dft) { DCServerConfig dcs = (device != null) ? DCServerFactory.getServerConfig(device.getDeviceCode()) : null; String prop = null; if (dcs != null) { prop = dcs.getStringProperty(key, dft); Print.logInfo("DCServerConfig property '" + key + "' ==> " + prop); if (StringTools.isBlank(prop) && RTConfig.hasProperty(key)) { Print.logInfo("(RTConfig property '" + key + "' ==> " + RTConfig.getString(key, "") + ")"); } } else { prop = RTConfig.getString(key, dft); Print.logInfo("RTConfig property '" + key + "' ==> " + prop); } return prop; }
public GoogleSig getSignature() { if (!this.signature_init) { this.signature_init = true; String key = this.getAuthorization(); if (!StringTools.isBlank(key) && key.startsWith(CLIENT_ID_PREFIX)) { String sigKey = this.getProperties().getString(PROP_signatureKey, ""); if (!StringTools.isBlank(sigKey)) { Print.logWarn("Setting SignatureKey: " + sigKey); this.signature = new GoogleSig(sigKey); } else { Print.logWarn("No signatureKey ..."); } } } return this.signature; }
/* private constructor */ private TrackServer(int tcpPorts[], int udpPorts[], int commandPort) throws Throwable { int listeners = 0; // Start TCP listeners if (!ListTools.isEmpty(tcpPorts)) { for (int i = 0; i < tcpPorts.length; i++) { int port = tcpPorts[i]; if (ServerSocketThread.isValidPort(port)) { try { this._startTCP(port); listeners++; } catch (java.net.BindException be) { Print.logError("TCP: Error binding to port: %d", port); } } else { throw new Exception("TCP: Invalid port number: " + port); } } } // Start UDP listeners if (!ListTools.isEmpty(udpPorts)) { for (int i = 0; i < udpPorts.length; i++) { int port = udpPorts[i]; if (ServerSocketThread.isValidPort(port)) { try { ServerSocketThread sst = this._startUDP(port); if (this.udpSocket == null) { this.udpSocket = sst.getDatagramSocket(); } listeners++; } catch (java.net.BindException be) { Print.logError("UDP: Error binding to port: %d", port); } } else { throw new Exception("UDP: Invalid port number: " + port); } } } /* do we have any active listeners? */ if (listeners <= 0) { Print.logWarn("No active device communication listeners!"); } }
private static void usage() { Print.logInfo("Usage:"); Print.logInfo(" java ... " + AccountString.class.getName() + " {options}"); Print.logInfo("Common Options:"); Print.logInfo(" -account=<id> Acount ID which owns AccountString"); Print.logInfo(" -string=<id> String ID to create/edit"); Print.logInfo(" -create Create a new AccountString"); Print.logInfo(" -edit Edit an existing (or newly created) AccountString"); Print.logInfo(" -delete Delete specified AccountString"); System.exit(1); }
protected Device loadDevice(String acctID, String devID) { if (StringTools.isBlank(acctID)) { return this.loadDevice(devID); // load ad ModemID } else { try { Account account = Account.getAccount(acctID); if (account == null) { Print.logError("Account-ID not found: " + acctID); return null; } else { Device dev = Transport.loadDeviceByTransportID(account, devID); return dev; } } catch (DBException dbe) { Print.logError("Error getting Device: " + acctID + "/" + devID + " [" + dbe + "]"); return null; } } }
/* extract email address from the specified string */ public static String getEMailAddress(String addr) { // extract/normalize email address try { return SendMail.getEMailAddress(addr); } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException // this will fail if JavaMail support for SendMail is not available. Print.logWarn("SendMail error: " + t); return null; } }
public void run() { String command = null; Print.logInfo("Client:OutputThread started"); while (true) { /* wait for commands */ synchronized (this.cmdList) { while ((this.cmdList.size() <= 0) && (getRunStatus() == THREAD_RUNNING)) { try { this.cmdList.wait(5000L); } catch (Throwable t) { /*ignore*/ } } if (getRunStatus() != THREAD_RUNNING) { break; } command = this.cmdList.remove(0).toString(); } /* send commands */ try { ClientSocketThread.socketWriteLine(this.socket, command); } catch (Throwable t) { Print.logError("Client:OutputThread - " + t); t.printStackTrace(); break; } } if (getRunStatus() == THREAD_RUNNING) { Print.logWarn("Client:OutputThread stopped due to error"); } else { Print.logInfo("Client:OutputThread stopped"); } synchronized (this.threadLock) { this.isRunning = false; Print.logInfo("Client:OutputThread stopped"); this.threadLock.notify(); } }
/** ** Add SMS Gateway support provider */ public static void AddSMSGateway(String name, SMSOutboundGateway smsGW) { /* validate name */ if (StringTools.isBlank(name)) { Print.logWarn("SMS Gateway name is blank"); return; } else if (smsGW == null) { Print.logWarn("SMS Gateway handler is null"); return; } /* initialize map? */ if (SmsGatewayHandlerMap == null) { SmsGatewayHandlerMap = new HashMap<String, SMSOutboundGateway>(); } /* save handler */ SmsGatewayHandlerMap.put(name.toLowerCase(), smsGW); Print.logDebug("Added SMS Gateway Handler: " + name); }
private Document GetXMLDocument(String url) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream input = HTMLTools.inputStream_GET(url, 5000); InputStreamReader reader = new InputStreamReader(input, ENCODING_UTF8); InputSource inSrc = new InputSource(reader); inSrc.setEncoding(ENCODING_UTF8); return db.parse(inSrc); } catch (ParserConfigurationException pce) { Print.logError("Parse error: " + pce); return null; } catch (SAXException se) { Print.logError("Parse error: " + se); return null; } catch (IOException ioe) { Print.logError("IO error: " + ioe); return null; } }
/** ** Main entery point for debugging/testing */ public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); Print.setAllOutputToStdout(true); Print.setEncoding(ENCODING_UTF8); String accountID = RTConfig.getString(ARG_ACCOUNT, "demo"); GoogleGeocodeV2 gn = new GoogleGeocodeV2("google", null, null); /* reverse geocode */ if (RTConfig.hasProperty(ARG_REVGEOCODE)) { GeoPoint gp = new GeoPoint(RTConfig.getString(ARG_REVGEOCODE, null)); if (!gp.isValid()) { Print.logInfo("Invalid GeoPoint specified"); System.exit(1); } Print.logInfo("Reverse-Geocoding GeoPoint: " + gp); Print.sysPrintln( "RevGeocode = " + gn.getReverseGeocode(gp, null /*localeStr*/, false /*cache*/)); // Note: Even though the values are printed in UTF-8 character encoding, the // characters may not appear to be property displayed if the console display // does not support UTF-8. System.exit(0); } /* no options */ Print.sysPrintln("No options specified"); System.exit(1); }
/** * ** Traverses the DBFactory dependency tree, creating a DBFactoryTree ** @param level The * current tree level ** @param dbFact The current DBFactory to add ** @param parentNode The * parent node to which a new DBFactoryNode child will be added ** @param addedTables A set of * table names added to the current DBFactoryTree * */ private static void _traverseDBFactoryTree( int level, DBFactory<? extends DBRecord> dbFact, DBFactoryTree parentNode, Set<String> addedTables) { /* no DBFactory? */ if (dbFact == null) { Print.logError("Null DBFactory!"); return; } String utableName = dbFact.getUntranslatedTableName(); /* already added? */ if (addedTables.contains(utableName)) { return; } addedTables.add(utableName); /* add this node */ // Print.logInfo(StringTools.replicateString(" ",level) + dbFact.getUntranslatedTableName()); DBFactoryTree dbFactNode = new DBFactoryTree(level, parentNode, dbFact); parentNode.addChild(dbFactNode); /* find dependent children */ DBFactory<? extends DBRecord> childFact[] = dbFact.getChildFactories(); for (int i = 0; i < childFact.length; i++) { int index = childFact[i].getParentTables().indexOf(utableName); if (level == index) { DBFactoryTree._traverseDBFactoryTree(level + 1, childFact[i], dbFactNode, addedTables); } else if (!addedTables.contains(childFact[i].getUntranslatedTableName())) { Print.logWarn( "Skipping table in heiarchy: " + utableName + " ==> " + childFact[i].getUntranslatedTableName()); } } }
/** * ** Invokes all listeners with an assciated command ** @param r a string that may specify a * command (possibly one ** of several) associated with the event */ protected void invokeListeners(String r) { if (this.actionListeners != null) { for (Iterator i = this.actionListeners.iterator(); i.hasNext(); ) { ActionListener al = (ActionListener) i.next(); ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, r); try { al.actionPerformed(ae); } catch (Throwable t) { Print.logError("Exception: " + t.getMessage()); } } } }
/* validate the syntax of the specified single email address */ public static boolean validateAddress(String addr) { if (StringTools.isBlank(addr)) { // blanks not alowed here return false; // fail quickly } else { try { return SendMail.validateAddress(addr); } catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException // this will fail if JavaMail support for SendMail is not available. Print.logWarn("SendMail error: " + t); return false; } } }
/** ** Main entery point for debugging/testing */ public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); Print.setAllOutputToStdout(true); Print.setEncoding(ENCODING_UTF8); /* host */ String host = RTConfig.getString("host", null); if (!StringTools.isBlank(host)) { HOST_PRIMARY = host; } /* GeoPoint */ GeoPoint gp = new GeoPoint(RTConfig.getString("gp", null)); if (!gp.isValid()) { Print.logInfo("Invalid GeoPoint specified"); System.exit(1); } Print.logInfo("Reverse-Geocoding GeoPoint: " + gp); /* Reverse Geocoding */ Nominatim gn = new Nominatim("nominatim", null, RTConfig.getCommandLineProperties()); Print.sysPrintln("RevGeocode = " + gn.getReverseGeocode(gp, null /*localeStr*/)); }
/** * ** Sets the DBRecord for this node ** @param record The DBRecord to set ** @return True if the * DBRecord was successfully set, false otherwise */ public boolean setDBRecord(DBRecord<?> record) { /* pre-checks */ this.dbRecord = null; if (record == null) { return false; } else if (!this.hasDBFactory()) { // TODO: we probably could just retrieve the DBFactory from the DBRecord Print.logError("DBFactory is not defined!"); return false; } /* check DBFactory */ DBFactory<?> rcdFact = DBRecord.getFactory(record); if (!this.getDBFactory().equals(rcdFact)) { Print.logError("Invalid DBFactory for specified DBRecord!"); return false; } /* set DBRecord */ this.dbRecord = record; return true; }
/* start TCP listener */ private void _startTCP(int port) throws Throwable { ServerSocketThread sst = null; /* create server socket */ try { sst = new ServerSocketThread(port); } catch (Throwable t) { // trap any server exception Print.logException("ServerSocket error", t); throw t; } /* initialize */ sst.setTextPackets(Constants.ASCII_PACKETS); sst.setBackspaceChar(null); // no backspaces allowed sst.setLineTerminatorChar(Constants.ASCII_LINE_TERMINATOR); sst.setIgnoreChar(Constants.ASCII_IGNORE_CHARS); sst.setMaximumPacketLength(Constants.MAX_PACKET_LENGTH); sst.setMinimumPacketLength(Constants.MIN_PACKET_LENGTH); sst.setIdleTimeout(TrackServer.tcpTimeout_idle); // time between packets sst.setPacketTimeout( TrackServer.tcpTimeout_packet); // time from start of packet to packet completion sst.setSessionTimeout(TrackServer.tcpTimeout_session); // time for entire session sst.setTerminateOnTimeout(Constants.TERMINATE_ON_TIMEOUT); sst.setClientPacketHandlerClass(TrackClientPacketHandler.class); sst.setLingerTimeoutSec(Constants.LINGER_ON_CLOSE_SEC); /* start thread */ Print.logInfo( "Starting TCP listener thread on port " + port + " [timeout=" + sst.getSessionTimeout() + "ms] ..."); sst.start(); this.tcpThread.add(sst); }
public HeaderColumnTemplate getHeaderColumnTemplate(DataColumnTemplate dct) { if (dct != null) { String keyName = dct.getKeyName(); if (this.headerColumnMap.containsKey(keyName)) { return this.headerColumnMap.get(keyName); } else { HeaderColumnTemplate hct = this._createHeaderColumnTemplate(dct); this.headerColumnMap.put(keyName, hct); return hct; } } else { Print.logStackTrace("DataColumnTemplate is null!"); return null; } }
public BodyColumnTemplate getBodyColumnTemplate(DataColumnTemplate dct) { if (dct != null) { String keyName = dct.getKeyName(); if (this.bodyColumnMap.containsKey(keyName)) { return this.bodyColumnMap.get(keyName); } else { BodyColumnTemplate bct = this._createBodyColumnTemplate(dct); this.bodyColumnMap.put(keyName, bct); return bct; } } else { Print.logStackTrace("DataColumnTemplate is null!"); return null; } }