/** ** 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(); }
/* 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; }
/** ** Reads/returns the specified CompileTime template file */ private static String readTemplate(File tf, String pkgName) { /* read template data */ byte templData[] = FileTools.readFile(tf); if (templData == null) { Print.errPrintln("\nUnable to read Input/Template file: " + tf); return null; } else if (templData.length == 0) { Print.errPrintln("\nInput/Template file is empty: " + tf); return null; } /* return template String */ String templateText = StringTools.toStringValue(templData); if (!StringTools.isBlank(pkgName) && !StringTools.isBlank(templateText)) { String lines[] = StringTools.split(templateText, '\n', false); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith(JAVA_PACKAGE_)) { lines[i] = CompiletimeVars.packageLine(pkgName); return StringTools.join(lines, '\n') + "\n"; } } StringBuffer sb = new StringBuffer(); sb.append(CompiletimeVars.packageLine(pkgName)).append("\n"); sb.append(templateText); return sb.toString(); } else { return templateText; } }
/** * ** Returns an I18N.Text instance used for lazy localization.<br> * ** (use in XML loaders to avoid expression matches when auto-updating * 'LocalStrings_XX.properties') ** @param pkg The package name ** @param key The localization key * ** @param dft The default localized text ** @param showError If true, a stacktrace will be * display if the key is invalid. ** @return An I18N.Text instance used for lazy localization */ public static I18N.Text parseText(String pkg, String key, String dft, boolean showError) { if (dft == null) { Print.logStackTrace("Default value is null!"); return new I18N.Text(pkg, key, ""); } else if (!StringTools.isBlank(key)) { return new I18N.Text(pkg, key, dft); } else if (!StringTools.startsWithIgnoreCase(dft, I18N_KEY_STARTE) && !StringTools.startsWithIgnoreCase(dft, I18N_KEY_STARTC)) { if (showError) { Print.logStackTrace( "Invalid/missing key definition!\n" + "Package: " + pkg + "\n" + "Key : " + key + "\n" + "Default: " + dft); } return new I18N.Text(pkg, null, dft); } else { int ks = I18N_KEY_STARTE.length(); int ke = dft.indexOf(I18N_KEY_END, ks); if (ke < ks) { return new I18N.Text(pkg, null, dft); // ']' is missing, return string as-is } String k = dft.substring(ks, ke).trim(); String v = dft.substring(ke + I18N_KEY_END.length()).trim(); return new I18N.Text(pkg, k, v); } }
public static void getDay(DAY day) { if (day == DAY.SUNDAY) { Print.pbl("sunday"); } else if (day == DAY.MONDAY) { Print.pbl("monday"); } }
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(); } }
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)); }
public static void main(String[] args) throws Exception { ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); // Enable asserts new ProcessFiles(new AtUnit(), "class").start(args); if (failures == 0) Print.print("OK (" + testsRun + " tests)"); else { Print.print("(" + testsRun + " tests)"); Print.print("\n>>> " + failures + " FAILURE" + (failures > 1 ? "S" : "") + " <<<"); for (String failed : failedTests) Print.print(" " + failed); } }
public void process(File cFile) { try { String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile)); if (!cName.contains("")) return; // Ignore unpackaged classes testClass = Class.forName(cName); } catch (Exception e) { throw new RuntimeException(e); } TestMethods testMethods = new TestMethods(); Method creator = null; Method cleanup = null; for (Method m : testClass.getDeclaredMethods()) { testMethods.addIfTestMethod(m); if (creator == null) creator = checkForCreatorMethod(m); if (cleanup == null) cleanup = checkForCleanupMethod(m); } if (testMethods.size() > 0) { if (creator == null) try { if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) { Print.print("Error: " + testClass + " default constructor must be public"); System.exit(1); } } catch (NoSuchMethodException e) { // Synthesized default constructor; OK } Print.print(testClass.getName()); } for (Method m : testMethods) { Print.printnb(" . " + m.getName() + " "); try { Object testObject = createTestObject(creator); boolean success = false; try { if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject); else { m.invoke(testObject); success = true; // If no assert fails } } catch (InvocationTargetException e) { // Actual exception is inside e: Print.print(e.getCause()); } Print.print(success ? "" : "(failed)"); testsRun++; if (!success) { failures++; failedTests.add(testClass.getName() + ": " + m.getName()); } if (cleanup != null) cleanup.invoke(testObject, testObject); } catch (Exception e) { throw new RuntimeException(e); } } }
/** * ** 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; }
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; } } }
/** ** Apply replacements/conditionals and write output */ public static void writeOutputSource(String inputSource, File outputFile) throws IOException { String outputSource = inputSource; if (StringTools.isBlank(outputSource)) { // throw new IOException("Output Source is empty"); return; } /* custom map */ Map<String, String> customMap = new HashMap<String, String>() { @Override public String get(Object key) { String ks = StringTools.trim(key); if (ks.toLowerCase().endsWith(".md5")) { String K = ks.substring(0, ks.length() - ".md5".length()); String V = RTConfig._getString(K, null, true /*dftOK*/); if (V != null) { return StringTools.trim(FileTools.getHash_MD5(V.getBytes())).toUpperCase(); } else { return null; } } else { return null; } } }; /* replace standard runtime vars in text (ie. %{var=value}) */ // -- replace %{var=value} outputSource = RTConfig.insertKeyValues(outputSource, STR_DELIM, END_DELIM, DFT_DELIM, customMap); // -- replace /#{var=value}#/ outputSource = RTConfig.insertKeyValues(outputSource, STR_CDELIM, END_CDELIM, DFT_CDELIM, customMap); /* conditional code? */ outputSource = CompiletimeVars.getConditionalSource(outputSource); /* write output */ if (outputFile != null) { Print.sysPrintln("Output to file: " + outputFile); boolean didWrite = FileTools.writeFile(outputSource.getBytes(), outputFile); if (!didWrite) { throw new IOException("Unable to write output file."); } } else { // -- write to stdout Print.sysPrintln(outputSource); } }
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 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; }
public Entry getReferencedEntry() { Entry entry = getRuntimeEntry(this.getKey()); if (entry == null) { Print.logStackTrace("Entry reference not found: " + this.getKey()); } return entry; }
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); } }
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; }
/* 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; } } }
/* 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); }
/* 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(); } }
/** ** Prints all LocalString keys for this I18N instance */ public void printKeyValues() { Enumeration e = this.getKeys(); if (e != null) { for (; e.hasMoreElements(); ) { String k = (String) e.nextElement(); String v = this.getString(k, "?"); Print.logInfo("Key:" + k + " Value:" + v); } } }
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; } } }
protected static Document GetXMLDocument(String url, int timeoutMS) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream input = HTMLTools.inputStream_GET(url, timeoutMS); 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; } }
public static void main(String argv[]) { RTConfig.setCommandLineArgs(argv); long ts = DateTime.getCurrentTimeSec(); double C = -5.6; TemperatureSet TSList[] = new TemperatureSet[3]; for (int s = 0; s < TSList.length; s++) { TemperatureSet TS = new TemperatureSet(); for (int i = 0; i < 10; i++) { long tempTS = ts + (12345L * (i + 1) * (s + 1)); double tempC = C + (2.3 * i) + (1.1 * s); Print.logInfo(s + ":" + i + "] Adding " + tempTS + ", " + tempC); TS.addTemperature(tempTS, tempC); } TSList[s] = TS; } String t = TemperatureSet.CreateGoogleDataTableJavaScript(false, TSList); Print.sysPrintln(t); }
/** ** 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); }