public void test_countTokens() { // Test for method int java.util.StringTokenizer.countTokens() StringTokenizer st = new StringTokenizer("This is a test String"); Assertion.AssertEquals("Incorrect token count returned", 5, st.CountTokens()); }
/// <summary> /// Retrieve an array of <tt>InetAddress</tt> created from a property /// value containting a <tt>delim</tt> separated list of hostnames and/or /// ipaddresses. /// </summary> /// <remarks> /// Retrieve an array of <tt>InetAddress</tt> created from a property /// value containting a <tt>delim</tt> separated list of hostnames and/or /// ipaddresses. /// </remarks> public static IPAddress[] GetInetAddressArray(string key, string delim, IPAddress [] def) { string p = GetProperty(key); if (p != null) { StringTokenizer tok = new StringTokenizer(p, delim); int len = tok.CountTokens(); IPAddress[] arr = new IPAddress[len]; for (int i = 0; i < len; i++) { string addr = tok.NextToken(); try { arr[i] = Extensions.GetAddressByName(addr); } catch (UnknownHostException uhe) { if (_log.Level > 0) { _log.WriteLine(addr); Runtime.PrintStackTrace(uhe, _log); } return(def); } } return(arr); } return(def); }
private static IDictionary <String, String> InternalParse(String fixMsg) { if (fixMsg == null) { throw new FixMsgUnrecognizableException("Unrecognizable fix message, message is a null string"); } if (fixMsg.Length == 0) { throw new FixMsgUnrecognizableException("Unrecognizable fix message, message is a empty string"); } IDictionary <String, String> parsedMessage = new HashMap <String, String>(); StringTokenizer tok = new StringTokenizer(fixMsg, soh); if (tok.CountTokens() < 4) { throw new FixMsgUnrecognizableException("Unrecognizable fix message, number of tokens is less then 4", fixMsg); } while (tok.HasMoreTokens()) { String filed = tok.NextToken(); StringTokenizer innerTokens = new StringTokenizer(filed, "="); if (innerTokens.CountTokens() != 2) { continue; } String tag = innerTokens.NextToken(); String value = innerTokens.NextToken(); parsedMessage.Put(tag, value); } return(parsedMessage); }
/// <summary>Set up a puzzle board to the given size.</summary> /// <remarks> /// Set up a puzzle board to the given size. /// Boards may be asymmetric, but the squares will always be divided to be /// more cells wide than they are tall. For example, a 6x6 puzzle will make /// sub-squares that are 3x2 (3 cells wide, 2 cells tall). Clearly that means /// the board is made up of 2x3 sub-squares. /// </remarks> /// <param name="stream">The input stream to read the data from</param> /// <exception cref="System.IO.IOException"/> public Sudoku(InputStream stream) { BufferedReader file = new BufferedReader(new InputStreamReader(stream, Charsets.Utf8 )); string line = file.ReadLine(); IList <int[]> result = new AList <int[]>(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line); int size = tokenizer.CountTokens(); int[] col = new int[size]; int y = 0; while (tokenizer.MoveNext()) { string word = tokenizer.NextToken(); if ("?".Equals(word)) { col[y] = -1; } else { col[y] = System.Convert.ToInt32(word); } y += 1; } result.AddItem(col); line = file.ReadLine(); } size = result.Count; board = Sharpen.Collections.ToArray(result, new int[size][]); squareYSize = (int)Math.Sqrt(size); squareXSize = size / squareYSize; file.Close(); }
public static int CalculateTime(string duration) { int min, sec, hr = 0; try { StringTokenizer st = new StringTokenizer(duration, "."); if (st.CountTokens() == 3) { hr = Convert.ToInt32(st.NextToken()); } min = Convert.ToInt32(st.NextToken()); sec = Convert.ToInt32(st.NextToken()); } catch (Exception e) { Console.WriteLine(e); StringTokenizer st = new StringTokenizer(duration, ":"); if (st.CountTokens() == 3) { hr = Convert.ToInt32(st.NextToken()); } min = Convert.ToInt32(st.NextToken()); sec = Convert.ToInt32(st.NextToken()); } int time = (hr * 3600 + min * 60 + sec) * 1000; return(time); }
public void test_ConstructorLjava_lang_StringLjava_lang_String() { // Test for method java.util.StringTokenizer(java.lang.String, // java.lang.String) StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":"); Assertion.Assert("Created incorrect tokenizer", st.CountTokens() == 5 && (st.NextElement().Equals("This"))); }
/// <exception cref="Org.Apache.Commons.Cli.ParseException"/> public static TestTFileSeek.IntegerRange Parse(string s) { StringTokenizer st = new StringTokenizer(s, " \t,"); if (st.CountTokens() != 2) { throw new ParseException("Bad integer specification: " + s); } int from = System.Convert.ToInt32(st.NextToken()); int to = System.Convert.ToInt32(st.NextToken()); return(new TestTFileSeek.IntegerRange(from, to)); }
public static string[] Split(string s, string tag) { StringTokenizer str = new StringTokenizer(s, tag); string[] result = new string[str.CountTokens()]; int index = 0; for (; str.HasMoreTokens();) { result[index++] = str.NextToken(); } return(result); }
/// <summary> /// Construct a SID from it's textual representation such as /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>. /// </summary> /// <remarks> /// Construct a SID from it's textual representation such as /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>. /// </remarks> /// <exception cref="SharpCifs.Smb.SmbException"></exception> public Sid(string textual) { StringTokenizer st = new StringTokenizer(textual, "-"); if (st.CountTokens() < 3 || !st.NextToken().Equals("S")) { // need S-N-M throw new SmbException("Bad textual SID format: " + textual); } Revision = byte.Parse(st.NextToken()); string tmp = st.NextToken(); long id = 0; if (tmp.StartsWith("0x")) { //id = long.Parse(Sharpen.Runtime.Substring(tmp, 2), 16); id = long.Parse(Runtime.Substring(tmp, 2)); } else { id = long.Parse(tmp); } IdentifierAuthority = new byte[6]; for (int i = 5; id > 0; i--) { IdentifierAuthority[i] = unchecked ((byte)(id % 256)); id >>= 8; } SubAuthorityCount = unchecked ((byte)st.CountTokens()); if (SubAuthorityCount > 0) { SubAuthority = new int[SubAuthorityCount]; for (int i1 = 0; i1 < SubAuthorityCount; i1++) { SubAuthority[i1] = (int)(long.Parse(st.NextToken()) & unchecked (0xFFFFFFFFL)); } } }
/// <summary> /// Executes the specified string command in a separate process with the /// specified environment and working directory. /// /// <para>This is a convenience method. An invocation of the form /// <tt>exec(command, envp, dir)</tt> /// behaves in exactly the same way as the invocation /// <tt><seealso cref="#exec(String[], String[], File) exec"/>(cmdarray, envp, dir)</tt>, /// where <code>cmdarray</code> is an array of all the tokens in /// <code>command</code>. /// /// </para> /// <para>More precisely, the <code>command</code> string is broken /// into tokens using a <seealso cref="StringTokenizer"/> created by the call /// <code>new <seealso cref="StringTokenizer"/>(command)</code> with no /// further modification of the character categories. The tokens /// produced by the tokenizer are then placed in the new string /// array <code>cmdarray</code>, in the same order. /// /// </para> /// </summary> /// <param name="command"> a specified system command. /// </param> /// <param name="envp"> array of strings, each element of which /// has environment variable settings in the format /// <i>name</i>=<i>value</i>, or /// <tt>null</tt> if the subprocess should inherit /// the environment of the current process. /// </param> /// <param name="dir"> the working directory of the subprocess, or /// <tt>null</tt> if the subprocess should inherit /// the working directory of the current process. /// </param> /// <returns> A new <seealso cref="Process"/> object for managing the subprocess /// </returns> /// <exception cref="SecurityException"> /// If a security manager exists and its /// <seealso cref="SecurityManager#checkExec checkExec"/> /// method doesn't allow creation of the subprocess /// </exception> /// <exception cref="IOException"> /// If an I/O error occurs /// </exception> /// <exception cref="NullPointerException"> /// If <code>command</code> is <code>null</code>, /// or one of the elements of <code>envp</code> is <code>null</code> /// </exception> /// <exception cref="IllegalArgumentException"> /// If <code>command</code> is empty /// </exception> /// <seealso cref= ProcessBuilder /// @since 1.3 </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public Process exec(String command, String[] envp, File dir) throws IOException public virtual Process Exec(String command, String[] envp, File dir) { if (command.Length() == 0) { throw new IllegalArgumentException("Empty command"); } StringTokenizer st = new StringTokenizer(command); String[] cmdarray = new String[st.CountTokens()]; for (int i = 0; st.HasMoreTokens(); i++) { cmdarray[i] = st.NextToken(); } return(Exec(cmdarray, envp, dir)); }
} // getSql public String GetTableName() { int AD_Table_ID = GetAD_Table_ID(); if (AD_Table_ID != 0) { MTable table = MTable.Get(GetCtx(), AD_Table_ID); String tableName = table.GetTableName(); if (!VAdvantage.Utility.Util.IsEmpty(tableName)) { return(tableName); } } // FROM clause String from = GetFromClause().Trim(); StringTokenizer st = new StringTokenizer(from, " ,\t\n\r\f", false); int tokens = st.CountTokens(); if (tokens == 0) { return(null); } if (tokens == 1) { return(st.NextToken()); } String mainTable = st.NextToken(); if (st.HasMoreTokens()) { String next = st.NextToken(); if (next.Equals("RIGHT", StringComparison.OrdinalIgnoreCase) || next.Equals("LEFT", StringComparison.OrdinalIgnoreCase) || next.Equals("INNER", StringComparison.OrdinalIgnoreCase) || next.Equals("FULL", StringComparison.OrdinalIgnoreCase)) { return(mainTable); } return(next); } return(mainTable); } // getTableName
public static DateTime readDate() { try { Exception e1 = new Exception("Invalid Input."); Exception e2 = new Exception("Date doesn't exist."); Exception e3 = new Exception("Date should be greater than or equal to today."); System.Console.Write("Date Format(MM/dd/yyyy) :"); string date = System.Console.ReadLine(); StringTokenizer st = new StringTokenizer(date, "/"); if (st.CountTokens() != 3) { throw e1; } int month = int.Parse(st.NextToken()); int day = int.Parse(st.NextToken()); int year = int.Parse(st.NextToken()); if (month < 1 || month > 12) { throw e2; } if (year < DateTime.Now.Year) { throw e3; } if (year == DateTime.Now.Year && month < DateTime.Now.Month) { throw e3; } if (year == DateTime.Now.Year && month == DateTime.Now.Month && day < DateTime.Now.Day) { throw e3; } return(new DateTime(year, month, day)); } catch (Exception e) { System.Console.WriteLine("Invalid Input."); throw e; } }
bool ProcessDrop(DragEvent evt, ImageView imageView) { // Attempt to parse clip data with expected format: category||entry_id. // Ignore event if data does not conform to this format. ClipData data = evt.ClipData; if (data != null) { if (data.ItemCount > 0) { ClipData.Item item = data.GetItemAt(0); String textData = (String)item.Text; if (textData != null) { StringTokenizer tokenizer = new StringTokenizer(textData, "||"); if (tokenizer.CountTokens() != 2) { return(false); } int category = -1; int entryId = -1; try { category = Java.Lang.Integer.ParseInt(tokenizer.NextToken()); entryId = Java.Lang.Integer.ParseInt(tokenizer.NextToken()); } catch (NumberFormatException exception) { return(false); } UpdateContentAndRecycleBitmap(category, entryId); // Update list fragment with selected entry. TitlesFragment titlesFrag = (TitlesFragment) FragmentManager.FindFragmentById(Resource.Id.frag_title); titlesFrag.SelectPosition(entryId); return(true); } } } return(false); }
/// <summary>Parses the given Port attribute value (e.g.</summary> /// <remarks> /// Parses the given Port attribute value (e.g. "8000,8001,8002") /// into an array of ports. /// </remarks> /// <param name="portValue">port attribute value</param> /// <returns>parsed array of ports</returns> /// <exception cref="Apache.Http.Cookie.MalformedCookieException"> /// if there is a problem in /// parsing due to invalid portValue. /// </exception> private static int[] ParsePortAttribute(string portValue) { StringTokenizer st = new StringTokenizer(portValue, ","); int[] ports = new int[st.CountTokens()]; try { int i = 0; while (st.HasMoreTokens()) { ports[i] = System.Convert.ToInt32(st.NextToken().Trim()); if (ports[i] < 0) { throw new MalformedCookieException("Invalid Port attribute."); } ++i; } } catch (FormatException e) { throw new MalformedCookieException("Invalid Port " + "attribute: " + e.Message); } return(ports); }
// test.cleanup(); // clean up after all to restore the system state /// <exception cref="System.IO.IOException"/> private void AnalyzeResult(long execTime, string resFileName, bool viewStats) { Path reduceFile = new Path(ReadDir, "part-00000"); DataInputStream @in; @in = new DataInputStream(fs.Open(reduceFile)); BufferedReader lines; lines = new BufferedReader(new InputStreamReader(@in)); long blocks = 0; long size = 0; long time = 0; float rate = 0; StringTokenizer badBlocks = null; long nrBadBlocks = 0; string line; while ((line = lines.ReadLine()) != null) { StringTokenizer tokens = new StringTokenizer(line, " \t\n\r\f%"); string attr = tokens.NextToken(); if (attr.EndsWith("blocks")) { blocks = long.Parse(tokens.NextToken()); } else { if (attr.EndsWith("size")) { size = long.Parse(tokens.NextToken()); } else { if (attr.EndsWith("time")) { time = long.Parse(tokens.NextToken()); } else { if (attr.EndsWith("rate")) { rate = float.ParseFloat(tokens.NextToken()); } else { if (attr.EndsWith("badBlocks")) { badBlocks = new StringTokenizer(tokens.NextToken(), ";"); nrBadBlocks = badBlocks.CountTokens(); } } } } } } Vector <string> resultLines = new Vector <string>(); resultLines.AddItem("----- DistributedFSCheck ----- : "); resultLines.AddItem(" Date & time: " + Sharpen.Extensions.CreateDate (Runtime.CurrentTimeMillis())); resultLines.AddItem(" Total number of blocks: " + blocks); resultLines.AddItem(" Total number of files: " + nrFiles); resultLines.AddItem("Number of corrupted blocks: " + nrBadBlocks); int nrBadFilesPos = resultLines.Count; TreeSet <string> badFiles = new TreeSet <string>(); long nrBadFiles = 0; if (nrBadBlocks > 0) { resultLines.AddItem(string.Empty); resultLines.AddItem("----- Corrupted Blocks (file@offset) ----- : "); while (badBlocks.HasMoreTokens()) { string curBlock = badBlocks.NextToken(); resultLines.AddItem(curBlock); badFiles.AddItem(Sharpen.Runtime.Substring(curBlock, 0, curBlock.IndexOf('@'))); } nrBadFiles = badFiles.Count; } resultLines.InsertElementAt(" Number of corrupted files: " + nrBadFiles, nrBadFilesPos ); if (viewStats) { resultLines.AddItem(string.Empty); resultLines.AddItem("----- Performance ----- : "); resultLines.AddItem(" Total MBytes read: " + size / Mega); resultLines.AddItem(" Throughput mb/sec: " + (float)size * 1000.0 / (time * Mega)); resultLines.AddItem(" Average IO rate mb/sec: " + rate / 1000 / blocks); resultLines.AddItem(" Test exec time sec: " + (float)execTime / 1000); } TextWriter res = new TextWriter(new FileOutputStream(new FilePath(resFileName), true )); for (int i = 0; i < resultLines.Count; i++) { string cur = resultLines[i]; Log.Info(cur); res.WriteLine(cur); } }
/// <exception cref="Org.Apache.Commons.Cli.ParseException"/> private void ProcessOptions(CommandLine line, Options opts) { // --help -h and --version -V must be processed first. if (line.HasOption('h')) { HelpFormatter formatter = new HelpFormatter(); System.Console.Out.WriteLine("TFile and SeqFile benchmark."); System.Console.Out.WriteLine(); formatter.PrintHelp(100, "java ... TestTFileSeqFileComparison [options]", "\nSupported options:" , opts, string.Empty); return; } if (line.HasOption('c')) { compress = line.GetOptionValue('c'); } if (line.HasOption('d')) { dictSize = System.Convert.ToInt32(line.GetOptionValue('d')); } if (line.HasOption('s')) { fileSize = long.Parse(line.GetOptionValue('s')) * 1024 * 1024; } if (line.HasOption('f')) { format = line.GetOptionValue('f'); } if (line.HasOption('i')) { fsInputBufferSize = System.Convert.ToInt32(line.GetOptionValue('i')); } if (line.HasOption('o')) { fsOutputBufferSize = System.Convert.ToInt32(line.GetOptionValue('o')); } if (line.HasOption('k')) { keyLength = System.Convert.ToInt32(line.GetOptionValue('k')); } if (line.HasOption('v')) { valueLength = System.Convert.ToInt32(line.GetOptionValue('v')); } if (line.HasOption('b')) { minBlockSize = System.Convert.ToInt32(line.GetOptionValue('b')) * 1024; } if (line.HasOption('r')) { rootDir = line.GetOptionValue('r'); } if (line.HasOption('S')) { seed = long.Parse(line.GetOptionValue('S')); } if (line.HasOption('w')) { string min_max = line.GetOptionValue('w'); StringTokenizer st = new StringTokenizer(min_max, " \t,"); if (st.CountTokens() != 2) { throw new ParseException("Bad word length specification: " + min_max); } minWordLen = System.Convert.ToInt32(st.NextToken()); maxWordLen = System.Convert.ToInt32(st.NextToken()); } if (line.HasOption('x')) { string strOp = line.GetOptionValue('x'); if (strOp.Equals("r")) { op = OpRead; } else { if (strOp.Equals("w")) { op = OpCreate; } else { if (strOp.Equals("rw")) { op = OpCreate | OpRead; } else { throw new ParseException("Unknown action specifier: " + strOp); } } } } proceed = true; }
public static Cursor GetSystemCustomCursor(String name) { GraphicsEnvironment.CheckHeadless(); Cursor cursor = SystemCustomCursors[name]; if (cursor == null) { lock (SystemCustomCursors) { if (SystemCustomCursorProperties == null) { LoadSystemCustomCursorProperties(); } } String prefix = CursorDotPrefix + name; String key = prefix + DotFileSuffix; if (!SystemCustomCursorProperties.ContainsKey(key)) { if (Log.isLoggable(PlatformLogger.Level.FINER)) { Log.finer("Cursor.getSystemCustomCursor(" + name + ") returned null"); } return(null); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String fileName = systemCustomCursorProperties.getProperty(key); String fileName = SystemCustomCursorProperties.GetProperty(key); String localized = SystemCustomCursorProperties.GetProperty(prefix + DotNameSuffix); if (localized == null) { localized = name; } String hotspot = SystemCustomCursorProperties.GetProperty(prefix + DotHotspotSuffix); if (hotspot == null) { throw new AWTException("no hotspot property defined for cursor: " + name); } StringTokenizer st = new StringTokenizer(hotspot, ","); if (st.CountTokens() != 2) { throw new AWTException("failed to parse hotspot property for cursor: " + name); } int x = 0; int y = 0; try { x = Convert.ToInt32(st.NextToken()); y = Convert.ToInt32(st.NextToken()); } catch (NumberFormatException) { throw new AWTException("failed to parse hotspot property for cursor: " + name); } try { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int fx = x; int fx = x; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int fy = y; int fy = y; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String flocalized = localized; String flocalized = localized; cursor = AccessController.doPrivileged <Cursor>(new PrivilegedExceptionActionAnonymousInnerClassHelper(fileName, fx, fy, flocalized)); } catch (Exception e) { throw new AWTException("Exception: " + e.GetType() + " " + e.Message + " occurred while creating cursor " + name); } if (cursor == null) { if (Log.isLoggable(PlatformLogger.Level.FINER)) { Log.finer("Cursor.getSystemCustomCursor(" + name + ") returned null"); } } else { SystemCustomCursors[name] = cursor; } } return(cursor); }
} // parse public String ParseAndSaveLine(String line, int AD_Client_ID, int AD_Org_ID, int C_Element_ID, MTree tree) { log.Config(line); // Fields with ',' are enclosed in " StringBuilder newLine = new StringBuilder(); StringTokenizer st = new StringTokenizer(line, "\"", false); newLine.Append(st.NextToken()); // first part while (st.HasMoreElements()) { String s = st.NextToken(); // enclosed part newLine.Append(s.Replace(',', ' ')); // remove ',' with space if (st.HasMoreTokens()) { newLine.Append(st.NextToken()); // unenclosed } } // add space at the end - tokenizer does not count empty fields newLine.Append(" "); // Parse Line - replace ",," with ", ," - tokenizer does not count empty fields String pLine = Utility.Util.Replace(newLine.ToString(), ",,", ", ,"); pLine = Utility.Util.Replace(pLine, ",,", ", ,"); st = new StringTokenizer(pLine, ",", false); // All fields there ? if (st.CountTokens() == 1) { log.Log(Level.SEVERE, "Ignored: Require ',' as separator - " + pLine); return(""); } if (st.CountTokens() < 9) { log.Log(Level.SEVERE, "Ignored: FieldNumber wrong: " + st.CountTokens() + " - " + pLine); return(""); } // Fill variables String Value = null, Name = null, Description = null, AccountType = null, AccountSign = null, IsDocControlled = null, IsSummary = null, Default_Account = null; int accountParent = -1; // for (int i = 0; i < 9 && st.HasMoreTokens(); i++) { String s = st.NextToken().Trim(); // Ignore, if is it header line if (s.StartsWith("[") && s.EndsWith("]")) { return(""); } if (s == null) { s = ""; } // if (i == 0) // A - Value { Value = s; } else if (i == 1) // B - Name { Name = s; } else if (i == 2) // C - Description { Description = s; } else if (i == 3) // D - Type { AccountType = s.Length > 0 ? s[0].ToString() : "E"; } else if (i == 4) // E - Sign { AccountSign = s.Length > 0 ? s[0].ToString() : "N"; } else if (i == 5) // F - DocControlled { IsDocControlled = s.Length > 0 ? s[0].ToString() : "N"; } else if (i == 6) // G - IsSummary { IsSummary = s.Length > 0 ? s[0].ToString() : "N"; } else if (i == 7) // H - Default_Account { Default_Account = s; } else if (i == 8) { accountParent = Util.GetValueOfInt(s); } } // Ignore if Value & Name are empty (no error message) if ((Value == null || Value.Length == 0) && (Name == null || Name.Length == 0)) { return(""); } //////////////////// //Commented By Lakhwinder //// Default Account may be blank //if (Default_Account == null || Default_Account.Length == 0) // // Default_Account = String.valueOf(s_keyNo++); // return ""; //// No Summary Account //if (IsSummary == null || IsSummary.Length == 0) // IsSummary = "N"; //if (!IsSummary.Equals("N")) // return ""; //// Validation //if (AccountType == null || AccountType.Length == 0) // AccountType = "E"; //if (AccountSign == null || AccountSign.Length == 0) // AccountSign = "N"; //if (IsDocControlled == null || IsDocControlled.Length == 0) // IsDocControlled = "N"; ////////////////////// // log.config( "Value=" + Value + ", AcctType=" + AccountType // + ", Sign=" + AccountSign + ", Doc=" + docControlled // + ", Summary=" + summary + " - " + Name + " - " + Description); try { // Try to find - allows to use same natutal account for multiple default accounts MElementValue na = null; if (m_valueMap.ContainsKey(Value)) { na = (MElementValue)m_valueMap[Value]; } if (na == null) { // Create Account - save later na = new MElementValue(m_ctx, Value, Name, Description, AccountType, AccountSign, IsDocControlled.ToUpper().StartsWith("Y"), IsSummary.ToUpper().StartsWith("Y"), m_trx); int refElementID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT C_ElementValue_ID FROM C_ElementValue WHERE IsActive='Y' AND AD_Client_ID=" + na.GetAD_Client_ID() + " AND Value='" + accountParent + @"' AND C_Element_ID=" + C_Element_ID, null, m_trx)); na.SetRef_C_ElementValue_ID(refElementID); m_valueMap[Value] = na; na.SetAD_Client_ID(AD_Client_ID); na.SetAD_Org_ID(AD_Org_ID); na.SetC_Element_ID(C_Element_ID); na.SetVIS_DefaultAccount(Default_Account); if (!na.Save(m_trx)) { return("Acct Element Values NOT inserted"); //m_info.Append(Msg.Translate(m_lang, "C_ElementValue_ID")).Append(" # ").Append(m_nap.Count).Append("\n"); } VAdvantage.Model.MTreeNode mNode = VAdvantage.Model.MTreeNode.Get(tree, na.Get_ID()); if (mNode == null) { mNode = new VAdvantage.Model.MTreeNode(tree, na.Get_ID()); } ((VAdvantage.Model.PO)mNode).Set_Value("Parent_ID", refElementID); if (!mNode.Save(m_trx)) { return("Acct Element Values NOT inserted"); } } if (!(Default_Account == null || Default_Account.Length == 0)) { // Add to Cache s_base.Add(Default_Account.ToUpper(), na); } } catch (Exception e) { return(e.Message); } return(""); } //
/// <summary> /// Create Account Entry for Default Accounts only. /// </summary> /// <param name="line">line with info /// <para> /// Line format (9 fields) /// 1 A [Account Value] /// 2 B [Account Name] /// 3 C [Description] /// 4 D [Account Type] /// 5 E [Account Sign] /// 6 F [Document Controlled] /// 7 G [Summary Account] /// 8 H [Default_Account] /// 9 I [Parent Value] - ignored /// </para> /// </param> /// <returns>error message or "" if OK</returns> public String ParseLine(String line) { log.Config(line); // Fields with ',' are enclosed in " StringBuilder newLine = new StringBuilder(); StringTokenizer st = new StringTokenizer(line, "\"", false); newLine.Append(st.NextToken()); // first part while (st.HasMoreElements()) { String s = st.NextToken(); // enclosed part newLine.Append(s.Replace(',', ' ')); // remove ',' with space if (st.HasMoreTokens()) { newLine.Append(st.NextToken()); // unenclosed } } // add space at the end - tokenizer does not count empty fields newLine.Append(" "); // Parse Line - replace ",," with ", ," - tokenizer does not count empty fields String pLine = Utility.Util.Replace(newLine.ToString(), ",,", ", ,"); pLine = Utility.Util.Replace(pLine, ",,", ", ,"); st = new StringTokenizer(pLine, ",", false); // All fields there ? if (st.CountTokens() == 1) { log.Log(Level.SEVERE, "Ignored: Require ',' as separator - " + pLine); return(""); } if (st.CountTokens() < 9) { log.Log(Level.SEVERE, "Ignored: FieldNumber wrong: " + st.CountTokens() + " - " + pLine); return(""); } // Fill variables String Value = null, Name = null, Description = null, AccountType = null, AccountSign = null, IsDocControlled = null, IsSummary = null, Default_Account = null; // for (int i = 0; i < 8 && st.HasMoreTokens(); i++) { String s = st.NextToken().Trim(); // Ignore, if is it header line if (s.StartsWith("[") && s.EndsWith("]")) { return(""); } if (s == null) { s = ""; } // if (i == 0) // A - Value { Value = s; } else if (i == 1) // B - Name { Name = s; } else if (i == 2) // C - Description { Description = s; } else if (i == 3) // D - Type { AccountType = s.Length > 0 ? s[0].ToString() : "E"; } else if (i == 4) // E - Sign { AccountSign = s.Length > 0 ? s[0].ToString() : "N"; } else if (i == 5) // F - DocControlled { IsDocControlled = s.Length > 0 ? s[0].ToString() : "N"; } else if (i == 6) // G - IsSummary { IsSummary = s.Length > 0 ? s[0].ToString() : "N"; } else if (i == 7) // H - Default_Account { Default_Account = s; } } // Ignore if Value & Name are empty (no error message) if ((Value == null || Value.Length == 0) && (Name == null || Name.Length == 0)) { return(""); } // Default Account may be blank if (Default_Account == null || Default_Account.Length == 0) { // Default_Account = String.valueOf(s_keyNo++); return(""); } // No Summary Account if (IsSummary == null || IsSummary.Length == 0) { IsSummary = "N"; } if (!IsSummary.Equals("N")) { return(""); } // Validation if (AccountType == null || AccountType.Length == 0) { AccountType = "E"; } if (AccountSign == null || AccountSign.Length == 0) { AccountSign = "N"; } if (IsDocControlled == null || IsDocControlled.Length == 0) { IsDocControlled = "N"; } // log.config( "Value=" + Value + ", AcctType=" + AccountType // + ", Sign=" + AccountSign + ", Doc=" + docControlled // + ", Summary=" + summary + " - " + Name + " - " + Description); try { // Try to find - allows to use same natutal account for multiple default accounts MElementValue na = null; if (m_valueMap.ContainsKey(Value)) { na = (MElementValue)m_valueMap[Value]; } if (na == null) { // Create Account - save later na = new MElementValue(m_ctx, Value, Name, Description, AccountType, AccountSign, IsDocControlled.ToUpper().StartsWith("Y"), IsSummary.ToUpper().StartsWith("Y"), m_trx); m_valueMap[Value] = na; } // Add to Cache s_base.Add(Default_Account.ToUpper(), na); } catch (Exception e) { return(e.Message); } return(""); } // parseLine
private bool EvaluateNumericLogic(decimal valueObj, string value1S, string op) { StringTokenizer st = new StringTokenizer(value1S.Trim(), "&|", true); try { int it = st.CountTokens(); decimal value1SDec = 0; if (it > 1) { if (((it / 2) - ((it + 1) / 2)) == 0) // only uneven arguments { //log.severe("Logic does not comply with format " // + "'<expression> [<logic> <expression>]' => " + logic); return(false); } StringBuilder logic = new StringBuilder(); string _operator = null; int res = -1; while (st.HasMoreTokens()) { //logic.Append(valueObj); res = valueObj.CompareTo(Convert.ToDecimal(st.NextToken().Trim())); if (OPERATION_Eq.Equals(op)) { logic.Append(res == 0 ? "true" : "false"); } else if (OPERATION_Gt.Equals(op)) { logic.Append(res == 1 ? "true" : "false"); } else if (OPERATION_GtEq.Equals(op)) { logic.Append(res >= 0 ? "true" : "false"); } else if (OPERATION_Le.Equals(op)) { logic.Append(res < 0 ? "true" : "false"); } else if (OPERATION_LeEq.Equals(op)) { logic.Append(res <= 0 ? "true" : "false"); } else if (OPERATION_Like.Equals(op)) { logic.Append(res != 0 ? "true" : "false"); } else if (OPERATION_NotEq.Equals(op)) { logic.Append(res == 0 ? "true" : "false"); } //logic.Append(st.NextToken().Trim()); if (st.HasMoreTokens()) { logic.Append(st.NextToken().Trim()); } } st = new StringTokenizer(logic.ToString().Trim(), "&|", true); bool retval = false; retval = st.NextToken().Trim().Equals("false") ? false : true; while (st.HasMoreTokens()) { _operator = st.NextToken().Trim(); if (_operator == "&") { retval = retval && (st.NextToken().Trim().Equals("false") ? false : true); } else if (_operator == "|") { retval = retval || (st.NextToken().Trim().Equals("false") ? false : true); } } return(retval); } else { value1SDec = Util.GetValueOfDecimal(value1S); if (OPERATION_Eq.Equals(op)) { return(valueObj.CompareTo(value1SDec) == 0); } else if (OPERATION_Gt.Equals(op)) { return(valueObj.CompareTo(value1SDec) > 0); } else if (OPERATION_GtEq.Equals(op)) { return(valueObj.CompareTo(value1SDec) >= 0); } else if (OPERATION_Le.Equals(op)) { return(valueObj.CompareTo(value1SDec) < 0); } else if (OPERATION_LeEq.Equals(op)) { return(valueObj.CompareTo(value1SDec) <= 0); } else if (OPERATION_NotEq.Equals(op)) { return(valueObj.CompareTo(value1SDec) != 0); } else if (OPERATION_Like.Equals(op)) { return(valueObj.CompareTo(value1SDec) == 0); } } //return Evaluator.EvaluateLogic(null, logic.ToString()); } catch { return(false); } return(false); }
/// <summary> /// Parses a string and returns an <code>AWTKeyStroke</code>. /// The string must have the following syntax: /// <pre> /// <modifiers>* (<typedID> | <pressedReleasedID>) /// /// modifiers := shift | control | ctrl | meta | alt | altGraph /// typedID := typed <typedKey> /// typedKey := string of length 1 giving Unicode character. /// pressedReleasedID := (pressed | released) key /// key := KeyEvent key code name, i.e. the name following "VK_". /// </pre> /// If typed, pressed or released is not specified, pressed is assumed. Here /// are some examples: /// <pre> /// "INSERT" => getAWTKeyStroke(KeyEvent.VK_INSERT, 0); /// "control DELETE" => getAWTKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_MASK); /// "alt shift X" => getAWTKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK); /// "alt shift released X" => getAWTKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK, true); /// "typed a" => getAWTKeyStroke('a'); /// </pre> /// </summary> /// <param name="s"> a String formatted as described above </param> /// <returns> an <code>AWTKeyStroke</code> object for that String </returns> /// <exception cref="IllegalArgumentException"> if <code>s</code> is <code>null</code>, /// or is formatted incorrectly </exception> public static AWTKeyStroke GetAWTKeyStroke(String s) { if (s == null) { throw new IllegalArgumentException("String cannot be null"); } const String errmsg = "String formatted incorrectly"; StringTokenizer st = new StringTokenizer(s, " "); int mask = 0; bool released = false; bool typed = false; bool pressed = false; lock (typeof(AWTKeyStroke)) { if (ModifierKeywords == null) { IDictionary <String, Integer> uninitializedMap = new Dictionary <String, Integer>(8, 1.0f); uninitializedMap["shift"] = Convert.ToInt32(InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK); uninitializedMap["control"] = Convert.ToInt32(InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK); uninitializedMap["ctrl"] = Convert.ToInt32(InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK); uninitializedMap["meta"] = Convert.ToInt32(InputEvent.META_DOWN_MASK | InputEvent.META_MASK); uninitializedMap["alt"] = Convert.ToInt32(InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK); uninitializedMap["altGraph"] = Convert.ToInt32(InputEvent.ALT_GRAPH_DOWN_MASK | InputEvent.ALT_GRAPH_MASK); uninitializedMap["button1"] = Convert.ToInt32(InputEvent.BUTTON1_DOWN_MASK); uninitializedMap["button2"] = Convert.ToInt32(InputEvent.BUTTON2_DOWN_MASK); uninitializedMap["button3"] = Convert.ToInt32(InputEvent.BUTTON3_DOWN_MASK); ModifierKeywords = Collections.SynchronizedMap(uninitializedMap); } } int count = st.CountTokens(); for (int i = 1; i <= count; i++) { String token = st.NextToken(); if (typed) { if (token.Length() != 1 || i != count) { throw new IllegalArgumentException(errmsg); } return(GetCachedStroke(token.CharAt(0), KeyEvent.VK_UNDEFINED, mask, false)); } if (pressed || released || i == count) { if (i != count) { throw new IllegalArgumentException(errmsg); } String keyCodeName = "VK_" + token; int keyCode = GetVKValue(keyCodeName); return(GetCachedStroke(KeyEvent.CHAR_UNDEFINED, keyCode, mask, released)); } if (token.Equals("released")) { released = true; continue; } if (token.Equals("pressed")) { pressed = true; continue; } if (token.Equals("typed")) { typed = true; continue; } Integer tokenMask = (Integer)ModifierKeywords[token]; if (tokenMask != null) { mask |= tokenMask.IntValue(); } else { throw new IllegalArgumentException(errmsg); } } throw new IllegalArgumentException(errmsg); }