KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > util > Env


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.util;
15
16 import java.awt.*;
17 import javax.swing.*;
18 import java.net.*;
19 import java.util.*;
20 import java.sql.*;
21
22 import org.compiere.Compiere;
23 import org.compiere.model.*;
24 import org.compiere.db.CConnection;
25
26
27 /**
28  * System Environment and static variables
29  *
30  * @author Jorg Janke
31  * @version $Id: Env.java,v 1.23 2003/11/06 07:09:09 jjanke Exp $
32  */

33 public final class Env
34 {
35     /** Logging */
36     private static Logger s_log = Logger.getCLogger(Env.class);
37
38     /**
39      * Test Init - Set Environment for tests
40      *
41      * @param traceLevel trace level
42      * @param isClient client session
43      * @return Context
44      */

45     public static Properties initTest (int traceLevel, boolean isClient)
46     {
47     // logger.entering("Env", "initTest");
48
org.compiere.Compiere.startupClient();
49         Log.setTraceLevel(traceLevel);
50         // Test Context
51
Properties ctx = Env.getCtx();
52         KeyNamePair[] roles = DB.login(ctx, CConnection.get(),
53             "System", "System", true);
54         // load role
55
if (roles != null && roles.length > 0)
56         {
57             KeyNamePair[] clients = DB.loadClients (ctx, roles[0]);
58             // load client
59
if (clients != null && clients.length > 0)
60             {
61                 KeyNamePair[] whs = DB.loadWarehouses(ctx, clients[0]);
62                 //
63
KeyNamePair[] orgs = DB.loadOrgs(ctx, clients[0]);
64                 // load org
65
if (orgs != null && orgs.length > 0)
66                 {
67                     DB.loadPreferences(ctx, orgs[0], null, null, null);
68                 }
69             }
70         }
71         //
72
Env.setContext(ctx, "#Date", "2000-01-01");
73     // logger.exiting("Env", "initTest");
74
return ctx;
75     } // testInit
76

77     /**
78      * Java Version Test
79      * @return true if Java Version is OK
80      */

81     public static boolean isJavaOK()
82     {
83         // Java System version check
84
String JavaDoc jVersion = System.getProperty("java.version");
85         if (jVersion.startsWith("1.4.1") || jVersion.startsWith("1.4.2")) // this release
86
return true;
87         // Warning
88
boolean ok = false;
89         if (jVersion.startsWith("1.4")) // later/earlier release
90
ok = true;
91
92         // Error Message
93
StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
94         msg.append(System.getProperty("java.vm.name")).append(" - ").append(jVersion);
95         if (ok)
96             msg.append("(untested)");
97         msg.append(" <> 1.4.1/2");
98         //
99
JOptionPane.showMessageDialog(null, msg.toString(),
100             org.compiere.Compiere.getName() + " - Java Version Check",
101             ok ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE);
102         return ok;
103     } // isJavaOK
104

105     /**
106      * Exit System
107      * @param status System exit status (usually 0 for no error)
108      */

109     public static void exitEnv (int status)
110     {
111         reset(true);
112         s_log.info("exit");
113         Logger.shutdownAll();
114         if (Ini.isClient())
115             System.exit (status);
116     } // close
117

118     /**
119      * Reset Cache
120      * @param all everything otherwise login data remains
121      */

122     public static void reset (boolean all)
123     {
124         s_log.info("reset - all=" + all);
125
126         // Dismantle windows
127
/**
128         for (int i = 0; i < s_windows.size(); i++)
129         {
130             Container win = (Container)s_windows.get(i);
131             if (win.getClass().getName().endsWith("AMenu")) // Null pointer
132                 ;
133             else if (win instanceof Window)
134                 ((Window)win).dispose();
135             else
136                 win.removeAll();
137         }
138         **/

139         s_windows.clear();
140
141         // Context
142
if (all)
143             s_ctx.clear();
144         else
145         {
146             Object JavaDoc[] keys = s_ctx.keySet().toArray();
147             for (int i = 0; i < keys.length; i++)
148             {
149                 String JavaDoc tag = keys[i].toString();
150                 if (Character.isDigit(tag.charAt(0)))
151                     s_ctx.remove(keys[i]);
152             }
153         }
154
155         // Cache
156
CacheMgt.get().reset();
157         DB.closeTarget();
158         // Reset Role Access
159
MRole defaultRole = MRole.getDefault(s_ctx, false);
160         if (defaultRole != null)
161             defaultRole.loadAccess(true); // Reload
162
} // resetAll
163

164
165     /*************************************************************************/
166
167     /**
168      * Application Context
169      */

170     private static Properties s_ctx = new Properties();
171     /** WindowNo for Find */
172     public static final int WINDOW_FIND = 1110;
173     /** WinowNo for MLookup */
174     public static final int WINDOW_MLOOKUP = 1111;
175     /** WindowNo for PrintCustomize */
176     public static final int WINDOW_CUSTOMIZE = 1112;
177     /** WindowNo for PrintCustomize */
178     public static final int WINDOW_INFO = 1113;
179
180     /** Tab for Info */
181     public static final int TAB_INFO = 1113;
182
183     /**
184      * Get Context
185      * @return Properties
186      */

187     public static final Properties getCtx()
188     {
189         return s_ctx;
190     } // getCtx
191

192     /**
193      * Set Context
194      * @param ctx context
195      */

196     public static void setCtx (Properties ctx)
197     {
198         if (ctx == null)
199             throw new IllegalArgumentException JavaDoc ("Env.setCtx - require Context");
200         s_ctx.clear();
201         s_ctx = ctx;
202     } // setCtx
203

204     /**
205      * Set Global Context to Value
206      * @param ctx context
207      * @param context context key
208      * @param value context value
209      */

210     public static void setContext (Properties ctx, String JavaDoc context, String JavaDoc value)
211     {
212         if (ctx == null || context == null)
213             return;
214         Log.trace(7, "Context " + context + "==" + value);
215         //
216
if (value == null || value.length() == 0)
217             ctx.remove(context);
218         else
219             ctx.setProperty(context, value);
220     } // setContext
221

222     /**
223      * Set Global Context to (int) Value
224      * @param ctx context
225      * @param context context key
226      * @param value context value
227      */

228     public static void setContext (Properties ctx, String JavaDoc context, int value)
229     {
230         if (ctx == null || context == null)
231             return;
232         Log.trace(7, "Context " + context + "==" + value);
233         //
234
ctx.setProperty(context, String.valueOf(value));
235     } // setContext
236

237     /**
238      * Set Global Context to Y/N Value
239      * @param ctx context
240      * @param context context key
241      * @param value context value
242      */

243     public static void setContext (Properties ctx, String JavaDoc context, boolean value)
244     {
245         setContext (ctx, context, value ? "Y" : "N");
246     } // setContext
247

248     /**
249      * Set Context for Window to Value
250      * @param ctx context
251      * @param WindowNo window no
252      * @param context context key
253      * @param value context value
254      */

255     public static void setContext (Properties ctx, int WindowNo, String JavaDoc context, String JavaDoc value)
256     {
257         if (ctx == null || context == null)
258             return;
259         if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP)
260             Log.trace(8, "Context("+WindowNo+") " + context + "==" + value);
261         //
262
if (value == null || value.equals(""))
263             ctx.remove(WindowNo+"|"+context);
264         else
265             ctx.setProperty(WindowNo+"|"+context, value);
266     } // setContext
267

268     /**
269      * Set Context for Window to int Value
270      * @param ctx context
271      * @param WindowNo window no
272      * @param context context key
273      * @param value context value
274      */

275     public static void setContext (Properties ctx, int WindowNo, String JavaDoc context, int value)
276     {
277         if (ctx == null || context == null)
278             return;
279         if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP)
280             Log.trace(8, "Context("+WindowNo+") " + context + "==" + value);
281         //
282
ctx.setProperty(WindowNo+"|"+context, String.valueOf(value));
283     } // setContext
284

285     /**
286      * Set Context for Window to Y/N Value
287      * @param ctx context
288      * @param WindowNo window no
289      * @param context context key
290      * @param value context value
291      */

292     public static void setContext (Properties ctx, int WindowNo, String JavaDoc context, boolean value)
293     {
294         setContext (ctx, WindowNo, context, value ? "Y" : "N");
295     } // setContext
296

297     /**
298      * Set Context for Window & Tab to Value
299      * @param ctx context
300      * @param WindowNo window no
301      * @param context context key
302      * @param value context value
303      * @param TabNo tab no
304      */

305     public static void setContext (Properties ctx, int WindowNo, int TabNo, String JavaDoc context, String JavaDoc value)
306     {
307         if (ctx == null || context == null)
308             return;
309         if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP)
310             Log.trace(9, "Context("+WindowNo+","+TabNo+") " + context + "==" + value);
311         //
312
if (value == null || value.equals(""))
313             ctx.remove(WindowNo+"|"+TabNo+"|"+context);
314         else
315             ctx.setProperty(WindowNo+"|"+TabNo+"|"+context, value);
316     } // setContext
317

318     /**
319      * Set AutoCommit
320      * @param ctx context
321      * @param autoCommit auto commit (save)
322      */

323     public static void setAutoCommit (Properties ctx, boolean autoCommit)
324     {
325         if (ctx == null)
326             return;
327         ctx.setProperty("AutoCommit", autoCommit ? "Y" : "N");
328     } // setAutoCommit
329

330     /**
331      * Set AutoCommit for Window
332      * @param ctx context
333      * @param WindowNo window no
334      * @param autoCommit auto commit (save)
335      */

336     public static void setAutoCommit (Properties ctx, int WindowNo, boolean autoCommit)
337     {
338         if (ctx == null)
339             return;
340         ctx.setProperty(WindowNo+"|AutoCommit", autoCommit ? "Y" : "N");
341     } // setAutoCommit
342

343     /**
344      * Get global Value of Context
345      * @param ctx context
346      * @param context context key
347      * @return value or ""
348      */

349     public static String JavaDoc getContext (Properties ctx, String JavaDoc context)
350     {
351         if (ctx == null || context == null)
352             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
353         return ctx.getProperty(context, "");
354     } // getContext
355

356     /**
357      * Get Value of Context for Window.
358      * if not found global context if available and enabled
359      * @param ctx context
360      * @param WindowNo window
361      * @param context context key
362      * @param onlyWindow if true, no defaults are used unless explicitly asked for
363      * @return value or ""
364      */

365     public static String JavaDoc getContext (Properties ctx, int WindowNo, String JavaDoc context, boolean onlyWindow)
366     {
367         if (ctx == null)
368             throw new IllegalArgumentException JavaDoc ("Env.getContext - No Ctx");
369         if (context == null)
370             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
371         String JavaDoc s = ctx.getProperty(WindowNo+"|"+context);
372         if (s == null)
373         {
374             // Explicit Base Values
375
if (context.startsWith("#") || context.startsWith("$"))
376                 return getContext(ctx, context);
377             if (onlyWindow) // no Default values
378
return "";
379             return getContext(ctx, "#" + context);
380         }
381         return s;
382     } // getContext
383

384     /**
385      * Get Value of Context for Window.
386      * if not found global context if available
387      * @param ctx context
388      * @param WindowNo window
389      * @param context context key
390      * @return value or ""
391      */

392     public static String JavaDoc getContext (Properties ctx, int WindowNo, String JavaDoc context)
393     {
394         return getContext(ctx, WindowNo, context, false);
395     } // getContext
396

397     /**
398      * Get Value of Context for Window & Tab,
399      * if not found global context if available
400      * @param ctx context
401      * @param WindowNo window no
402      * @param TabNo tab no
403      * @param context context key
404      * @return value or ""
405      */

406     public static String JavaDoc getContext (Properties ctx, int WindowNo, int TabNo, String JavaDoc context)
407     {
408         if (ctx == null || context == null)
409             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
410         String JavaDoc s = ctx.getProperty(WindowNo+"|"+TabNo+"|"+context);
411         if (s == null)
412             return getContext(ctx, WindowNo, context, false);
413         return s;
414     } // getContext
415

416     /**
417      * Get Context and convert it to an integer (0 if error)
418      * @param ctx context
419      * @param context context key
420      * @return value
421      */

422     public static int getContextAsInt(Properties ctx, String JavaDoc context)
423     {
424         if (ctx == null || context == null)
425             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
426         String JavaDoc s = getContext(ctx, context);
427         if (s.length() == 0)
428             s = getContext(ctx, 0, context, false); // search 0 and defaults
429
if (s.length() == 0)
430             return 0;
431         //
432
try
433         {
434             return Integer.parseInt(s);
435         }
436         catch (NumberFormatException JavaDoc e)
437         {
438             s_log.error("getContextAsInt (" + context + ") = " + s, e);
439         }
440         return 0;
441     } // getContextAsInt
442

443     /**
444      * Get Context and convert it to an integer (0 if error)
445      * @param ctx context
446      * @param WindowNo window no
447      * @param context context key
448      * @return value or 0
449      */

450     public static int getContextAsInt(Properties ctx, int WindowNo, String JavaDoc context)
451     {
452         String JavaDoc s = getContext(ctx, WindowNo, context, false);
453         if (s.length() == 0)
454             return 0;
455         //
456
try
457         {
458             return Integer.parseInt(s);
459         }
460         catch (NumberFormatException JavaDoc e)
461         {
462             s_log.error("getContextAsInt (" + context + ") = " + s, e);
463         }
464         return 0;
465     } // getContextAsInt
466

467     /**
468      * Get Context and convert it to an integer (0 if error)
469      * @param ctx context
470      * @param WindowNo window no
471      * @parem TabNo tab no
472      * @param context context key
473      * @return value or 0
474      */

475     public static int getContextAsInt (Properties ctx, int WindowNo, int TabNo, String JavaDoc context)
476     {
477         String JavaDoc s = getContext(ctx, WindowNo, TabNo, context);
478         if (s.length() == 0)
479             return 0;
480         //
481
try
482         {
483             return Integer.parseInt(s);
484         }
485         catch (NumberFormatException JavaDoc e)
486         {
487             s_log.error("getContextAsInt (" + context + ") = " + s, e);
488         }
489         return 0;
490     } // getContextAsInt
491

492     /**
493      * Is AutoCommit
494      * @param ctx context
495      * @return true if auto commit
496      */

497     public static boolean isAutoCommit (Properties ctx)
498     {
499         if (ctx == null)
500             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
501         String JavaDoc s = getContext(ctx, "AutoCommit");
502         if (s != null && s.equals("Y"))
503             return true;
504         return false;
505     } // isAutoCommit
506

507     /**
508      * Is Window AutoCommit (if not set use default)
509      * @param ctx context
510      * @param WindowNo window no
511      * @return true if auto commit
512      */

513     public static boolean isAutoCommit (Properties ctx, int WindowNo)
514     {
515         if (ctx == null)
516             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
517         String JavaDoc s = getContext(ctx, WindowNo, "AutoCommit", false);
518         if (s != null)
519         {
520             if (s.equals("Y"))
521                 return true;
522             else
523                 return false;
524         }
525         return isAutoCommit(ctx);
526     } // isAutoCommit
527

528     /**
529      * Get Context and convert it to a Timestamp
530      * if error return today's date
531      * @param ctx context
532      * @param context context key
533      * @return Timestamp
534      */

535     public static Timestamp getContextAsDate(Properties ctx, String JavaDoc context)
536     {
537         return getContextAsDate(ctx, 0, context);
538     } // getContextAsDate
539

540     /**
541      * Get Context and convert it to a Timestamp
542      * if error return today's date
543      * @param ctx context
544      * @param WindowNo window no
545      * @param context context key
546      * @return Timestamp
547      */

548     public static Timestamp getContextAsDate(Properties ctx, int WindowNo, String JavaDoc context)
549     {
550         if (ctx == null || context == null)
551             throw new IllegalArgumentException JavaDoc ("Env.getContext - require Context");
552         String JavaDoc s = getContext(ctx, WindowNo, context, false);
553         // JDBC Format YYYY-MM-DD example 2000-09-11 00:00:00.0
554
if (s == null || s.equals(""))
555         {
556             s_log.error("getContextAsDate - No value for: " + context);
557             return new Timestamp(System.currentTimeMillis());
558         }
559
560         // timestamp requires time
561
if (s.trim().length() == 10)
562             s = s.trim() + " 00:00:00.0";
563
564         return Timestamp.valueOf(s);
565     } // getContextAsDate
566

567     /**
568      * Get Login AD_Client_ID
569      * @param ctx context
570      * @return login AD_Client_ID
571      */

572     public static int getAD_Client_ID (Properties ctx)
573     {
574         return Env.getContextAsInt(ctx, "#AD_Client_ID");
575     } // getAD_Client_ID
576

577     /**
578      * Get Login AD_Org_ID
579      * @param ctx context
580      * @return login AD_Org_ID
581      */

582     public static int getAD_Org_ID (Properties ctx)
583     {
584         return Env.getContextAsInt(ctx, "#AD_Org_ID");
585     } // getAD_Client_ID
586

587     /*************************************************************************/
588
589     /**
590      * Get Preference.
591      * <pre>
592      * 0) Current Setting
593      * 1) Window Preference
594      * 2) Global Preference
595      * 3) Login settings
596      * 4) Accounting settings
597      * </pre>
598      * @param ctx context
599      * @param AD_Window_ID window no
600      * @param context Entity to search
601      * @param system System level preferences (vs. user defined)
602      * @return preference value
603      */

604     public static String JavaDoc getPreference (Properties ctx, int AD_Window_ID, String JavaDoc context, boolean system)
605     {
606         if (ctx == null || context == null)
607             throw new IllegalArgumentException JavaDoc ("Env.getPreference - require Context");
608         String JavaDoc retValue = null;
609         //
610
if (!system) // User Preferences
611
{
612             retValue = ctx.getProperty("P"+AD_Window_ID+"|"+context);// Window Pref
613
if (retValue == null)
614                 retValue = ctx.getProperty("P|"+context); // Global Pref
615
}
616         else // System Preferences
617
{
618             retValue = ctx.getProperty("#"+context); // Login setting
619
if (retValue == null)
620                 retValue = ctx.getProperty("$"+context); // Accounting setting
621
}
622         //
623
return (retValue == null ? "" : retValue);
624     } // getPreference
625

626     /****************************************************************************
627      * Language issues
628      */

629
630     /** Context Language identifier */
631     static public final String JavaDoc LANG = "#AD_Language";
632
633     /**
634      * Check Base Language
635      * @param ctx context
636      * @param TableName table to be translated
637      * @return true if base language and table not translated
638      */

639     public static boolean isBaseLanguage (Properties ctx, String JavaDoc TableName)
640     {
641         if (TableName.startsWith("AD") || TableName.equals("C_UOM"))
642             Language.isBaseLanguage (getAD_Language(ctx));
643         else // No AD Table
644
if (!isMultiLingualDocument(ctx))
645                 return true; // access base table
646
return Language.isBaseLanguage (getAD_Language(ctx));
647     } // isBaseLanguage
648

649     /**
650      * Check Base Language
651      * @param AD_Language language
652      * @param TableName table to be translated
653      * @return true if base language and table not translated
654      */

655     public static boolean isBaseLanguage (String JavaDoc AD_Language, String JavaDoc TableName)
656     {
657         if (TableName.startsWith("AD") || TableName.equals("C_UOM"))
658             Language.isBaseLanguage (AD_Language);
659         else // No AD Table
660
if (!isMultiLingualDocument(s_ctx)) // Base Context
661
return true; // access base table
662
return Language.isBaseLanguage (AD_Language);
663     } // isBaseLanguage
664

665     /**
666      * Check Base Language
667      * @param language language
668      * @param TableName table to be translated
669      * @return true if base language and table not translated
670      */

671     public static boolean isBaseLanguage (Language language, String JavaDoc TableName)
672     {
673         if (TableName.startsWith("AD") || TableName.equals("C_UOM"))
674             language.isBaseLanguage();
675         else // No AD Table
676
if (!isMultiLingualDocument(s_ctx)) // Base Context
677
return true; // access base table
678
return language.isBaseLanguage();
679     } // isBaseLanguage
680

681     /**
682      * Do we have Multi-Lingual Documents.
683      * Set in DB.loadOrgs
684      * @param ctx context
685      * @return true if multi lingual documents
686      */

687     public static boolean isMultiLingualDocument (Properties ctx)
688     {
689         return "Y".equals(Env.getContext(ctx, "#IsMultiLingualDocument"));
690     } // isMultiLingualDocument
691

692     /**
693      * Get AD_Language
694      * @param ctx context
695      * @return AD_Language eg. en_US
696      */

697     public static String JavaDoc getAD_Language (Properties ctx)
698     {
699         if (ctx != null)
700         {
701             String JavaDoc lang = getContext(ctx, LANG);
702             if (lang != null || lang.length() > 0)
703                 return lang;
704         }
705         return Language.getBaseAD_Language();
706     } // getAD_Language
707

708     /**
709      * Get AD_Language
710      * @param ctx context
711      * @return Language
712      */

713     public static Language getLanguage (Properties ctx)
714     {
715         if (ctx != null)
716         {
717             String JavaDoc lang = getContext(ctx, LANG);
718             if (lang != null || lang.length() > 0)
719                 return Language.getLanguage(lang);
720         }
721         return Language.getLanguage();
722     } // getLanguage
723

724     /**
725      * Verify Language.
726      * Check that language is supported by the system
727      * @param ctx might be updated with new AD_Language
728      * @param language language
729      */

730     public static void verifyLanguage (Properties ctx, Language language)
731     {
732         if (language.isBaseLanguage())
733             return;
734         boolean IsSystemLanguage = false;
735         String JavaDoc sql = "SELECT IsSystemLanguage FROM AD_Language WHERE AD_Language=?";
736         try
737         {
738             PreparedStatement pstmt = DB.prepareStatement(sql);
739             pstmt.setString(1, language.getAD_Language());
740             ResultSet rs = pstmt.executeQuery();
741             if (rs.next())
742                 IsSystemLanguage = "Y".equals(rs.getString(1));
743             rs.close();
744             pstmt.close();
745         }
746         catch (SQLException e)
747         {
748             s_log.error("verifyLanguage (1)", e);
749         }
750         // Everything OK
751
if (IsSystemLanguage && !"0".equals(Msg.getMsg(ctx, "0")))
752             return;
753         //
754
s_log.warn ("verifyLanguage - Not System Language=" + language);
755
756         // Looking for same language
757
sql = "SELECT AD_Language FROM AD_Language WHERE AD_Language LIKE ?"
758             + " AND (IsSystemLanguage='Y' OR IsBaseLanguage='Y')";
759         String JavaDoc newLanguage = null;
760         try
761         {
762             PreparedStatement pstmt = DB.prepareStatement(sql);
763             pstmt.setString(1, language.getAD_Language().substring(0,2) + "%"); // first two char = lang
764
ResultSet rs = pstmt.executeQuery();
765             if (rs.next())
766                 newLanguage = rs.getString(1);
767             rs.close();
768             pstmt.close();
769         }
770         catch (SQLException e)
771         {
772             s_log.error("verifyLanguage (2)", e);
773         }
774         // We found same language
775
if (newLanguage != null && !"0".equals(Msg.getMsg(newLanguage, "0")))
776         {
777             s_log.info("verifyLanguage - Found similar Language " + newLanguage);
778             language.setAD_Language(newLanguage);
779             Env.setContext(ctx, Env.LANG, newLanguage);
780             return;
781         }
782
783         // none found - use Database Base Language
784
s_log.info("verifyLanguage - Set to Base Language " + Language.getBaseAD_Language());
785         language.setAD_Language(Language.getBaseAD_Language());
786         Env.setContext(ctx, Env.LANG, Language.getBaseAD_Language());
787         // finally load messages
788
Msg.getMsg(ctx, "0");
789     } // verifyLanguage
790

791     /*************************************************************************/
792
793     /**
794      * Get Context as String array with format: key == value
795      * @param ctx context
796      * @return context string
797      */

798     public static String JavaDoc[] getEntireContext(Properties ctx)
799     {
800         if (ctx == null)
801             throw new IllegalArgumentException JavaDoc ("Env.getEntireContext - require Context");
802         Iterator keyIterator = ctx.keySet().iterator();
803         String JavaDoc[] sList = new String JavaDoc[ctx.size()];
804         int i = 0;
805         while (keyIterator.hasNext())
806         {
807             Object JavaDoc key = keyIterator.next();
808             sList[i++] = key.toString() + " == " + ctx.get(key).toString();
809         }
810
811         return sList;
812     } // getEntireContext
813

814     /**
815      * Get Header info (connection, org, user)
816      * @param ctx context
817      * @param WindowNo window
818      * @return Header String
819      */

820     public static String JavaDoc getHeader(Properties ctx, int WindowNo)
821     {
822         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
823         if (WindowNo > 0)
824             sb.append(getContext(ctx, WindowNo, "WindowName", false)).append(" ");
825         sb.append(getContext(ctx, "#AD_User_Name")).append("@")
826             .append(getContext(ctx, "#AD_Client_Name")).append(".")
827             .append(getContext(ctx, "#AD_Org_Name"))
828             .append(" [").append(CConnection.get().toString()).append("]");
829         return sb.toString();
830     } // getHeader
831

832     /**
833      * Clean up context for Window (i.e. delete it)
834      * @param ctx context
835      * @param WindowNo window
836      */

837     public static void clearWinContext(Properties ctx, int WindowNo)
838     {
839         if (ctx == null)
840             throw new IllegalArgumentException JavaDoc ("Env.clearWinContext - require Context");
841         //
842
Object JavaDoc[] keys = ctx.keySet().toArray();
843         for (int i = 0; i < keys.length; i++)
844         {
845             String JavaDoc tag = keys[i].toString();
846             if (tag.startsWith(WindowNo+"|"))
847                 ctx.remove(keys[i]);
848         }
849         // Clear Lookup Cache
850
MLookupCache.cacheReset(WindowNo);
851     // MLocator.cacheReset(WindowNo);
852
//
853
removeWindow(WindowNo);
854     } // clearWinContext
855

856     /**
857      * Clean up all context (i.e. delete it)
858      * @param ctx context
859      */

860     public static void clearContext(Properties ctx)
861     {
862         if (ctx == null)
863             throw new IllegalArgumentException JavaDoc ("Env.clearContext - require Context");
864         ctx.clear();
865     } // clearContext
866

867
868     /**
869      * Parse Context replaces global or Window context @tag@ with actual value.
870      *
871      * @param ctx context
872      * @param WindowNo Number of Window
873      * @param value Message to be parsed
874      * @param onlyWindow if true, no defaults are used
875      * @param ignoreUnparsable if true, unsuccessful @tag@ are ignored otherwise "" is returned
876      * @return parsed String or "" if not successful and ignoreUnparsable
877      */

878     public static String JavaDoc parseContext (Properties ctx, int WindowNo, String JavaDoc value,
879         boolean onlyWindow, boolean ignoreUnparsable)
880     {
881         if (value == null)
882             return "";
883
884         String JavaDoc token;
885         String JavaDoc inStr = new String JavaDoc(value);
886         StringBuffer JavaDoc outStr = new StringBuffer JavaDoc();
887
888         int i = inStr.indexOf("@");
889         while (i != -1)
890         {
891             outStr.append(inStr.substring(0, i)); // up to @
892
inStr = inStr.substring(i+1, inStr.length()); // from first @
893

894             int j = inStr.indexOf("@"); // next @
895
if (j < 0)
896             {
897                 s_log.error("parseContext - no second tag: " + inStr);
898                 return ""; // no second tag
899
}
900
901             token = inStr.substring(0, j);
902
903             String JavaDoc ctxInfo = getContext(ctx, WindowNo, token, onlyWindow); // get context
904
if (ctxInfo.length() == 0 && (token.startsWith("#") || token.startsWith("$")) )
905                 ctxInfo = getContext(ctx, token); // get global context
906
if (ctxInfo.length() == 0)
907             {
908                 Log.trace(Log.l5_DData, "Env.parseContext - no context (" + WindowNo + ") for: " + token);
909                 if (!ignoreUnparsable)
910                     return ""; // token not found
911
}
912             else
913                 outStr.append(ctxInfo); // replace context with Context
914

915             inStr = inStr.substring(j+1, inStr.length()); // from second @
916
i = inStr.indexOf("@");
917         }
918         outStr.append(inStr); // add the rest of the string
919

920         return outStr.toString();
921     } // parseContext
922

923     /**
924      * Parse Context replaces global or Window context @tag@ with actual value.
925      *
926      * @param ctx context
927      * @param WindowNo Number of Window
928      * @param value Message to be parsed
929      * @param onlyWindow if true, no defaults are used
930      * @return parsed String or "" if not successful
931      */

932     public static String JavaDoc parseContext (Properties ctx, int WindowNo, String JavaDoc value,
933         boolean onlyWindow)
934     {
935         return parseContext(ctx, WindowNo, value, onlyWindow, false);
936     } // parseContext
937

938     /*************************************************************************/
939
940     private static ArrayList s_windows = new ArrayList(20);
941
942     /**
943      * Add Container and return WindowNo.
944      * The container is a APanel, AWindow or JFrame/JDialog
945      * @param win window
946      * @return WindowNo used for context
947      */

948     public static int createWindowNo(Container win)
949     {
950         int retValue = s_windows.size();
951         s_windows.add(win);
952         return retValue;
953     } // createWindowNo
954

955     /**
956      * Search Window by comparing the Frames
957      * @param container container
958      * @return WindowNo of container or 0
959      */

960     public static int getWindowNo (Container container)
961     {
962         if (container == null)
963             return 0;
964         JFrame winFrame = getFrame(container);
965         if (winFrame == null)
966             return 0;
967
968         // loop through windows
969
for (int i = 0; i < s_windows.size(); i++)
970         {
971             Container cmp = (Container)s_windows.get(i);
972             if (cmp != null)
973             {
974                 JFrame cmpFrame = getFrame(cmp);
975                 if (winFrame.equals(cmpFrame))
976                     return i;
977             }
978         }
979         return 0;
980     } // getWindowNo
981

982     /**
983      * Return the JFrame pointer of WindowNo - or null
984      * @param WindowNo window
985      * @return JFrame of WindowNo
986      */

987     public static JFrame getWindow (int WindowNo)
988     {
989         JFrame retValue = null;
990         try
991         {
992             retValue = getFrame ((Container)s_windows.get(WindowNo));
993         }
994         catch (Exception JavaDoc e)
995         {
996             System.err.println("Env.getWindow - " + e);
997         }
998         return retValue;
999     } // getWindow
1000

1001    /**
1002     * Remove window from active list
1003     * @param WindowNo window
1004     */

1005    private static void removeWindow (int WindowNo)
1006    {
1007        if (WindowNo <= s_windows.size())
1008            s_windows.set(WindowNo, null);
1009    } // removeWindow
1010

1011    /**
1012     * Clean up context for Window (i.e. delete it)
1013     * @param WindowNo window
1014     */

1015    public static void clearWinContext(int WindowNo)
1016    {
1017        clearWinContext (s_ctx, WindowNo);
1018    } // clearWinContext
1019

1020    /**
1021     * Clean up all context (i.e. delete it)
1022     */

1023    public static void clearContext()
1024    {
1025        s_ctx.clear();
1026    } // clearContext
1027

1028
1029    /*************************************************************************/
1030
1031    /**
1032     * Get Frame of Window
1033     * @param container Container
1034     * @return JFrame of container or null
1035     */

1036    public static JFrame getFrame (Container container)
1037    {
1038        Container element = container;
1039        while (element != null)
1040        {
1041            if (element instanceof JFrame)
1042                return (JFrame)element;
1043            element = element.getParent();
1044        }
1045        return null;
1046    } // getFrame
1047

1048    /**
1049     * Get Graphics of container or its parent.
1050     * The element may not have a Graphic if not displayed yet,
1051     * but the parent might have.
1052     * @param container Container
1053     * @return Graphics of container or null
1054     */

1055    public static Graphics getGraphics (Container container)
1056    {
1057        Container element = container;
1058        while (element != null)
1059        {
1060            Graphics g = element.getGraphics();
1061            if (g != null)
1062                return g;
1063            element = element.getParent();
1064        }
1065        return null;
1066    } // getFrame
1067

1068    /**
1069     * Return JDialog or JFrame Parent
1070     * @param container Container
1071     * @return JDialog or JFrame of container
1072     */

1073    public static Window getParent (Container container)
1074    {
1075        Container element = container;
1076        while (element != null)
1077        {
1078            if (element instanceof JDialog || element instanceof JFrame)
1079                return (Window)element;
1080            element = element.getParent();
1081        }
1082        return null;
1083    } // getParent
1084

1085    /*************************************************************************/
1086
1087    /**
1088     * Get Image with File name
1089     *
1090     * @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif)
1091     * @return image
1092     */

1093    public static Image getImage (String JavaDoc fileNameInImageDir)
1094    {
1095        URL url = Compiere.class.getResource("images/" + fileNameInImageDir);
1096        if (url == null)
1097            return null;
1098        Toolkit tk = Toolkit.getDefaultToolkit();
1099        return tk.getImage(url);
1100    } // getImage
1101

1102    /**
1103     * Get ImageIcon
1104     *
1105     * @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif)
1106     * @return image
1107     */

1108    public static ImageIcon getImageIcon (String JavaDoc fileNameInImageDir)
1109    {
1110        URL url = Compiere.class.getResource("images/" + fileNameInImageDir);
1111        if (url == null)
1112            return null;
1113        return new ImageIcon(url);
1114    } // getImageIcon
1115

1116
1117    /**************************************************************************/
1118
1119    /**
1120     * Start Browser
1121     * @param url url
1122     */

1123    public static void startBrowser (String JavaDoc url)
1124    {
1125        Log.trace(Log.l1_User, "Env.startBrowser", url);
1126        // OS command
1127
String JavaDoc cmd = "explorer ";
1128        if (!System.getProperty("os.name").startsWith("Win"))
1129            cmd = "netscape ";
1130        //
1131
String JavaDoc execute = cmd + url;
1132        try
1133        {
1134            Runtime.getRuntime().exec(execute);
1135        }
1136        catch (Exception JavaDoc e)
1137        {
1138            System.err.println("Env.startBrowser - " + execute + " - " + e);
1139        }
1140    } // startBrowser
1141

1142    /**************************************************************************
1143     * Static Variables
1144     */

1145
1146    /**
1147     * Big Decimal Zero
1148     */

1149    static final public java.math.BigDecimal JavaDoc ZERO = new java.math.BigDecimal JavaDoc(0.0);
1150    static final public java.math.BigDecimal JavaDoc ONE = new java.math.BigDecimal JavaDoc(1.0);
1151
1152    /**
1153     * New Line
1154     */

1155    public static final String JavaDoc NL = System.getProperty("line.separator");
1156
1157
1158    /**
1159     * Static initializer
1160     */

1161    static
1162    {
1163        // Set English as default Language
1164
s_ctx.put(LANG, Language.getBaseAD_Language());
1165    } // static
1166

1167} // Env
1168
Popular Tags