PageRenderTime 30ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/core/src/org/pentaho/di/core/Const.java

https://github.com/dbogdanovich/pentaho-kettle
Java | 2980 lines | 1329 code | 377 blank | 1274 comment | 321 complexity | 93298c4ee5d9bd83b175a2ea3d6b9423 MD5 | raw file
  1. //CHECKSTYLE:FileLength:OFF
  2. /*! ******************************************************************************
  3. *
  4. * Pentaho Data Integration
  5. *
  6. * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
  7. *
  8. *******************************************************************************
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with
  12. * the License. You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. *
  22. ******************************************************************************/
  23. package org.pentaho.di.core;
  24. import java.awt.Font;
  25. import java.awt.GraphicsEnvironment;
  26. import java.io.BufferedReader;
  27. import java.io.IOException;
  28. import java.io.InputStreamReader;
  29. import java.io.PrintWriter;
  30. import java.io.StringWriter;
  31. import java.net.InetAddress;
  32. import java.net.NetworkInterface;
  33. import java.net.SocketException;
  34. import java.net.URL;
  35. import java.net.URLClassLoader;
  36. import java.text.DecimalFormat;
  37. import java.text.DecimalFormatSymbols;
  38. import java.text.NumberFormat;
  39. import java.text.ParseException;
  40. import java.text.ParsePosition;
  41. import java.text.SimpleDateFormat;
  42. import java.util.ArrayList;
  43. import java.util.Arrays;
  44. import java.util.Calendar;
  45. import java.util.Date;
  46. import java.util.Enumeration;
  47. import java.util.List;
  48. import java.util.Locale;
  49. import java.util.TimeZone;
  50. import java.util.regex.Matcher;
  51. import java.util.regex.Pattern;
  52. import org.apache.commons.lang.StringEscapeUtils;
  53. import org.apache.commons.lang.StringUtils;
  54. import org.pentaho.di.core.exception.KettleException;
  55. import org.pentaho.di.core.row.ValueMetaInterface;
  56. import org.pentaho.di.i18n.BaseMessages;
  57. import org.pentaho.di.laf.BasePropertyHandler;
  58. import org.pentaho.di.version.BuildVersion;
  59. /**
  60. * This class is used to define a number of default values for various settings throughout Kettle. It also contains a
  61. * number of static final methods to make your life easier.
  62. *
  63. * @author Matt
  64. * @since 07-05-2003
  65. *
  66. */
  67. public class Const {
  68. private static Class<?> PKG = Const.class; // for i18n purposes, needed by Translator2!!
  69. /**
  70. * Version number
  71. *
  72. * @deprecated Use {@link BuildVersion#getVersion()} instead
  73. */
  74. @Deprecated
  75. public static final String VERSION = BuildVersion.getInstance().getVersion();
  76. /**
  77. * Copyright year
  78. */
  79. public static final String COPYRIGHT_YEAR = "2013";
  80. /**
  81. * Release Type
  82. */
  83. public enum ReleaseType {
  84. RELEASE_CANDIDATE, MILESTONE, PREVIEW, GA
  85. }
  86. /**
  87. * Sleep time waiting when buffer is empty (the default)
  88. */
  89. public static final int TIMEOUT_GET_MILLIS = 50;
  90. /**
  91. * Sleep time waiting when buffer is full (the default)
  92. */
  93. public static final int TIMEOUT_PUT_MILLIS = 50;
  94. /**
  95. * print update every ... lines
  96. */
  97. public static final int ROWS_UPDATE = 50000;
  98. /**
  99. * Size of rowset: bigger = faster for large amounts of data
  100. */
  101. public static final int ROWS_IN_ROWSET = 10000;
  102. /**
  103. * Fetch size in rows when querying a database
  104. */
  105. public static final int FETCH_SIZE = 10000;
  106. /**
  107. * Sort size: how many rows do we sort in memory at once?
  108. */
  109. public static final int SORT_SIZE = 5000;
  110. /**
  111. * What's the file systems file separator on this operating system?
  112. */
  113. public static final String FILE_SEPARATOR = System.getProperty( "file.separator" );
  114. /**
  115. * What's the path separator on this operating system?
  116. */
  117. public static final String PATH_SEPARATOR = System.getProperty( "path.separator" );
  118. /**
  119. * CR: operating systems specific Carriage Return
  120. */
  121. public static final String CR = System.getProperty( "line.separator" );
  122. /**
  123. * DOSCR: MS-DOS specific Carriage Return
  124. */
  125. public static final String DOSCR = "\n\r";
  126. /**
  127. * An empty ("") String.
  128. */
  129. public static final String EMPTY_STRING = "";
  130. /**
  131. * The Java runtime version
  132. */
  133. public static final String JAVA_VERSION = System.getProperty( "java.vm.version" );
  134. /**
  135. * Path to the users home directory (keep this entry above references to getKettleDirectory())
  136. *
  137. * @deprecated Use {@link Const.getUserHomeDirectory()} instead.
  138. */
  139. @Deprecated
  140. public static final String USER_HOME_DIRECTORY = NVL( System.getProperty( "KETTLE_HOME" ), System
  141. .getProperty( "user.home" ) );
  142. /**
  143. * Path to the simple-jndi directory
  144. */
  145. public static String JNDI_DIRECTORY = NVL( System.getProperty( "KETTLE_JNDI_ROOT" ), System
  146. .getProperty( "org.osjava.sj.root" ) );
  147. /*
  148. * The images directory
  149. *
  150. * public static final String IMAGE_DIRECTORY = "/ui/images/";
  151. */
  152. public static final String PLUGIN_BASE_FOLDERS_PROP = "KETTLE_PLUGIN_BASE_FOLDERS";
  153. /**
  154. * the default comma separated list of base plugin folders.
  155. */
  156. public static final String DEFAULT_PLUGIN_BASE_FOLDERS = "plugins,"
  157. + ( Const.isEmpty( getDIHomeDirectory() ) ? "" : getDIHomeDirectory() + FILE_SEPARATOR + "plugins," )
  158. + getKettleDirectory() + FILE_SEPARATOR + "plugins";
  159. /**
  160. * Default minimum date range...
  161. */
  162. public static final Date MIN_DATE = new Date( -2208992400000L ); // 1900/01/01 00:00:00.000
  163. /**
  164. * Default maximum date range...
  165. */
  166. public static final Date MAX_DATE = new Date( 7258114799468L ); // 2199/12/31 23:59:59.999
  167. /**
  168. * The default minimum year in a dimension date range
  169. */
  170. public static final int MIN_YEAR = 1900;
  171. /**
  172. * The default maximum year in a dimension date range
  173. */
  174. public static final int MAX_YEAR = 2199;
  175. /**
  176. * Specifies the number of pixels to the right we have to go in dialog boxes.
  177. */
  178. public static final int RIGHT = 400;
  179. /**
  180. * Specifies the length (width) of fields in a number of pixels in dialog boxes.
  181. */
  182. public static final int LENGTH = 350;
  183. /**
  184. * The margin between the different dialog components & widgets
  185. */
  186. public static final int MARGIN = 4;
  187. /**
  188. * The default percentage of the width of screen where we consider the middle of a dialog.
  189. */
  190. public static final int MIDDLE_PCT = 35;
  191. /**
  192. * The default width of an arrow in the Graphical Views
  193. */
  194. public static final int ARROW_WIDTH = 1;
  195. /**
  196. * The horizontal and vertical margin of a dialog box.
  197. */
  198. public static final int FORM_MARGIN = 5;
  199. /**
  200. * The default shadow size on the graphical view.
  201. */
  202. public static final int SHADOW_SIZE = 4;
  203. /**
  204. * The size of relationship symbols
  205. */
  206. public static final int SYMBOLSIZE = 10;
  207. /**
  208. * Max nr. of files to remember
  209. */
  210. public static final int MAX_FILE_HIST = 9; // Having more than 9 files in the file history is not compatible with pre
  211. // 5.0 versions
  212. /**
  213. * The default locale for the kettle environment (system defined)
  214. */
  215. public static final Locale DEFAULT_LOCALE = Locale.getDefault(); // new Locale("nl", "BE");
  216. /**
  217. * The default decimal separator . or ,
  218. */
  219. public static final char DEFAULT_DECIMAL_SEPARATOR = ( new DecimalFormatSymbols( DEFAULT_LOCALE ) )
  220. .getDecimalSeparator();
  221. /**
  222. * The default grouping separator , or .
  223. */
  224. public static final char DEFAULT_GROUPING_SEPARATOR = ( new DecimalFormatSymbols( DEFAULT_LOCALE ) )
  225. .getGroupingSeparator();
  226. /**
  227. * The default currency symbol
  228. */
  229. public static final String DEFAULT_CURRENCY_SYMBOL = ( new DecimalFormatSymbols( DEFAULT_LOCALE ) )
  230. .getCurrencySymbol();
  231. /**
  232. * The default number format
  233. */
  234. public static final String DEFAULT_NUMBER_FORMAT = ( (DecimalFormat) ( NumberFormat.getInstance() ) )
  235. .toPattern();
  236. /**
  237. * Default string representing Null String values (empty)
  238. */
  239. public static final String NULL_STRING = "";
  240. /**
  241. * Default string representing Null Number values (empty)
  242. */
  243. public static final String NULL_NUMBER = "";
  244. /**
  245. * Default string representing Null Date values (empty)
  246. */
  247. public static final String NULL_DATE = "";
  248. /**
  249. * Default string representing Null BigNumber values (empty)
  250. */
  251. public static final String NULL_BIGNUMBER = "";
  252. /**
  253. * Default string representing Null Boolean values (empty)
  254. */
  255. public static final String NULL_BOOLEAN = "";
  256. /**
  257. * Default string representing Null Integer values (empty)
  258. */
  259. public static final String NULL_INTEGER = "";
  260. /**
  261. * Default string representing Null Binary values (empty)
  262. */
  263. public static final String NULL_BINARY = "";
  264. /**
  265. * Default string representing Null Undefined values (empty)
  266. */
  267. public static final String NULL_NONE = "";
  268. /**
  269. * The base name of the Chef logfile
  270. */
  271. public static final String CHEF_LOG_FILE = "chef";
  272. /**
  273. * The base name of the Spoon logfile
  274. */
  275. public static final String SPOON_LOG_FILE = "spoon";
  276. /**
  277. * The base name of the Menu logfile
  278. */
  279. public static final String MENU_LOG_FILE = "menu";
  280. /**
  281. * A number of tips that are shown when the application first starts.
  282. */
  283. private static String[] tips;
  284. /**
  285. * An array of date conversion formats
  286. */
  287. private static String[] dateFormats;
  288. /**
  289. * An array of number conversion formats
  290. */
  291. private static String[] numberFormats;
  292. /**
  293. * Generalized date/time format: Wherever dates are used, date and time values are organized from the most to the
  294. * least significant. see also method StringUtil.getFormattedDateTime()
  295. */
  296. public static final String GENERALIZED_DATE_TIME_FORMAT = "yyyyddMM_hhmmss";
  297. public static final String GENERALIZED_DATE_TIME_FORMAT_MILLIS = "yyyyddMM_hhmmssSSS";
  298. /**
  299. * Default we store our information in Unicode UTF-8 character set.
  300. */
  301. public static final String XML_ENCODING = "UTF-8";
  302. /** The possible extensions a transformation XML file can have. */
  303. public static final String[] STRING_TRANS_AND_JOB_FILTER_EXT = new String[] {
  304. "*.ktr;*.kjb;*.xml", "*.ktr;*.xml", "*.kjb;*.xml", "*.xml", "*.*" };
  305. /** The discriptions of the possible extensions a transformation XML file can have. */
  306. private static String[] STRING_TRANS_AND_JOB_FILTER_NAMES;
  307. /** The extension of a Kettle transformation XML file */
  308. public static final String STRING_TRANS_DEFAULT_EXT = "ktr";
  309. /** The possible extensions a transformation XML file can have. */
  310. public static final String[] STRING_TRANS_FILTER_EXT = new String[] { "*.ktr;*.xml", "*.xml", "*.*" };
  311. /** The discriptions of the possible extensions a transformation XML file can have. */
  312. private static String[] STRING_TRANS_FILTER_NAMES;
  313. /** The extension of a Kettle job XML file */
  314. public static final String STRING_JOB_DEFAULT_EXT = "kjb";
  315. /** The possible extensions a job XML file can have. */
  316. public static final String[] STRING_JOB_FILTER_EXT = new String[] { "*.kjb;*.xml", "*.xml", "*.*" };
  317. /** The discriptions of the possible extensions a job XML file can have. */
  318. private static String[] STRING_JOB_FILTER_NAMES;
  319. /** Name of the kettle parameters file */
  320. public static final String KETTLE_PROPERTIES = "kettle.properties";
  321. /** The prefix that all internal kettle variables should have */
  322. public static final String INTERNAL_VARIABLE_PREFIX = "Internal";
  323. /** The version number as an internal variable */
  324. public static final String INTERNAL_VARIABLE_KETTLE_VERSION = INTERNAL_VARIABLE_PREFIX + ".Kettle.Version";
  325. /** The build version as an internal variable */
  326. public static final String INTERNAL_VARIABLE_KETTLE_BUILD_VERSION = INTERNAL_VARIABLE_PREFIX
  327. + ".Kettle.Build.Version";
  328. /** The build date as an internal variable */
  329. public static final String INTERNAL_VARIABLE_KETTLE_BUILD_DATE = INTERNAL_VARIABLE_PREFIX + ".Kettle.Build.Date";
  330. /** The job filename directory */
  331. public static final String INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY = INTERNAL_VARIABLE_PREFIX
  332. + ".Job.Filename.Directory";
  333. /** The job filename name */
  334. public static final String INTERNAL_VARIABLE_JOB_FILENAME_NAME = INTERNAL_VARIABLE_PREFIX + ".Job.Filename.Name";
  335. /** The job name */
  336. public static final String INTERNAL_VARIABLE_JOB_NAME = INTERNAL_VARIABLE_PREFIX + ".Job.Name";
  337. /** The job directory */
  338. public static final String INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY = INTERNAL_VARIABLE_PREFIX
  339. + ".Job.Repository.Directory";
  340. /** The job run ID */
  341. public static final String INTERNAL_VARIABLE_JOB_RUN_ID = INTERNAL_VARIABLE_PREFIX + ".Job.Run.ID";
  342. /** The job run attempt nr */
  343. public static final String INTERNAL_VARIABLE_JOB_RUN_ATTEMPTNR = INTERNAL_VARIABLE_PREFIX + ".Job.Run.AttemptNr";
  344. /**
  345. * All the internal transformation variables
  346. */
  347. public static final String[] INTERNAL_TRANS_VARIABLES = new String[] {
  348. Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY,
  349. Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME,
  350. Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY,
  351. };
  352. /**
  353. * All the internal job variables
  354. */
  355. public static final String[] INTERNAL_JOB_VARIABLES = new String[] {
  356. Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY, Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME,
  357. Const.INTERNAL_VARIABLE_JOB_NAME, Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY,
  358. Const.INTERNAL_VARIABLE_JOB_RUN_ID, Const.INTERNAL_VARIABLE_JOB_RUN_ATTEMPTNR, };
  359. /** The transformation filename directory */
  360. public static final String INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY = INTERNAL_VARIABLE_PREFIX
  361. + ".Transformation.Filename.Directory";
  362. /** The transformation filename name */
  363. public static final String INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME = INTERNAL_VARIABLE_PREFIX
  364. + ".Transformation.Filename.Name";
  365. /** The transformation name */
  366. public static final String INTERNAL_VARIABLE_TRANSFORMATION_NAME = INTERNAL_VARIABLE_PREFIX
  367. + ".Transformation.Name";
  368. /** The transformation directory */
  369. public static final String INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY = INTERNAL_VARIABLE_PREFIX
  370. + ".Transformation.Repository.Directory";
  371. /** The step partition ID */
  372. public static final String INTERNAL_VARIABLE_STEP_PARTITION_ID = INTERNAL_VARIABLE_PREFIX + ".Step.Partition.ID";
  373. /** The step partition number */
  374. public static final String INTERNAL_VARIABLE_STEP_PARTITION_NR = INTERNAL_VARIABLE_PREFIX
  375. + ".Step.Partition.Number";
  376. /** The slave transformation number */
  377. public static final String INTERNAL_VARIABLE_SLAVE_SERVER_NUMBER = INTERNAL_VARIABLE_PREFIX
  378. + ".Slave.Transformation.Number";
  379. /** The slave transformation name */
  380. public static final String INTERNAL_VARIABLE_SLAVE_SERVER_NAME = INTERNAL_VARIABLE_PREFIX + ".Slave.Server.Name";
  381. /** The size of the cluster : number of slaves */
  382. public static final String INTERNAL_VARIABLE_CLUSTER_SIZE = INTERNAL_VARIABLE_PREFIX + ".Cluster.Size";
  383. /** The slave transformation number */
  384. public static final String INTERNAL_VARIABLE_STEP_UNIQUE_NUMBER = INTERNAL_VARIABLE_PREFIX
  385. + ".Step.Unique.Number";
  386. /** Is this transformation running clustered, on the master? */
  387. public static final String INTERNAL_VARIABLE_CLUSTER_MASTER = INTERNAL_VARIABLE_PREFIX + ".Cluster.Master";
  388. /**
  389. * The internal clustered run ID, unique across a clustered execution, important while doing parallel clustered runs
  390. */
  391. public static final String INTERNAL_VARIABLE_CLUSTER_RUN_ID = INTERNAL_VARIABLE_PREFIX + ".Cluster.Run.ID";
  392. /** The size of the cluster : number of slaves */
  393. public static final String INTERNAL_VARIABLE_STEP_UNIQUE_COUNT = INTERNAL_VARIABLE_PREFIX + ".Step.Unique.Count";
  394. /** The step name */
  395. public static final String INTERNAL_VARIABLE_STEP_NAME = INTERNAL_VARIABLE_PREFIX + ".Step.Name";
  396. /** The step copy nr */
  397. public static final String INTERNAL_VARIABLE_STEP_COPYNR = INTERNAL_VARIABLE_PREFIX + ".Step.CopyNr";
  398. /** The default maximum for the nr of lines in the GUI logs */
  399. public static final int MAX_NR_LOG_LINES = 5000;
  400. /** The default maximum for the nr of lines in the history views */
  401. public static final int MAX_NR_HISTORY_LINES = 50;
  402. /** The default fetch size for lines of history. */
  403. public static final int HISTORY_LINES_FETCH_SIZE = 10;
  404. /** The default log line timeout in minutes : 12 hours */
  405. public static final int MAX_LOG_LINE_TIMEOUT_MINUTES = 12 * 60;
  406. /** UI-agnostic flag for warnings */
  407. public static final int WARNING = 1;
  408. /** UI-agnostic flag for warnings */
  409. public static final int ERROR = 2;
  410. /** UI-agnostic flag for warnings */
  411. public static final int INFO = 3;
  412. /**
  413. * The margin between the text of a note and its border.
  414. */
  415. public static final int NOTE_MARGIN = 5;
  416. /**
  417. * The default undo level for Kettle
  418. */
  419. public static final int MAX_UNDO = 100;
  420. /**
  421. * The file that documents these variables.
  422. */
  423. public static final String KETTLE_VARIABLES_FILE = "kettle-variables.xml";
  424. /**
  425. * If you set this environment variable you can limit the log size of all transformations and jobs that don't have the
  426. * "log size limit" property set in their respective properties.
  427. */
  428. public static final String KETTLE_LOG_SIZE_LIMIT = "KETTLE_LOG_SIZE_LIMIT";
  429. /**
  430. * The name of the variable that defines the log database connection by default for all transformations
  431. */
  432. public static final String KETTLE_TRANS_LOG_DB = "KETTLE_TRANS_LOG_DB";
  433. /**
  434. * The name of the variable that defines the logging schema for all transformations
  435. */
  436. public static final String KETTLE_TRANS_LOG_SCHEMA = "KETTLE_TRANS_LOG_SCHEMA";
  437. /**
  438. * The name of the variable that defines the logging table for all transformations
  439. */
  440. public static final String KETTLE_TRANS_LOG_TABLE = "KETTLE_TRANS_LOG_TABLE";
  441. /**
  442. * The name of the variable that defines the log database connection by default for all jobs
  443. */
  444. public static final String KETTLE_JOB_LOG_DB = "KETTLE_JOB_LOG_DB";
  445. /**
  446. * The name of the variable that defines the logging schema for all jobs
  447. */
  448. public static final String KETTLE_JOB_LOG_SCHEMA = "KETTLE_JOB_LOG_SCHEMA";
  449. /**
  450. * The name of the variable that defines the logging table for all jobs
  451. */
  452. public static final String KETTLE_JOB_LOG_TABLE = "KETTLE_JOB_LOG_TABLE";
  453. /**
  454. * The name of the variable that defines the transformation performance log schema by default for all transformations
  455. */
  456. public static final String KETTLE_TRANS_PERFORMANCE_LOG_DB = "KETTLE_TRANS_PERFORMANCE_LOG_DB";
  457. /**
  458. * The name of the variable that defines the transformation performance log database connection by default for all
  459. * transformations
  460. */
  461. public static final String KETTLE_TRANS_PERFORMANCE_LOG_SCHEMA = "KETTLE_TRANS_PERFORMANCE_LOG_SCHEMA";
  462. /**
  463. * The name of the variable that defines the transformation performance log table by default for all transformations
  464. */
  465. public static final String KETTLE_TRANS_PERFORMANCE_LOG_TABLE = "KETTLE_TRANS_PERFORMANCE_LOG_TABLE";
  466. /**
  467. * The name of the variable that defines the job entry log database by default for all jobs
  468. */
  469. public static final String KETTLE_JOBENTRY_LOG_DB = "KETTLE_JOBENTRY_LOG_DB";
  470. /**
  471. * The name of the variable that defines the job entry log schema by default for all jobs
  472. */
  473. public static final String KETTLE_JOBENTRY_LOG_SCHEMA = "KETTLE_JOBENTRY_LOG_SCHEMA";
  474. /**
  475. * The name of the variable that defines the job entry log table by default for all jobs
  476. */
  477. public static final String KETTLE_JOBENTRY_LOG_TABLE = "KETTLE_JOBENTRY_LOG_TABLE";
  478. /**
  479. * The name of the variable that defines the steps log database by default for all transformations
  480. */
  481. public static final String KETTLE_STEP_LOG_DB = "KETTLE_STEP_LOG_DB";
  482. /**
  483. * The name of the variable that defines the steps log schema by default for all transformations
  484. */
  485. public static final String KETTLE_STEP_LOG_SCHEMA = "KETTLE_STEP_LOG_SCHEMA";
  486. /**
  487. * The name of the variable that defines the steps log table by default for all transformations
  488. */
  489. public static final String KETTLE_STEP_LOG_TABLE = "KETTLE_STEP_LOG_TABLE";
  490. /**
  491. * The name of the variable that defines the log channel log database by default for all transformations and jobs
  492. */
  493. public static final String KETTLE_CHANNEL_LOG_DB = "KETTLE_CHANNEL_LOG_DB";
  494. /**
  495. * The name of the variable that defines the log channel log schema by default for all transformations and jobs
  496. */
  497. public static final String KETTLE_CHANNEL_LOG_SCHEMA = "KETTLE_CHANNEL_LOG_SCHEMA";
  498. /**
  499. * The name of the variable that defines the log channel log table by default for all transformations and jobs
  500. */
  501. public static final String KETTLE_CHANNEL_LOG_TABLE = "KETTLE_CHANNEL_LOG_TABLE";
  502. /**
  503. * The name of the variable that defines the metrics log database by default for all transformations and jobs
  504. */
  505. public static final String KETTLE_METRICS_LOG_DB = "KETTLE_METRICS_LOG_DB";
  506. /**
  507. * The name of the variable that defines the metrics log schema by default for all transformations and jobs
  508. */
  509. public static final String KETTLE_METRICS_LOG_SCHEMA = "KETTLE_METRICS_LOG_SCHEMA";
  510. /**
  511. * The name of the variable that defines the metrics log table by default for all transformations and jobs
  512. */
  513. public static final String KETTLE_METRICS_LOG_TABLE = "KETTLE_METRICS_LOG_TABLE";
  514. /**
  515. * The name of the variable that defines the checkpoint log database by default for all jobs
  516. */
  517. public static final String KETTLE_CHECKPOINT_LOG_DB = "KETTLE_CHECKPOINT_LOG_DB";
  518. /**
  519. * The name of the variable that defines the checkpoint log schema by default for all jobs
  520. */
  521. public static final String KETTLE_CHECKPOINT_LOG_SCHEMA = "KETTLE_CHECKPOINT_LOG_SCHEMA";
  522. /**
  523. * The name of the variable that defines the checkpoint log table by default for all jobs
  524. */
  525. public static final String KETTLE_CHECKPOINT_LOG_TABLE = "KETTLE_CHECKPOINT_LOG_TABLE";
  526. /**
  527. * Name of the environment variable to set the location of the shared object file (xml) for transformations and jobs
  528. */
  529. public static final String KETTLE_SHARED_OBJECTS = "KETTLE_SHARED_OBJECTS";
  530. /**
  531. * System wide flag to drive the evaluation of null in ValueMeta. If this setting is set to "Y", an empty string and
  532. * null are different. Otherwise they are not.
  533. */
  534. public static final String KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL = "KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL";
  535. /**
  536. * System wide flag to allow non-strict string to number conversion for backward compatibility. If this setting is set
  537. * to "Y", an string starting with digits will be converted successfully into a number. (example: 192.168.1.1 will be
  538. * converted into 192 or 192.168 depending on the decimal symbol). The default (N) will be to throw an error if
  539. * non-numeric symbols are found in the string.
  540. */
  541. public static final String KETTLE_LENIENT_STRING_TO_NUMBER_CONVERSION =
  542. "KETTLE_LENIENT_STRING_TO_NUMBER_CONVERSION";
  543. /**
  544. * System wide flag to ignore timezone while writing date/timestamp value to the database. See PDI-10749 for details.
  545. */
  546. public static final String KETTLE_COMPATIBILITY_DB_IGNORE_TIMEZONE = "KETTLE_COMPATIBILITY_DB_IGNORE_TIMEZONE";
  547. /**
  548. * System wide flag to set the maximum number of log lines that are kept internally by Kettle. Set to 0 to keep all
  549. * rows (default)
  550. */
  551. public static final String KETTLE_MAX_LOG_SIZE_IN_LINES = "KETTLE_MAX_LOG_SIZE_IN_LINES";
  552. /**
  553. * System wide flag to set the maximum age (in minutes) of a log line while being kept internally by Kettle. Set to 0
  554. * to keep all rows indefinitely (default)
  555. */
  556. public static final String KETTLE_MAX_LOG_TIMEOUT_IN_MINUTES = "KETTLE_MAX_LOG_TIMEOUT_IN_MINUTES";
  557. /**
  558. * System wide flag to determine whether standard error will be redirected to Kettle logging facilities. Will redirect
  559. * if the value is equal ignoring case to the string "Y"
  560. */
  561. public static final String KETTLE_REDIRECT_STDERR = "KETTLE_REDIRECT_STDERR";
  562. /**
  563. * System wide flag to determine whether standard out will be redirected to Kettle logging facilities. Will redirect
  564. * if the value is equal ignoring case to the string "Y"
  565. */
  566. public static final String KETTLE_REDIRECT_STDOUT = "KETTLE_REDIRECT_STDOUT";
  567. /**
  568. * This environment variable will set a time-out after which waiting, completed or stopped transformations and jobs
  569. * will be automatically cleaned up. The default value is 1440 (one day).
  570. */
  571. public static final String KETTLE_CARTE_OBJECT_TIMEOUT_MINUTES = "KETTLE_CARTE_OBJECT_TIMEOUT_MINUTES";
  572. /**
  573. * System wide parameter: the maximum number of step performance snapshots to keep in memory. Set to 0 to keep all
  574. * snapshots indefinitely (default)
  575. */
  576. public static final String KETTLE_STEP_PERFORMANCE_SNAPSHOT_LIMIT = "KETTLE_STEP_PERFORMANCE_SNAPSHOT_LIMIT";
  577. /**
  578. * A variable to configure the maximum number of job trackers kept in memory.
  579. */
  580. public static final String KETTLE_MAX_JOB_TRACKER_SIZE = "KETTLE_MAX_JOB_TRACKER_SIZE";
  581. /**
  582. * A variable to configure the maximum number of job entry results kept in memory for logging purposes.
  583. */
  584. public static final String KETTLE_MAX_JOB_ENTRIES_LOGGED = "KETTLE_MAX_JOB_ENTRIES_LOGGED";
  585. /**
  586. * A variable to configure the maximum number of logging registry entries kept in memory for logging purposes.
  587. */
  588. public static final String KETTLE_MAX_LOGGING_REGISTRY_SIZE = "KETTLE_MAX_LOGGING_REGISTRY_SIZE";
  589. /**
  590. * The name of the system wide variable that can contain the name of the SAP Connection factory for the test button in
  591. * the DB dialog. This defaults to
  592. */
  593. public static final String KETTLE_SAP_CONNECTION_FACTORY = "KETTLE_SAP_CONNECTION_FACTORY";
  594. /**
  595. * The default SAP ERP connection factory
  596. */
  597. public static final String KETTLE_SAP_CONNECTION_FACTORY_DEFAULT_NAME =
  598. "org.pentaho.di.trans.steps.sapinput.sap.SAPConnectionFactory";
  599. /**
  600. * Name of the environment variable to specify additional classes to scan for plugin annotations
  601. */
  602. public static final String KETTLE_PLUGIN_CLASSES = "KETTLE_PLUGIN_CLASSES";
  603. /**
  604. * Name of the environment variable to specify additional packaged to scan for plugin annotations (warning: slow!)
  605. */
  606. public static final String KETTLE_PLUGIN_PACKAGES = "KETTLE_PLUGIN_PACKAGES";
  607. /**
  608. * Name of the environment variable that contains the size of the transformation rowset size. This overwrites values
  609. * that you set transformation settings.
  610. */
  611. public static final String KETTLE_TRANS_ROWSET_SIZE = "KETTLE_TRANS_ROWSET_SIZE";
  612. /**
  613. * A general initial version comment
  614. */
  615. public static final String VERSION_COMMENT_INITIAL_VERSION = "Creation of initial version";
  616. /**
  617. * A general edit version comment
  618. */
  619. public static final String VERSION_COMMENT_EDIT_VERSION = "Modification by user";
  620. /**
  621. * The XML file that contains the list of native Kettle steps
  622. */
  623. public static final String XML_FILE_KETTLE_STEPS = "kettle-steps.xml";
  624. /**
  625. * The name of the environment variable that will contain the alternative location of the kettle-steps.xml file
  626. */
  627. public static final String KETTLE_CORE_STEPS_FILE = "KETTLE_CORE_STEPS_FILE";
  628. /**
  629. * The XML file that contains the list of native partition plugins
  630. */
  631. public static final String XML_FILE_KETTLE_PARTITION_PLUGINS = "kettle-partition-plugins.xml";
  632. /**
  633. * The name of the environment variable that will contain the alternative location of the kettle-job-entries.xml file
  634. */
  635. public static final String KETTLE_CORE_JOBENTRIES_FILE = "KETTLE_CORE_JOBENTRIES_FILE";
  636. /**
  637. * The XML file that contains the list of native Kettle Carte Servlets
  638. */
  639. public static final String XML_FILE_KETTLE_SERVLETS = "kettle-servlets.xml";
  640. /**
  641. * The XML file that contains the list of native Kettle value metadata plugins
  642. */
  643. public static final String XML_FILE_KETTLE_VALUEMETA_PLUGINS = "kettle-valuemeta-plugins.xml";
  644. /**
  645. * The name of the environment variable that will contain the alternative location of the kettle-valuemeta-plugins.xml
  646. * file
  647. */
  648. public static final String KETTLE_VALUEMETA_PLUGINS_FILE = "KETTLE_VALUEMETA_PLUGINS_FILE";
  649. /**
  650. * The XML file that contains the list of native Kettle logging plugins
  651. */
  652. public static final String XML_FILE_KETTLE_LOGGING_PLUGINS = "kettle-logging-plugins.xml";
  653. /**
  654. * The name of the environment variable that will contain the alternative location of the kettle-logging-plugins.xml
  655. * file
  656. */
  657. public static final String KETTLE_LOGGING_PLUGINS_FILE = "KETTLE_LOGGING_PLUGINS_FILE";
  658. /**
  659. * The name of the environment variable that will contain the alternative location of the kettle-servlets.xml file
  660. */
  661. public static final String KETTLE_CORE_SERVLETS_FILE = "KETTLE_CORE_SERVLETS_FILE";
  662. /**
  663. * The name of the variable that optionally contains an alternative rowset get timeout (in ms). This only makes a
  664. * difference for extremely short lived transformations.
  665. */
  666. public static final String KETTLE_ROWSET_GET_TIMEOUT = "KETTLE_ROWSET_GET_TIMEOUT";
  667. /**
  668. * The name of the variable that optionally contains an alternative rowset put timeout (in ms). This only makes a
  669. * difference for extremely short lived transformations.
  670. */
  671. public static final String KETTLE_ROWSET_PUT_TIMEOUT = "KETTLE_ROWSET_PUT_TIMEOUT";
  672. /**
  673. * Set this variable to Y if you want to test a more efficient batching row set. (default = N)
  674. */
  675. public static final String KETTLE_BATCHING_ROWSET = "KETTLE_BATCHING_ROWSET";
  676. /**
  677. * Set this variable to Y to disable standard Kettle logging to the console. (stdout)
  678. */
  679. public static final String KETTLE_DISABLE_CONSOLE_LOGGING = "KETTLE_DISABLE_CONSOLE_LOGGING";
  680. /**
  681. * The XML file that contains the list of native Kettle job entries
  682. */
  683. public static final String XML_FILE_KETTLE_JOB_ENTRIES = "kettle-job-entries.xml";
  684. /**
  685. * The XML file that contains the list of native Kettle repository types (DB, File, etc)
  686. */
  687. public static final String XML_FILE_KETTLE_REPOSITORIES = "kettle-repositories.xml";
  688. /**
  689. * The XML file that contains the list of native Kettle database types (MySQL, Oracle, etc)
  690. */
  691. public static final String XML_FILE_KETTLE_DATABASE_TYPES = "kettle-database-types.xml";
  692. /**
  693. * The XML file that contains the list of native extension points (None by default, this is mostly for OEM purposes)
  694. */
  695. public static final String XML_FILE_KETTLE_EXTENSION_POINTS = "kettle-extension-points.xml";
  696. /**
  697. * the value the Pan JVM should return on exit.
  698. */
  699. public static final String KETTLE_TRANS_PAN_JVM_EXIT_CODE = "KETTLE_TRANS_PAN_JVM_EXIT_CODE";
  700. /**
  701. * The name of the variable containing an alternative default number format
  702. */
  703. public static final String KETTLE_DEFAULT_NUMBER_FORMAT = "KETTLE_DEFAULT_NUMBER_FORMAT";
  704. /**
  705. * The name of the variable containing an alternative default bignumber format
  706. */
  707. public static final String KETTLE_DEFAULT_BIGNUMBER_FORMAT = "KETTLE_DEFAULT_BIGNUMBER_FORMAT";
  708. /**
  709. * The name of the variable containing an alternative default integer format
  710. */
  711. public static final String KETTLE_DEFAULT_INTEGER_FORMAT = "KETTLE_DEFAULT_INTEGER_FORMAT";
  712. /**
  713. * The name of the variable containing an alternative default date format
  714. */
  715. public static final String KETTLE_DEFAULT_DATE_FORMAT = "KETTLE_DEFAULT_DATE_FORMAT";
  716. /**
  717. * Compatibility settings for setNrErrors
  718. */
  719. // see PDI-10270 for details.
  720. public static final String KETTLE_COMPATIBILITY_SET_ERROR_ON_SPECIFIC_JOB_ENTRIES =
  721. "KETTLE_COMPATIBILITY_SET_ERROR_ON_SPECIFIC_JOB_ENTRIES";
  722. /**
  723. * The XML file that contains the list of native import rules
  724. */
  725. public static final String XML_FILE_KETTLE_IMPORT_RULES = "kettle-import-rules.xml";
  726. private static String[] emptyPaddedSpacesStrings;
  727. /**
  728. * The release type of this compilation
  729. */
  730. public static final ReleaseType RELEASE = ReleaseType.GA;
  731. /**
  732. * The system environment variable indicating where the alternative location for the Pentaho metastore folder is
  733. * located.
  734. */
  735. public static final String PENTAHO_METASTORE_FOLDER = "PENTAHO_METASTORE_FOLDER";
  736. /**
  737. * The name of the local client MetaStore
  738. *
  739. */
  740. public static final String PENTAHO_METASTORE_NAME = "Pentaho Local Client Metastore";
  741. /**
  742. * rounds double f to any number of places after decimal point Does arithmetic using BigDecimal class to avoid integer
  743. * overflow while rounding
  744. *
  745. * @param f
  746. * The value to round
  747. * @param places
  748. * The number of decimal places
  749. * @return The rounded floating point value
  750. */
  751. public static final double round( double f, int places ) {
  752. return round( f, places, java.math.BigDecimal.ROUND_HALF_EVEN );
  753. }
  754. /**
  755. * rounds double f to any number of places after decimal point Does arithmetic using BigDecimal class to avoid integer
  756. * overflow while rounding
  757. *
  758. * @param f
  759. * The value to round
  760. * @param places
  761. * The number of decimal places
  762. * @param roundingMode
  763. * The mode for rounding, e.g. java.math.BigDecimal.ROUND_HALF_EVEN
  764. * @return The rounded floating point value
  765. */
  766. public static final double round( double f, int places, int roundingMode ) {
  767. // We can't round non-numbers or infinite values
  768. //
  769. if ( f == Double.NaN || f == Double.NEGATIVE_INFINITY || f == Double.POSITIVE_INFINITY ) {
  770. return f;
  771. }
  772. // Do the rounding...
  773. //
  774. java.math.BigDecimal bdtemp = java.math.BigDecimal.valueOf( f );
  775. bdtemp = bdtemp.setScale( places, roundingMode );
  776. return bdtemp.doubleValue();
  777. }
  778. /*
  779. * OLD code: caused a lot of problems with very small and very large numbers. It's a miracle it worked at all. Go
  780. * ahead, have a laugh... public static final float round(double f, int places) { float temp = (float) (f *
  781. * (Math.pow(10, places)));
  782. *
  783. * temp = (Math.round(temp));
  784. *
  785. * temp = temp / (int) (Math.pow(10, places));
  786. *
  787. * return temp;
  788. *
  789. * }
  790. */
  791. /**
  792. * Convert a String into an integer. If the conversion fails, assign a default value.
  793. *
  794. * @param str
  795. * The String to convert to an integer
  796. * @param def
  797. * The default value
  798. * @return The converted value or the default.
  799. */
  800. public static final int toInt( String str, int def ) {
  801. int retval;
  802. try {
  803. retval = Integer.parseInt( str );
  804. } catch ( Exception e ) {
  805. retval = def;
  806. }
  807. return retval;
  808. }
  809. /**
  810. * Convert a String into a long integer. If the conversion fails, assign a default value.
  811. *
  812. * @param str
  813. * The String to convert to a long integer
  814. * @param def
  815. * The default value
  816. * @return The converted value or the default.
  817. */
  818. public static final long toLong( String str, long def ) {
  819. long retval;
  820. try {
  821. retval = Long.parseLong( str );
  822. } catch ( Exception e ) {
  823. retval = def;
  824. }
  825. return retval;
  826. }
  827. /**
  828. * Convert a String into a double. If the conversion fails, assign a default value.
  829. *
  830. * @param str
  831. * The String to convert to a double
  832. * @param def
  833. * The default value
  834. * @return The converted value or the default.
  835. */
  836. public static final double toDouble( String str, double def ) {
  837. double retval;
  838. try {
  839. retval = Double.parseDouble( str );
  840. } catch ( Exception e ) {
  841. retval = def;
  842. }
  843. return retval;
  844. }
  845. /**
  846. * Convert a String into a date. The date format is <code>yyyy/MM/dd HH:mm:ss.SSS</code>. If the conversion fails,
  847. * assign a default value.
  848. *
  849. * @param str
  850. * The String to convert into a Date
  851. * @param def
  852. * The default value
  853. * @return The converted value or the default.
  854. */
  855. public static final Date toDate( String str, Date def ) {
  856. SimpleDateFormat df = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss.SSS", Locale.US );
  857. try {
  858. return df.parse( str );
  859. } catch ( ParseException e ) {
  860. return def;
  861. }
  862. }
  863. /**
  864. * Determines whether or not a character is considered a space. A character is considered a space in Kettle if it is a
  865. * space, a tab, a newline or a cariage return.
  866. *
  867. * @param c
  868. * The character to verify if it is a space.
  869. * @return true if the character is a space. false otherwise.
  870. */
  871. public static final boolean isSpace( char c ) {
  872. return c == ' ' || c == '\t' || c == '\r' || c == '\n' || Character.isWhitespace( c );
  873. }
  874. /**
  875. * Left trim: remove spaces to the left of a String.
  876. *
  877. * @param str
  878. * The String to left trim
  879. * @return The left trimmed String
  880. */
  881. public static String ltrim( String source ) {
  882. if ( source == null ) {
  883. return null;
  884. }
  885. int from = 0;
  886. while ( from < source.length() && isSpace( source.charAt( from ) ) ) {
  887. from++;
  888. }
  889. return source.substring( from );
  890. }
  891. /**
  892. * Right trim: remove spaces to the right of a string
  893. *
  894. * @param str
  895. * The string to right trim
  896. * @return The trimmed string.
  897. */
  898. public static String rtrim( String source ) {
  899. if ( source == null ) {
  900. return null;
  901. }
  902. int max = source.length();
  903. while ( max > 0 && isSpace( source.charAt( max - 1 ) ) ) {
  904. max--;
  905. }
  906. return source.substring( 0, max );
  907. }
  908. /**
  909. * Trims a string: removes the leading and trailing spaces of a String.
  910. *
  911. * @param str
  912. * The string to trim
  913. * @return The trimmed string.
  914. */
  915. public static final String trim( String str ) {
  916. if ( str == null ) {
  917. return null;
  918. }
  919. int max = str.length() - 1;
  920. int min = 0;
  921. while ( min <= max && isSpace( str.charAt( min ) ) ) {
  922. min++;
  923. }
  924. while ( max >= 0 && isSpace( str.charAt( max ) ) ) {
  925. max--;
  926. }
  927. if ( max < min ) {
  928. return "";
  929. }
  930. return str.substring( min, max + 1 );
  931. }
  932. /**
  933. * Right pad a string: adds spaces to a string until a certain length. If the length is smaller then the limit
  934. * specified, the String is truncated.
  935. *
  936. * @param ret
  937. * The string to pad
  938. * @param limit
  939. * The desired length of the padded string.
  940. * @return The padded String.
  941. */
  942. public static final String rightPad( String ret, int limit ) {
  943. if ( ret == null ) {
  944. return rightPad( new StringBuffer(), limit );
  945. } else {
  946. return rightPad( new StringBuffer( ret ), limit );
  947. }
  948. }
  949. /**
  950. * Right pad a StringBuffer: adds spaces to a string until a certain length. If the length is smaller then the limit
  951. * specified, the String is truncated.
  952. *
  953. * @param ret
  954. * The StringBuffer to pad
  955. * @param limit
  956. * The desired length of the padded string.
  957. * @return The padded String.
  958. */
  959. public static final String rightPad( StringBuffer ret, int limit ) {
  960. int len = ret.length();
  961. int l;
  962. if ( len > limit ) {
  963. ret.setLength( limit );
  964. } else {
  965. for ( l = len; l < limit; l++ ) {
  966. ret.append( ' ' );
  967. }
  968. }
  969. return ret.toString();
  970. }
  971. /**
  972. * Replace values in a String with another.
  973. *
  974. * @param string
  975. * The original String.
  976. * @param repl
  977. * The text to replace
  978. * @param with
  979. * The new text bit
  980. * @return The resulting string with the text pieces replaced.
  981. */
  982. public static final String replace( String string, String repl, String with ) {
  983. StringBuffer str = new StringBuffer( string );
  984. for ( int i = str.length() - 1; i >= 0; i-- ) {
  985. if ( str.substring( i ).startsWith( repl ) ) {
  986. str.delete( i, i + repl.length() );
  987. str.insert( i, with );
  988. }
  989. }
  990. return str.toString();
  991. }
  992. /**
  993. * Alternate faster version of string replace using a stringbuffer as input.
  994. *
  995. * @param str
  996. * The string where we want to replace in
  997. * @param code
  998. * The code to search for
  999. * @param repl
  1000. * The replacement string for code
  1001. */
  1002. public static void repl( StringBuffer str, String code, String repl ) {
  1003. int clength = code.length();
  1004. int i = str.length() - clength;
  1005. while ( i >= 0 ) {
  1006. String look = str.substring( i, i + clength );
  1007. // Look for a match!
  1008. if ( look.equalsIgnoreCase( code ) ) {
  1009. str.replace( i, i + clength, repl );
  1010. }
  1011. i--;
  1012. }
  1013. }
  1014. /**
  1015. * Count the number of spaces to the left of a text. (leading)
  1016. *
  1017. * @param field
  1018. * The text to examine
  1019. * @return The number of leading spaces found.
  1020. */
  1021. public static final int nrSpacesBefore( String field ) {
  1022. int nr = 0;
  1023. int len = field.length();
  1024. while ( nr < len && field.charAt( nr ) == ' ' ) {
  1025. nr++;
  1026. }
  1027. return nr;
  1028. }
  1029. /**
  1030. * Count the number of spaces to the right of a text. (trailing)
  1031. *
  1032. * @param field
  1033. * The text to examine
  1034. * @return The number of trailing spaces found.
  1035. */
  1036. public static final int nrSpacesAfter( String field ) {
  1037. int nr = 0;
  1038. int len = field.length();
  1039. while ( nr < len && field.charAt( field.length() - 1 - nr ) == ' ' ) {
  1040. nr++;
  1041. }
  1042. return nr;
  1043. }
  1044. /**
  1045. * Checks whether or not a String consists only of spaces.
  1046. *
  1047. * @param str
  1048. * The string to check
  1049. * @return true if the string has nothing but spaces.
  1050. */
  1051. public static final boolean onlySpaces( String str ) {
  1052. for ( int i = 0; i < str.length(); i++ ) {
  1053. if ( !isSpace( str.charAt( i ) ) ) {
  1054. return false;
  1055. }
  1056. }
  1057. return true;
  1058. }
  1059. /**
  1060. * determine the OS name
  1061. *
  1062. * @return The name of the OS
  1063. */
  1064. public static final String getOS() {
  1065. return System.getProperty( "os.name" );
  1066. }
  1067. /**
  1068. * Determine the quoting character depending on the OS. Often used for shell calls, gives back " for Windows systems
  1069. * otherwise '
  1070. *
  1071. * @return quoting character
  1072. */
  1073. public static String getQuoteCharByOS() {
  1074. if ( isWindows() ) {
  1075. return "\"";
  1076. } else {
  1077. return "'";
  1078. }
  1079. }
  1080. /**
  1081. * Quote a string depending on the OS. Often used for shell calls.
  1082. *
  1083. * @return quoted string
  1084. */
  1085. public static String optionallyQuoteStringByOS( String string ) {
  1086. String quote = getQuoteCharByOS();
  1087. if ( isEmpty( string ) ) {
  1088. return quote;
  1089. }
  1090. // If the field already contains quotes, we don't touch it anymore, just
  1091. // return the same string...
  1092. // also return it if no spaces are found
  1093. if ( string.indexOf( quote ) >= 0 || ( string.indexOf( ' ' ) < 0 && string.indexOf( '=' ) < 0 ) ) {
  1094. return string;
  1095. } else {
  1096. return quote + string + quote;
  1097. }
  1098. }
  1099. /**
  1100. * @return True if the OS is a Windows derivate.
  1101. */
  1102. public static final boolean isWindows() {
  1103. return getOS().startsWith( "Windows" );
  1104. }
  1105. /**
  1106. * @return True if the OS is a Linux derivate.
  1107. */
  1108. public static final boolean isLinux() {
  1109. return getOS().startsWith( "Linux" );
  1110. }
  1111. /**
  1112. * @return True if the OS is an OSX derivate.
  1113. */
  1114. public static final boolean isOSX() {
  1115. return getOS().toUpperCase().contains( "OS X" );
  1116. }
  1117. /**
  1118. * Determine the hostname of the machine Kettle is running on
  1119. *
  1120. * @return The hostname
  1121. */
  1122. public static final String getHostname() {
  1123. String lastHostname = "localhost";
  1124. try {
  1125. Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
  1126. while ( en.hasMoreElements() ) {
  1127. NetworkInterface nwi = en.nextElement();
  1128. Enumeration<InetAddress> ip = nwi.getInetAddresses();
  1129. while ( ip.hasMoreElements() ) {
  1130. InetAddress in = ip.nextElement();
  1131. lastHostname = in.getHostName();
  1132. // System.out.println(" ip address bound : "+in.getHostAddress());
  1133. // System.out.println(" hostname : "+in.getHostName());
  1134. // System.out.println(" Cann.hostname : "+in.getCanonicalHostName());
  1135. // System.out.println(" ip string : "+in.toString());
  1136. if ( !lastHostname.equalsIgnoreCase( "localhost" ) && !( lastHostname.indexOf( ':' ) >= 0 ) ) {
  1137. return lastHostname;
  1138. }
  1139. }
  1140. }
  1141. } catch ( SocketException e ) {
  1142. return lastHostname;
  1143. }
  1144. return lastHostname;
  1145. }
  1146. /**
  1147. * Determine the hostname of the machine Kettle is running on
  1148. *
  1149. * @return The hostname
  1150. */
  1151. public static final String getHostnameReal() {
  1152. if ( isWindows() ) {
  1153. // Windows will always set the 'COMPUTERNAME' variable
  1154. return System.getenv( "COMPUTERNAME" );
  1155. } else {
  1156. // If it is not Windows then it is most likely a Unix-like operating system
  1157. // such as Solaris, AIX, HP-UX, Linux or MacOS.
  1158. // Most modern shells (such as Bash or derivatives) sets the
  1159. // HOSTNAME variable so lets try that first.
  1160. String hostname = System.getenv( "HOSTNAME" );
  1161. if ( hostname != null ) {
  1162. return hostname;
  1163. } else {
  1164. BufferedReader br;
  1165. try {
  1166. Process pr = Runtime.getRuntime().exec( "hostname" );
  1167. br = new BufferedReader( new InputStreamReader( pr.getInputStream() ) );
  1168. String line;
  1169. if ( ( line = br.readLine() ) != null ) {
  1170. return line;
  1171. }
  1172. pr.waitFor();
  1173. br.close();
  1174. } catch ( IOException e ) {
  1175. return getHostname();
  1176. } catch ( InterruptedException e ) {
  1177. return getHostname();
  1178. }
  1179. }
  1180. }
  1181. return getHostname();
  1182. }
  1183. /**
  1184. * Determins the IP address of the machine Kettle is running on.
  1185. *
  1186. * @return The IP address
  1187. */
  1188. public static final String getIPAddress() throws Exception {
  1189. Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces();
  1190. while ( enumInterfaces.hasMoreElements() ) {
  1191. NetworkInterface nwi = enumInterfaces.nextElement();
  1192. Enumeration<InetAddress> ip = nwi.getInetAddresses();
  1193. while ( ip.hasMoreElements() ) {
  1194. InetAddress in = ip.nextElement();
  1195. if ( !in.isLoopbackAddress() && in.toString().indexOf( ":" ) < 0 ) {
  1196. return in.getHostAddress();
  1197. }
  1198. }
  1199. }
  1200. return "127.0.0.1";
  1201. }
  1202. /**
  1203. * Get the primary IP address tied to a network interface (excluding loop-back etc)
  1204. *
  1205. * @param networkInterfaceName
  1206. * the name of the network interface to interrogate
  1207. * @return null if the network interface or address wasn't found.
  1208. *
  1209. * @throws SocketException
  1210. * in case of a security or network error
  1211. */
  1212. public static final String getIPAddress( String networkInterfaceName ) throws SocketException {
  1213. NetworkInterface networkInterface = NetworkInterface.getByName( networkInterfaceName );
  1214. Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses();
  1215. while ( ipAddresses.hasMoreElements() ) {
  1216. InetAddress inetAddress = ipAddresses.nextElement();
  1217. if ( !inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf( ":" ) < 0 ) {
  1218. String hostname = inetAddress.getHostAddress();
  1219. return hostname;
  1220. }
  1221. }
  1222. return null;
  1223. }
  1224. /**
  1225. * Tries to determine the MAC address of the machine Kettle is running on.
  1226. *
  1227. * @return The MAC address.
  1228. */
  1229. public static final String getMACAddress() throws Exception {
  1230. String ip = getIPAddress();
  1231. String mac = "none";
  1232. String os = getOS();
  1233. String s = "";
  1234. @SuppressWarnings( "unused" )
  1235. Boolean errorOccured = false;
  1236. // System.out.println("os = "+os+", ip="+ip);
  1237. if ( os.equalsIgnoreCase( "Windows NT" )
  1238. || os.equalsIgnoreCase( "Windows 2000" ) || os.equalsIgnoreCase( "Windows XP" )
  1239. || os.equalsIgnoreCase( "Windows 95" ) || os.equalsIgnoreCase( "Windows 98" )
  1240. || os.equalsIgnoreCase( "Windows Me" ) || os.startsWith( "Windows" ) ) {
  1241. try {
  1242. // System.out.println("EXEC> nbtstat -a "+ip);
  1243. Process p = Runtime.getRuntime().exec( "nbtstat -a " + ip );
  1244. // read the standard output of the command
  1245. BufferedReader stdInput = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
  1246. while ( !procDone( p ) ) {
  1247. while ( ( s = stdInput.readLine() ) != null ) {
  1248. // System.out.println("NBTSTAT> "+s);
  1249. if ( s.indexOf( "MAC" ) >= 0 ) {
  1250. int idx = s.indexOf( '=' );
  1251. mac = s.substring( idx + 2 );
  1252. }
  1253. }
  1254. }
  1255. stdInput.close();
  1256. } catch ( Exception e ) {
  1257. errorOccured = true;
  1258. }
  1259. } else if ( os.equalsIgnoreCase( "Linux" ) ) {
  1260. try {
  1261. Process p = Runtime.getRuntime().exec( "/sbin/ifconfig -a" );
  1262. // read the standard output of the command
  1263. BufferedReader stdInput = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
  1264. while ( !procDone( p ) ) {
  1265. while ( ( s = stdInput.readLine() ) != null ) {
  1266. int idx = s.indexOf( "HWaddr" );
  1267. if ( idx >= 0 ) {
  1268. mac = s.substring( idx + 7 );
  1269. }
  1270. }
  1271. }
  1272. stdInput.close();
  1273. } catch ( Exception e ) {
  1274. errorOccured = true;
  1275. }
  1276. } else if ( os.equalsIgnoreCase( "Solaris" ) ) {
  1277. try {
  1278. Process p = Runtime.getRuntime().exec( "/usr/sbin/ifconfig -a" );
  1279. // read the standard output of the command
  1280. BufferedReader stdInput = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
  1281. while ( !procDone( p ) ) {
  1282. while ( ( s = stdInput.readLine() ) != null ) {
  1283. int idx = s.indexOf( "ether" );
  1284. if ( idx >= 0 ) {
  1285. mac = s.substring( idx + 6 );
  1286. }
  1287. }
  1288. }
  1289. stdInput.close();
  1290. } catch ( Exception e ) {
  1291. errorOccured = true;
  1292. }
  1293. } else if ( os.equalsIgnoreCase( "HP-UX" ) ) {
  1294. try {
  1295. Process p = Runtime.getRuntime().exec( "/usr/sbin/lanscan -a" );
  1296. // read the standard output of the command
  1297. BufferedReader stdInput = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
  1298. while ( !procDone( p ) ) {
  1299. while ( ( s = stdInput.readLine() ) != null ) {
  1300. if ( s.indexOf( "MAC" ) >= 0 ) {
  1301. int idx = s.indexOf( "0x" );
  1302. mac = s.substring( idx + 2 );
  1303. }
  1304. }
  1305. }
  1306. stdInput.close();
  1307. } catch ( Exception e ) {
  1308. errorOccured = true;
  1309. }
  1310. }
  1311. // should do something if we got an error processing!
  1312. return Const.trim( mac );
  1313. }
  1314. private static final boolean procDone( Process p ) {
  1315. try {
  1316. p.exitValue();
  1317. return true;
  1318. } catch ( IllegalThreadStateException e ) {
  1319. return false;
  1320. }
  1321. }
  1322. /**
  1323. * Looks up the user's home directory (or KETTLE_HOME) for every invocation. This is no longer a static property so
  1324. * the value may be set after this class is loaded.
  1325. *
  1326. * @return The path to the users home directory, or the System property {@code KETTLE_HOME} if set.
  1327. */
  1328. public static final String getUserHomeDirectory() {
  1329. return NVL( System.getProperty( "KETTLE_HOME" ), System.getProperty( "user.home" ) );
  1330. }
  1331. /**
  1332. * Determines the Kettle directory in the user's home directory.
  1333. *
  1334. * @return The Kettle directory.
  1335. */
  1336. public static final String getKettleDirectory() {
  1337. return getUserHomeDirectory() + FILE_SEPARATOR + BasePropertyHandler.getProperty( "userBaseDir", ".kettle" );
  1338. }
  1339. /**
  1340. * Returns the value of DI_HOME.
  1341. */
  1342. public static final String getDIHomeDirectory() {
  1343. return System.getProperty( "DI_HOME" );
  1344. }
  1345. /**
  1346. * Determines the location of the shared objects file
  1347. *
  1348. * @return the name of the shared objects file
  1349. */
  1350. public static final String getSharedObjectsFile() {
  1351. return getKettleDirectory() + FILE_SEPARATOR + "shared.xml";
  1352. }
  1353. /**
  1354. * Returns the path to the Kettle local (current directory) repositories XML file.
  1355. *
  1356. * @return The local repositories file.
  1357. */
  1358. public static final String getKettleLocalRepositoriesFile() {
  1359. return "repositories.xml";
  1360. }
  1361. /**
  1362. * Returns the full path to the Kettle repositories XML file.
  1363. *
  1364. * @return The Kettle repositories file.
  1365. */
  1366. public static final String getKettleUserRepositoriesFile() {
  1367. return getKettleDirectory() + FILE_SEPARATOR + getKettleLocalRepositoriesFile();
  1368. }
  1369. /**
  1370. * Returns the path to the Kettle local (current directory) Carte password file:
  1371. * <p>
  1372. * ./pwd/kettle.pwd<br>
  1373. *
  1374. * @return The local Carte password file.
  1375. */
  1376. public static final String getKettleLocalCartePasswordFile() {
  1377. return "pwd/kettle.pwd";
  1378. }
  1379. /**
  1380. * Returns the path to the Kettle Carte password file in the home directory:
  1381. * <p>
  1382. * $KETTLE_HOME/.kettle/kettle.pwd<br>
  1383. *
  1384. * @return The Carte password file in the home directory.
  1385. */
  1386. public static final String getKettleCartePasswordFile() {
  1387. return getKettleDirectory() + FILE_SEPARATOR + "kettle.pwd";
  1388. }
  1389. /**
  1390. * Retrieves the content of an environment variable
  1391. *
  1392. * @param variable
  1393. * The name of the environment variable
  1394. * @param deflt
  1395. * The default value in case no value was found
  1396. * @return The value of the environment variable or the value of deflt in case no variable was defined.
  1397. */
  1398. public static String getEnvironmentVariable( String variable, String deflt ) {
  1399. return System.getProperty( variable, deflt );
  1400. }
  1401. /**
  1402. * Replaces environment variables in a string. For example if you set KETTLE_HOME as an environment variable, you can
  1403. * use %%KETTLE_HOME%% in dialogs etc. to refer to this value. This procedures looks for %%...%% pairs and replaces
  1404. * them including the name of the environment variable with the actual value. In case the variable was not set,
  1405. * nothing is replaced!
  1406. *
  1407. * @param string
  1408. * The source string where text is going to be replaced.
  1409. *
  1410. * @return The expanded string.
  1411. * @deprecated use StringUtil.environmentSubstitute(): handles both Windows and unix conventions
  1412. */
  1413. @Deprecated
  1414. public static final String replEnv( String string ) {
  1415. if ( string == null ) {
  1416. return null;
  1417. }
  1418. StringBuffer str = new StringBuffer( string );
  1419. int idx = str.indexOf( "%%" );
  1420. while ( idx >= 0 ) {
  1421. // OK, so we found a marker, look for the next one...
  1422. int to = str.indexOf( "%%", idx + 2 );
  1423. if ( to >= 0 ) {
  1424. // OK, we found the other marker also...
  1425. String marker = str.substring( idx, to + 2 );
  1426. String var = str.substring( idx + 2, to );
  1427. if ( var != null && var.length() > 0 ) {
  1428. // Get the environment variable
  1429. String newval = getEnvironmentVariable( var, null );
  1430. if ( newval != null ) {
  1431. // Replace the whole bunch
  1432. str.replace( idx, to + 2, newval );
  1433. // System.out.println("Replaced ["+marker+"] with ["+newval+"]");
  1434. // The last position has changed...
  1435. to += newval.length() - marker.length();
  1436. }
  1437. }
  1438. } else {
  1439. // We found the start, but NOT the ending %% without closing %%
  1440. to = idx;
  1441. }
  1442. // Look for the next variable to replace...
  1443. idx = str.indexOf( "%%", to + 1 );
  1444. }
  1445. return str.toString();
  1446. }
  1447. /**
  1448. * Replaces environment variables in an array of strings.
  1449. * <p>
  1450. * See also: replEnv(String string)
  1451. *
  1452. * @param string
  1453. * The array of strings that wants its variables to be replaced.
  1454. * @return the array with the environment variables replaced.
  1455. * @deprecated please use StringUtil.environmentSubstitute now.
  1456. */
  1457. @Deprecated
  1458. public static final String[] replEnv( String[] string ) {
  1459. String[] retval = new String[string.length];
  1460. for ( int i = 0; i < string.length; i++ ) {
  1461. retval[i] = Const.replEnv( string[i] );
  1462. }
  1463. return retval;
  1464. }
  1465. /**
  1466. * Implements Oracle style NVL function
  1467. *
  1468. * @param source
  1469. * The source argument
  1470. * @param def
  1471. * The default value in case source is null or the length of the string is 0
  1472. * @return source if source is not null, otherwise return def
  1473. */
  1474. public static final String NVL( String source, String def ) {
  1475. if ( source == null || source.length() == 0 ) {
  1476. return def;
  1477. }
  1478. return source;
  1479. }
  1480. /**
  1481. * Return empty string "" in case the given parameter is null, otherwise return the same value.
  1482. *
  1483. * @param source
  1484. * The source value to check for null.
  1485. * @return empty string if source is null, otherwise simply return the source value.
  1486. */
  1487. public static final String nullToEmpty( String source ) {
  1488. if ( source == null ) {
  1489. return "";
  1490. }
  1491. return source;
  1492. }
  1493. /**
  1494. * Search for a string in an array of strings and return the index.
  1495. *
  1496. * @param lookup
  1497. * The string to search for
  1498. * @param array
  1499. * The array of strings to look in
  1500. * @return The index of a search string in an array of strings. -1 if not found.
  1501. */
  1502. public static final int indexOfString( String lookup, String[] array ) {
  1503. if ( array == null ) {
  1504. return -1;
  1505. }
  1506. if ( lookup == null ) {
  1507. return -1;
  1508. }
  1509. for ( int i = 0; i < array.length; i++ ) {
  1510. if ( lookup.equalsIgnoreCase( array[i] ) ) {
  1511. return i;
  1512. }
  1513. }
  1514. return -1;
  1515. }
  1516. /**
  1517. * Search for strings in an array of strings and return the indexes.
  1518. *
  1519. * @param lookup
  1520. * The strings to search for
  1521. * @param array
  1522. * The array of strings to look in
  1523. * @return The indexes of strings in an array of strings. -1 if not found.
  1524. */
  1525. public static final int[] indexsOfStrings( String[] lookup, String[] array ) {
  1526. int[] indexes = new int[lookup.length];
  1527. for ( int i = 0; i < indexes.length; i++ ) {
  1528. indexes[i] = indexOfString( lookup[i], array );
  1529. }
  1530. return indexes;
  1531. }
  1532. /**
  1533. * Search for strings in an array of strings and return the indexes. If a string is not found, the index is not
  1534. * returned.
  1535. *
  1536. * @param lookup
  1537. * The strings to search for
  1538. * @param array
  1539. * The array of strings to look in
  1540. * @return The indexes of strings in an array of strings. Only existing indexes are returned (no -1)
  1541. */
  1542. public static final int[] indexsOfFoundStrings( String[] lookup, String[] array ) {
  1543. List<Integer> indexesList = new ArrayList<Integer>();
  1544. for ( int i = 0; i < lookup.length; i++ ) {
  1545. int idx = indexOfString( lookup[i], array );
  1546. if ( idx >= 0 ) {
  1547. indexesList.add( Integer.valueOf( idx ) );
  1548. }
  1549. }
  1550. int[] indexes = new int[indexesList.size()];
  1551. for ( int i = 0; i < indexesList.size(); i++ ) {
  1552. indexes[i] = ( indexesList.get( i ) ).intValue();
  1553. }
  1554. return indexes;
  1555. }
  1556. /**
  1557. * Search for a string in a list of strings and return the index.
  1558. *
  1559. * @param lookup
  1560. * The string to search for
  1561. * @param list
  1562. * The ArrayList of strings to look in
  1563. * @return The index of a search string in an array of strings. -1 if not found.
  1564. */
  1565. public static final int indexOfString( String lookup, List<String> list ) {
  1566. if ( list == null ) {
  1567. return -1;
  1568. }
  1569. for ( int i = 0; i < list.size(); i++ ) {
  1570. String compare = list.get( i );
  1571. if ( lookup.equalsIgnoreCase( compare ) ) {
  1572. return i;
  1573. }
  1574. }
  1575. return -1;
  1576. }
  1577. /**
  1578. * Sort the strings of an array in alphabetical order.
  1579. *
  1580. * @param input
  1581. * The array of strings to sort.
  1582. * @return The sorted array of strings.
  1583. */
  1584. public static final String[] sortStrings( String[] input ) {
  1585. Arrays.sort( input );
  1586. return input;
  1587. }
  1588. /**
  1589. * Convert strings separated by a string into an array of strings.
  1590. * <p>
  1591. * <code>
  1592. Example: a;b;c;d ==> new String[] { a, b, c, d }
  1593. * </code>
  1594. *
  1595. * <p>
  1596. * <b>NOTE: this differs from String.split() in a way that the built-in method uses regular expressions and this one
  1597. * does not.</b>
  1598. *
  1599. * @param string
  1600. * The string to split
  1601. * @param separator
  1602. * The separator used.
  1603. * @return the string split into an array of strings
  1604. */
  1605. public static final String[] splitString( String string, String separator ) {
  1606. /*
  1607. * 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
  1608. */
  1609. // System.out.println("splitString ["+path+"] using ["+separator+"]");
  1610. List<String> list = new ArrayList<String>();
  1611. if ( string == null || string.length() == 0 ) {
  1612. return new String[] {};
  1613. }
  1614. int sepLen = separator.length();
  1615. int from = 0;
  1616. int end = string.length() - sepLen + 1;
  1617. for ( int i = from; i < end; i += sepLen ) {
  1618. if ( string.substring( i, i + sepLen ).equalsIgnoreCase( separator ) ) {
  1619. // OK, we found a separator, the string to add to the list
  1620. // is [from, i[
  1621. list.add( NVL( string.substring( from, i ), "" ) );
  1622. from = i + sepLen;
  1623. }
  1624. }
  1625. // Wait, if the string didn't end with a separator, we still have information at the end of the string...
  1626. // In our example that would be "d"...
  1627. if ( from + sepLen <= string.length() ) {
  1628. list.add( NVL( string.substring( from, string.length() ), "" ) );
  1629. }
  1630. return list.toArray( new String[list.size()] );
  1631. }
  1632. /**
  1633. * Convert strings separated by a character into an array of strings.
  1634. * <p>
  1635. * <code>
  1636. Example: a;b;c;d == new String[] { a, b, c, d }
  1637. * </code>
  1638. *
  1639. * @param string
  1640. * The string to split
  1641. * @param separator
  1642. * The separator used.
  1643. * @return the string split into an array of strings
  1644. */
  1645. public static final String[] splitString( String string, char separator ) {
  1646. return splitString( string, separator, false );
  1647. }
  1648. /**
  1649. * Convert strings separated by a character into an array of strings.
  1650. * <p>
  1651. * <code>
  1652. Example: a;b;c;d == new String[] { a, b, c, d }
  1653. * </code>
  1654. *
  1655. * @param string
  1656. * The string to split
  1657. * @param separator
  1658. * The separator used.
  1659. * @param escape
  1660. * in case the separator can be escaped (\;) The escape characters are NOT removed!
  1661. * @return the string split into an array of strings
  1662. */
  1663. public static final String[] splitString( String string, char separator, boolean escape ) {
  1664. /*
  1665. * 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
  1666. */
  1667. // System.out.println("splitString ["+path+"] using ["+separator+"]");
  1668. List<String> list = new ArrayList<String>();
  1669. if ( string == null || string.length() == 0 ) {
  1670. return new String[] {};
  1671. }
  1672. int from = 0;
  1673. int end = string.length();
  1674. for ( int i = from; i < end; i += 1 ) {
  1675. boolean found = string.charAt( i ) == separator;
  1676. if ( found && escape && i > 0 ) {
  1677. found &= string.charAt( i - 1 ) != '\\';
  1678. }
  1679. if ( found ) {
  1680. // OK, we found a separator, the string to add to the list
  1681. // is [from, i[
  1682. list.add( NVL( string.substring( from, i ), "" ) );
  1683. from = i + 1;
  1684. }
  1685. }
  1686. // Wait, if the string didn't end with a separator, we still have information at the end of the string...
  1687. // In our example that would be "d"...
  1688. if ( from + 1 <= string.length() ) {
  1689. list.add( NVL( string.substring( from, string.length() ), "" ) );
  1690. }
  1691. return list.toArray( new String[list.size()] );
  1692. }
  1693. /**
  1694. * Convert strings separated by a string into an array of strings.
  1695. * <p>
  1696. * <code>
  1697. * Example /a/b/c --> new String[] { a, b, c }
  1698. * </code>
  1699. *
  1700. * @param path
  1701. * The string to split
  1702. * @param separator
  1703. * The separator used.
  1704. * @return the string split into an array of strings
  1705. */
  1706. public static final String[] splitPath( String path, String separator ) {
  1707. //
  1708. // Example /a/b/c --> new String[] { a, b, c }
  1709. //
  1710. // Make sure training slashes are removed
  1711. //
  1712. // Example /a/b/c/ --> new String[] { a, b, c }
  1713. //
  1714. // Check for empty paths...
  1715. //
  1716. if ( path == null || path.length() == 0 || path.equals( separator ) ) {
  1717. return new String[] {};
  1718. }
  1719. // lose trailing separators
  1720. //
  1721. while ( path.endsWith( separator ) ) {
  1722. path = path.substring( 0, path.length() - 1 );
  1723. }
  1724. int sepLen = separator.length();
  1725. int nr_separators = 1;
  1726. int from = path.startsWith( separator ) ? sepLen : 0;
  1727. for ( int i = from; i < path.length(); i += sepLen ) {
  1728. if ( path.substring( i, i + sepLen ).equalsIgnoreCase( separator ) ) {
  1729. nr_separators++;
  1730. }
  1731. }
  1732. String[] spath = new String[nr_separators];
  1733. int nr = 0;
  1734. for ( int i = from; i < path.length(); i += sepLen ) {
  1735. if ( path.substring( i, i + sepLen ).equalsIgnoreCase( separator ) ) {
  1736. spath[nr] = path.substring( from, i );
  1737. nr++;
  1738. from = i + sepLen;
  1739. }
  1740. }
  1741. if ( nr < spath.length ) {
  1742. spath[nr] = path.substring( from );
  1743. }
  1744. //
  1745. // a --> { a }
  1746. //
  1747. if ( spath.length == 0 && path.length() > 0 ) {
  1748. spath = new String[] { path };
  1749. }
  1750. return spath;
  1751. }
  1752. /**
  1753. * Split the given string using the given delimiter and enclosure strings.
  1754. *
  1755. * The delimiter and enclosures are not regular expressions (regexes); rather they are literal strings that will be
  1756. * quoted so as not to be treated like regexes.
  1757. *
  1758. * This method expects that the data contains an even number of enclosure strings in the input; otherwise the results
  1759. * are undefined
  1760. *
  1761. * @param stringToSplit
  1762. * the String to split
  1763. * @param delimiter
  1764. * the delimiter string
  1765. * @param enclosure
  1766. * the enclosure string
  1767. * @return an array of strings split on the delimiter (ignoring those in enclosures), or null if the string to split
  1768. * is null.
  1769. */
  1770. public static String[] splitString( String stringToSplit, String delimiter, String enclosure ) {
  1771. ArrayList<String> splitList = null;
  1772. // Handle "bad input" cases
  1773. if ( stringToSplit == null ) {
  1774. return null;
  1775. }
  1776. if ( delimiter == null ) {
  1777. return ( new String[] { stringToSplit } );
  1778. }
  1779. // Split the string on the delimiter, we'll build the "real" results from the partial results
  1780. String[] delimiterSplit = stringToSplit.split( Pattern.quote( delimiter ) );
  1781. // At this point, if the enclosure is null or empty, we will return the delimiter split
  1782. if ( isEmpty( enclosure ) ) {
  1783. return delimiterSplit;
  1784. }
  1785. // Keep track of partial splits and concatenate them into a legit split
  1786. StringBuffer concatSplit = null;
  1787. if ( delimiterSplit != null && delimiterSplit.length > 0 ) {
  1788. // We'll have at least one result so create the result list object
  1789. splitList = new ArrayList<String>();
  1790. // Proceed through the partial splits, concatenating if the splits are within the enclosure
  1791. for ( String currentSplit : delimiterSplit ) {
  1792. if ( !currentSplit.contains( enclosure ) ) {
  1793. // If we are currently concatenating a split, we are inside an enclosure. Since this
  1794. // split doesn't contain an enclosure, we can concatenate it (with a delimiter in front).
  1795. // If we're not concatenating, the split is fine so add it to the result list.
  1796. if ( concatSplit != null ) {
  1797. concatSplit.append( delimiter );
  1798. concatSplit.append( currentSplit );
  1799. } else {
  1800. splitList.add( currentSplit );
  1801. }
  1802. } else {
  1803. // Find number of enclosures in the split, and whether that number is odd or even.
  1804. int numEnclosures = StringUtils.countMatches( currentSplit, enclosure );
  1805. boolean oddNumberOfEnclosures = ( numEnclosures % 2 != 0 );
  1806. boolean addSplit = false;
  1807. // This split contains an enclosure, so either start or finish concatenating
  1808. if ( concatSplit == null ) {
  1809. concatSplit = new StringBuffer( currentSplit ); // start concatenation
  1810. addSplit = !oddNumberOfEnclosures;
  1811. } else {
  1812. // Check to make sure a new enclosure hasn't started within this split. This method expects
  1813. // that there are no non-delimiter characters between a delimiter and a starting enclosure.
  1814. // At this point in the code, the split shouldn't start with the enclosure, so add a delimiter
  1815. concatSplit.append( delimiter );
  1816. // Add the current split to the concatenated split
  1817. concatSplit.append( currentSplit );
  1818. // If the number of enclosures is odd, the enclosure is closed so add the split to the list
  1819. // and reset the "concatSplit" buffer. Otherwise continue
  1820. addSplit = oddNumberOfEnclosures;
  1821. }
  1822. if ( addSplit ) {
  1823. splitList.add( concatSplit.toString() );
  1824. concatSplit = null;
  1825. addSplit = false;
  1826. }
  1827. }
  1828. }
  1829. }
  1830. // Return list as array
  1831. return splitList.toArray( new String[splitList.size()] );
  1832. }
  1833. /**
  1834. * Sorts the array of Strings, determines the uniquely occurring strings.
  1835. *
  1836. * @param strings
  1837. * the array that you want to do a distinct on
  1838. * @return a sorted array of uniquely occurring strings
  1839. */
  1840. public static final String[] getDistinctStrings( String[] strings ) {
  1841. if ( strings == null ) {
  1842. return null;
  1843. }
  1844. if ( strings.length == 0 ) {
  1845. return new String[] {};
  1846. }
  1847. String[] sorted = sortStrings( strings );
  1848. List<String> result = new ArrayList<String>();
  1849. String previous = "";
  1850. for ( int i = 0; i < sorted.length; i++ ) {
  1851. if ( !sorted[i].equalsIgnoreCase( previous ) ) {
  1852. result.add( sorted[i] );
  1853. }
  1854. previous = sorted[i];
  1855. }
  1856. return result.toArray( new String[result.size()] );
  1857. }
  1858. /**
  1859. * Returns a string of the stack trace of the specified exception
  1860. */
  1861. public static final String getStackTracker( Throwable e ) {
  1862. return getClassicStackTrace( e );
  1863. }
  1864. public static final String getClassicStackTrace( Throwable e ) {
  1865. StringWriter stringWriter = new StringWriter();
  1866. PrintWriter printWriter = new PrintWriter( stringWriter );
  1867. e.printStackTrace( printWriter );
  1868. String string = stringWriter.toString();
  1869. try {
  1870. stringWriter.close();
  1871. } catch ( IOException ioe ) {
  1872. // is this really required?
  1873. }
  1874. return string;
  1875. }
  1876. public static String getCustomStackTrace( Throwable aThrowable ) {
  1877. final StringBuilder result = new StringBuilder();
  1878. String errorMessage = aThrowable.toString();
  1879. result.append( errorMessage );
  1880. if ( !errorMessage.contains( Const.CR ) ) {
  1881. result.append( CR );
  1882. }
  1883. // add each element of the stack trace
  1884. //
  1885. for ( StackTraceElement element : aThrowable.getStackTrace() ) {
  1886. result.append( element );
  1887. result.append( CR );
  1888. }
  1889. return result.toString();
  1890. }
  1891. /**
  1892. * Check if the string supplied is empty. A String is empty when it is null or when the length is 0
  1893. *
  1894. * @param string
  1895. * The string to check
  1896. * @return true if the string supplied is empty
  1897. */
  1898. public static final boolean isEmpty( String string ) {
  1899. return string == null || string.length() == 0;
  1900. }
  1901. /**
  1902. * Check if the stringBuffer supplied is empty. A StringBuffer is empty when it is null or when the length is 0
  1903. *
  1904. * @param string
  1905. * The stringBuffer to check
  1906. * @return true if the stringBuffer supplied is empty
  1907. */
  1908. public static final boolean isEmpty( StringBuffer string ) {
  1909. return string == null || string.length() == 0;
  1910. }
  1911. /**
  1912. * Check if the string array supplied is empty. A String array is empty when it is null or when the number of elements
  1913. * is 0
  1914. *
  1915. * @param string
  1916. * The string array to check
  1917. * @return true if the string array supplied is empty
  1918. */
  1919. public static final boolean isEmpty( String[] strings ) {
  1920. return strings == null || strings.length == 0;
  1921. }
  1922. /**
  1923. * Check if the array supplied is empty. An array is empty when it is null or when the length is 0
  1924. *
  1925. * @param array
  1926. * The array to check
  1927. * @return true if the array supplied is empty
  1928. */
  1929. public static final boolean isEmpty( Object[] array ) {
  1930. return array == null || array.length == 0;
  1931. }
  1932. /**
  1933. * Check if the list supplied is empty. An array is empty when it is null or when the length is 0
  1934. *
  1935. * @param list
  1936. * the list to check
  1937. * @return true if the supplied list is empty
  1938. */
  1939. public static final boolean isEmpty( List<?> list ) {
  1940. return list == null || list.size() == 0;
  1941. }
  1942. /**
  1943. * @return a new ClassLoader
  1944. */
  1945. public static final ClassLoader createNewClassLoader() throws KettleException {
  1946. try {
  1947. // Nothing really in URL, everything is in scope.
  1948. URL[] urls = new URL[] {};
  1949. URLClassLoader ucl = new URLClassLoader( urls );
  1950. return ucl;
  1951. } catch ( Exception e ) {
  1952. throw new KettleException( "Unexpected error during classloader creation", e );
  1953. }
  1954. }
  1955. /**
  1956. * Utility class for use in JavaScript to create a new byte array. This is surprisingly difficult to do in JavaScript.
  1957. *
  1958. * @return a new java byte array
  1959. */
  1960. public static final byte[] createByteArray( int size ) {
  1961. return new byte[size];
  1962. }
  1963. /**
  1964. * Sets the first character of each word in upper-case.
  1965. *
  1966. * @param string
  1967. * The strings to convert to initcap
  1968. * @return the input string but with the first character of each word converted to upper-case.
  1969. */
  1970. public static final String initCap( String string ) {
  1971. StringBuffer change = new StringBuffer( string );
  1972. boolean new_word;
  1973. int i;
  1974. char lower, upper, ch;
  1975. new_word = true;
  1976. for ( i = 0; i < string.length(); i++ ) {
  1977. lower = change.substring( i, i + 1 ).toLowerCase().charAt( 0 ); // Lowercase is default.
  1978. upper = change.substring( i, i + 1 ).toUpperCase().charAt( 0 ); // Uppercase for new words.
  1979. ch = upper;
  1980. if ( new_word ) {
  1981. change.setCharAt( i, upper );
  1982. } else {
  1983. change.setCharAt( i, lower );
  1984. }
  1985. new_word = false;
  1986. // Cast to (int) is required for extended characters (SB)
  1987. if ( !Character.isLetterOrDigit( (int) ch ) && ch != '_' ) {
  1988. new_word = true;
  1989. }
  1990. }
  1991. return change.toString();
  1992. }
  1993. /**
  1994. * Create a valid filename using a name We remove all special characters, spaces, etc.
  1995. *
  1996. * @param name
  1997. * The name to use as a base for the filename
  1998. * @return a valid filename
  1999. */
  2000. public static final String createFilename( String name ) {
  2001. StringBuffer filename = new StringBuffer();
  2002. for ( int i = 0; i < name.length(); i++ ) {
  2003. char c = name.charAt( i );
  2004. if ( Character.isUnicodeIdentifierPart( c ) ) {
  2005. filename.append( c );
  2006. } else if ( Character.isWhitespace( c ) ) {
  2007. filename.append( '_' );
  2008. }
  2009. }
  2010. return filename.toString().toLowerCase();
  2011. }
  2012. public static final String createFilename( String directory, String name, String extension ) {
  2013. if ( directory.endsWith( Const.FILE_SEPARATOR ) ) {
  2014. return directory + createFilename( name ) + extension;
  2015. } else {
  2016. return directory + Const.FILE_SEPARATOR + createFilename( name ) + extension;
  2017. }
  2018. }
  2019. public static final String createName( String filename ) {
  2020. if ( Const.isEmpty( filename ) ) {
  2021. return filename;
  2022. }
  2023. String pureFilename = filenameOnly( filename );
  2024. if ( pureFilename.endsWith( ".ktr" ) || pureFilename.endsWith( ".kjb" ) || pureFilename.endsWith( ".xml" ) ) {
  2025. pureFilename = pureFilename.substring( 0, pureFilename.length() - 4 );
  2026. }
  2027. StringBuffer sb = new StringBuffer();
  2028. for ( int i = 0; i < pureFilename.length(); i++ ) {
  2029. char c = pureFilename.charAt( i );
  2030. if ( Character.isUnicodeIdentifierPart( c ) ) {
  2031. sb.append( c );
  2032. } else if ( Character.isWhitespace( c ) ) {
  2033. sb.append( ' ' );
  2034. } else if ( c == '-' ) {
  2035. sb.append( c );
  2036. }
  2037. }
  2038. return sb.toString();
  2039. }
  2040. /**
  2041. * <p>
  2042. * Returns the pure filename of a filename with full path. E.g. if passed parameter is
  2043. * <code>/opt/tomcat/logs/catalina.out</code> this method returns <code>catalina.out</code>. The method works with the
  2044. * Environment variable <i>System.getProperty("file.separator")</i>, so on linux/Unix it will check for the last
  2045. * occurrence of a frontslash, on windows for the last occurrence of a backslash.
  2046. * </p>
  2047. *
  2048. * <p>
  2049. * To make this OS independent, the method could check for the last occurrence of a frontslash and backslash and use
  2050. * the higher value of both. Should work, since these characters aren't allowed in filenames on neither OS types (or
  2051. * said differently: Neither linux nor windows can carry frontslashes OR backslashes in filenames). Just a suggestion
  2052. * of an improvement ...
  2053. * </p>
  2054. *
  2055. * @param sFullPath
  2056. * @return
  2057. */
  2058. public static String filenameOnly( String sFullPath ) {
  2059. if ( Const.isEmpty( sFullPath ) ) {
  2060. return sFullPath;
  2061. }
  2062. int idx = sFullPath.lastIndexOf( FILE_SEPARATOR );
  2063. if ( idx != -1 ) {
  2064. return sFullPath.substring( idx + 1 );
  2065. } else {
  2066. idx = sFullPath.lastIndexOf( '/' ); // URL, VFS
  2067. if ( idx != -1 ) {
  2068. return sFullPath.substring( idx + 1 );
  2069. } else {
  2070. return sFullPath;
  2071. }
  2072. }
  2073. }
  2074. /**
  2075. * Returning the internationalized tips of the days. They get created once on first request.
  2076. *
  2077. * @return
  2078. */
  2079. public static String[] getTips() {
  2080. if ( tips == null ) {
  2081. int tipsOfDayCount = toInt( BaseMessages.getString( PKG, "Const.TipOfDay.Count" ), 0 );
  2082. tips = new String[tipsOfDayCount];
  2083. for ( int i = 1; i <= tipsOfDayCount; i++ ) {
  2084. tips[i - 1] = BaseMessages.getString( PKG, "Const.TipOfDay" + Integer.toString( i ) );
  2085. }
  2086. }
  2087. return tips;
  2088. }
  2089. /**
  2090. * Returning the localized date conversion formats. They get created once on first request.
  2091. *
  2092. * @return
  2093. */
  2094. public static String[] getDateFormats() {
  2095. if ( dateFormats == null ) {
  2096. int dateFormatsCount = toInt( BaseMessages.getString( PKG, "Const.DateFormat.Count" ), 0 );
  2097. dateFormats = new String[dateFormatsCount];
  2098. for ( int i = 1; i <= dateFormatsCount; i++ ) {
  2099. dateFormats[i - 1] = BaseMessages.getString( PKG, "Const.DateFormat" + Integer.toString( i ) );
  2100. }
  2101. }
  2102. return dateFormats;
  2103. }
  2104. /**
  2105. * Returning the localized number conversion formats. They get created once on first request.
  2106. *
  2107. * @return
  2108. */
  2109. public static String[] getNumberFormats() {
  2110. if ( numberFormats == null ) {
  2111. int numberFormatsCount = toInt( BaseMessages.getString( PKG, "Const.NumberFormat.Count" ), 0 );
  2112. numberFormats = new String[numberFormatsCount + 1];
  2113. numberFormats[0] = DEFAULT_NUMBER_FORMAT;
  2114. for ( int i = 1; i <= numberFormatsCount; i++ ) {
  2115. numberFormats[i] = BaseMessages.getString( PKG, "Const.NumberFormat" + Integer.toString( i ) );
  2116. }
  2117. }
  2118. return numberFormats;
  2119. }
  2120. /**
  2121. * @return An array of all default conversion formats, to be used in dialogs etc.
  2122. */
  2123. public static String[] getConversionFormats() {
  2124. String[] dats = Const.getDateFormats();
  2125. String[] nums = Const.getNumberFormats();
  2126. int totsize = dats.length + nums.length;
  2127. String[] formats = new String[totsize];
  2128. for ( int x = 0; x < dats.length; x++ ) {
  2129. formats[x] = dats[x];
  2130. }
  2131. for ( int x = 0; x < nums.length; x++ ) {
  2132. formats[dats.length + x] = nums[x];
  2133. }
  2134. return formats;
  2135. }
  2136. public static String[] getTransformationAndJobFilterNames() {
  2137. if ( STRING_TRANS_AND_JOB_FILTER_NAMES == null ) {
  2138. STRING_TRANS_AND_JOB_FILTER_NAMES =
  2139. new String[] {
  2140. BaseMessages.getString( PKG, "Const.FileFilter.TransformationJob" ),
  2141. BaseMessages.getString( PKG, "Const.FileFilter.Transformations" ),
  2142. BaseMessages.getString( PKG, "Const.FileFilter.Jobs" ),
  2143. BaseMessages.getString( PKG, "Const.FileFilter.XML" ),
  2144. BaseMessages.getString( PKG, "Const.FileFilter.All" ) };
  2145. }
  2146. return STRING_TRANS_AND_JOB_FILTER_NAMES;
  2147. }
  2148. public static String[] getTransformationFilterNames() {
  2149. if ( STRING_TRANS_FILTER_NAMES == null ) {
  2150. STRING_TRANS_FILTER_NAMES =
  2151. new String[] {
  2152. BaseMessages.getString( PKG, "Const.FileFilter.Transformations" ),
  2153. BaseMessages.getString( PKG, "Const.FileFilter.XML" ),
  2154. BaseMessages.getString( PKG, "Const.FileFilter.All" ) };
  2155. }
  2156. return STRING_TRANS_FILTER_NAMES;
  2157. }
  2158. public static String[] getJobFilterNames() {
  2159. if ( STRING_JOB_FILTER_NAMES == null ) {
  2160. STRING_JOB_FILTER_NAMES =
  2161. new String[] {
  2162. BaseMessages.getString( PKG, "Const.FileFilter.Jobs" ),
  2163. BaseMessages.getString( PKG, "Const.FileFilter.XML" ),
  2164. BaseMessages.getString( PKG, "Const.FileFilter.All" ) };
  2165. }
  2166. return STRING_JOB_FILTER_NAMES;
  2167. }
  2168. /**
  2169. * Return the current time as nano-seconds.
  2170. *
  2171. * @return time as nano-seconds.
  2172. */
  2173. public static long nanoTime() {
  2174. return new Date().getTime() * 1000;
  2175. }
  2176. /**
  2177. * Return the input string trimmed as specified.
  2178. *
  2179. * @param string
  2180. * String to be trimmed
  2181. * @param trimType
  2182. * Type of trimming
  2183. *
  2184. * @return Trimmed string.
  2185. */
  2186. public static String trimToType( String string, int trimType ) {
  2187. switch ( trimType ) {
  2188. case ValueMetaInterface.TRIM_TYPE_BOTH:
  2189. return trim( string );
  2190. case ValueMetaInterface.TRIM_TYPE_LEFT:
  2191. return ltrim( string );
  2192. case ValueMetaInterface.TRIM_TYPE_RIGHT:
  2193. return rtrim( string );
  2194. case ValueMetaInterface.TRIM_TYPE_NONE:
  2195. default:
  2196. return string;
  2197. }
  2198. }
  2199. /**
  2200. * implemented to help prevent errors in matching up pluggable LAF directories and paths/files eliminating malformed
  2201. * URLs - duplicate file separators or missing file separators.
  2202. *
  2203. * @param dir
  2204. * @param file
  2205. * @return concatenated string representing a file url
  2206. */
  2207. public static String safeAppendDirectory( String dir, String file ) {
  2208. boolean dirHasSeparator = ( ( dir.lastIndexOf( FILE_SEPARATOR ) ) == dir.length() );
  2209. boolean fileHasSeparator = ( file.indexOf( FILE_SEPARATOR ) != 0 );
  2210. if ( ( dirHasSeparator && !fileHasSeparator ) || ( !dirHasSeparator && fileHasSeparator ) ) {
  2211. return dir + file;
  2212. }
  2213. if ( dirHasSeparator && fileHasSeparator ) {
  2214. return dir + file.substring( 1 );
  2215. }
  2216. return dir + FILE_SEPARATOR + file;
  2217. }
  2218. /**
  2219. * Create an array of Strings consisting of spaces. The index of a String in the array determines the number of spaces
  2220. * in that string.
  2221. *
  2222. * @return array of 'space' Strings.
  2223. */
  2224. public static String[] getEmptyPaddedStrings() {
  2225. if ( emptyPaddedSpacesStrings == null ) {
  2226. emptyPaddedSpacesStrings = new String[250];
  2227. for ( int i = 0; i < emptyPaddedSpacesStrings.length; i++ ) {
  2228. emptyPaddedSpacesStrings[i] = rightPad( "", i );
  2229. }
  2230. }
  2231. return emptyPaddedSpacesStrings;
  2232. }
  2233. /**
  2234. * Return the percentage of free memory for this JVM.
  2235. *
  2236. * @return Percentage of free memory.
  2237. */
  2238. public static final int getPercentageFreeMemory() {
  2239. Runtime runtime = Runtime.getRuntime();
  2240. long maxMemory = runtime.maxMemory();
  2241. long allocatedMemory = runtime.totalMemory();
  2242. long freeMemory = runtime.freeMemory();
  2243. long totalFreeMemory = ( freeMemory + ( maxMemory - allocatedMemory ) );
  2244. int percentage = (int) Math.round( 100 * (double) totalFreeMemory / maxMemory );
  2245. return percentage;
  2246. }
  2247. /**
  2248. * Return non digits only.
  2249. *
  2250. * @return non digits in a string.
  2251. */
  2252. public static String removeDigits( String input ) {
  2253. if ( Const.isEmpty( input ) ) {
  2254. return null;
  2255. }
  2256. StringBuffer digitsOnly = new StringBuffer();
  2257. char c;
  2258. for ( int i = 0; i < input.length(); i++ ) {
  2259. c = input.charAt( i );
  2260. if ( !Character.isDigit( c ) ) {
  2261. digitsOnly.append( c );
  2262. }
  2263. }
  2264. return digitsOnly.toString();
  2265. }
  2266. /**
  2267. * Return digits only.
  2268. *
  2269. * @return digits in a string.
  2270. */
  2271. public static String getDigitsOnly( String input ) {
  2272. if ( Const.isEmpty( input ) ) {
  2273. return null;
  2274. }
  2275. StringBuffer digitsOnly = new StringBuffer();
  2276. char c;
  2277. for ( int i = 0; i < input.length(); i++ ) {
  2278. c = input.charAt( i );
  2279. if ( Character.isDigit( c ) ) {
  2280. digitsOnly.append( c );
  2281. }
  2282. }
  2283. return digitsOnly.toString();
  2284. }
  2285. /**
  2286. * Remove time from a date.
  2287. *
  2288. * @return a date without hour.
  2289. */
  2290. public static Date removeTimeFromDate( Date input ) {
  2291. if ( input == null ) {
  2292. return null;
  2293. }
  2294. // Get an instance of the Calendar.
  2295. Calendar calendar = Calendar.getInstance();
  2296. // Make sure the calendar will not perform automatic correction.
  2297. calendar.setLenient( false );
  2298. // Set the time of the calendar to the given date.
  2299. calendar.setTime( input );
  2300. // Remove the hours, minutes, seconds and milliseconds.
  2301. calendar.set( Calendar.HOUR_OF_DAY, 0 );
  2302. calendar.set( Calendar.MINUTE, 0 );
  2303. calendar.set( Calendar.SECOND, 0 );
  2304. calendar.set( Calendar.MILLISECOND, 0 );
  2305. // Return the date again.
  2306. return calendar.getTime();
  2307. }
  2308. /**
  2309. * Escape XML content. i.e. replace characters with &values;
  2310. *
  2311. * @param content
  2312. * content
  2313. * @return escaped content
  2314. */
  2315. public static String escapeXML( String content ) {
  2316. if ( isEmpty( content ) ) {
  2317. return content;
  2318. }
  2319. return StringEscapeUtils.escapeXml( content );
  2320. }
  2321. /**
  2322. * Escape HTML content. i.e. replace characters with &values;
  2323. *
  2324. * @param content
  2325. * content
  2326. * @return escaped content
  2327. */
  2328. public static String escapeHtml( String content ) {
  2329. if ( isEmpty( content ) ) {
  2330. return content;
  2331. }
  2332. return StringEscapeUtils.escapeHtml( content );
  2333. }
  2334. /**
  2335. * UnEscape HTML content. i.e. replace characters with &values;
  2336. *
  2337. * @param content
  2338. * content
  2339. * @return unescaped content
  2340. */
  2341. public static String unEscapeHtml( String content ) {
  2342. if ( isEmpty( content ) ) {
  2343. return content;
  2344. }
  2345. return StringEscapeUtils.unescapeHtml( content );
  2346. }
  2347. /**
  2348. * UnEscape XML content. i.e. replace characters with &values;
  2349. *
  2350. * @param content
  2351. * content
  2352. * @return unescaped content
  2353. */
  2354. public static String unEscapeXml( String content ) {
  2355. if ( isEmpty( content ) ) {
  2356. return content;
  2357. }
  2358. return StringEscapeUtils.unescapeXml( content );
  2359. }
  2360. /**
  2361. * Escape SQL content. i.e. replace characters with &values;
  2362. *
  2363. * @param content
  2364. * content
  2365. * @return escaped content
  2366. */
  2367. public static String escapeSQL( String content ) {
  2368. if ( isEmpty( content ) ) {
  2369. return content;
  2370. }
  2371. return StringEscapeUtils.escapeSql( content );
  2372. }
  2373. /**
  2374. * Remove CR / LF from String
  2375. *
  2376. * @param in
  2377. * input
  2378. * @return cleaned string
  2379. */
  2380. public static String removeCRLF( String in ) {
  2381. char[] inArray = in.toCharArray();
  2382. StringBuffer out = new StringBuffer( inArray.length );
  2383. for ( int i = 0; i < inArray.length; i++ ) {
  2384. char c = inArray[i];
  2385. if ( !( c == '\n' || c == '\r' ) ) {
  2386. out.append( c );
  2387. }
  2388. }
  2389. return out.toString();
  2390. }
  2391. /**
  2392. * Remove CR / LF from String
  2393. *
  2394. * @param in
  2395. * input
  2396. * @return cleaned string
  2397. */
  2398. public static String removeCR( String in ) {
  2399. char[] inArray = in.toCharArray();
  2400. StringBuffer out = new StringBuffer( inArray.length );
  2401. for ( int i = 0; i < inArray.length; i++ ) {
  2402. char c = inArray[i];
  2403. if ( c != '\n' ) {
  2404. out.append( c );
  2405. }
  2406. }
  2407. return out.toString();
  2408. } // removeCR
  2409. /**
  2410. * Remove CR / LF from String
  2411. *
  2412. * @param in
  2413. * input
  2414. * @return cleaned string
  2415. */
  2416. public static String removeLF( String in ) {
  2417. char[] inArray = in.toCharArray();
  2418. StringBuffer out = new StringBuffer( inArray.length );
  2419. for ( int i = 0; i < inArray.length; i++ ) {
  2420. char c = inArray[i];
  2421. if ( c != '\r' ) {
  2422. out.append( c );
  2423. }
  2424. }
  2425. return out.toString();
  2426. } // removeCRLF
  2427. /**
  2428. * Remove Horizontan Tab from String
  2429. *
  2430. * @param in
  2431. * input
  2432. * @return cleaned string
  2433. */
  2434. public static String removeTAB( String in ) {
  2435. char[] inArray = in.toCharArray();
  2436. StringBuffer out = new StringBuffer( inArray.length );
  2437. for ( int i = 0; i < inArray.length; i++ ) {
  2438. char c = inArray[i];
  2439. if ( c != '\t' ) {
  2440. out.append( c );
  2441. }
  2442. }
  2443. return out.toString();
  2444. }
  2445. /**
  2446. * Add time to an input date
  2447. *
  2448. * @param input
  2449. * the date
  2450. * @param time
  2451. * the time to add (in string)
  2452. * @param DateFormat
  2453. * the time format
  2454. * @return date = input + time
  2455. */
  2456. public static Date addTimeToDate( Date input, String time, String DateFormat ) throws Exception {
  2457. if ( isEmpty( time ) ) {
  2458. return input;
  2459. }
  2460. if ( input == null ) {
  2461. return null;
  2462. }
  2463. String dateformatString = NVL( DateFormat, "HH:mm:ss" );
  2464. int t = decodeTime( time, dateformatString );
  2465. Date d = new Date( input.getTime() + t );
  2466. return d;
  2467. }
  2468. // Decodes a time value in specified date format and returns it as milliseconds since midnight.
  2469. public static int decodeTime( String s, String DateFormat ) throws Exception {
  2470. SimpleDateFormat f = new SimpleDateFormat( DateFormat );
  2471. TimeZone utcTimeZone = TimeZone.getTimeZone( "UTC" );
  2472. f.setTimeZone( utcTimeZone );
  2473. f.setLenient( false );
  2474. ParsePosition p = new ParsePosition( 0 );
  2475. Date d = f.parse( s, p );
  2476. if ( d == null ) {
  2477. throw new Exception( "Invalid time value " + DateFormat + ": \"" + s + "\"." );
  2478. }
  2479. return (int) d.getTime();
  2480. }
  2481. /**
  2482. * Get the number of occurances of searchFor in string.
  2483. *
  2484. * @param string
  2485. * String to be searched
  2486. * @param searchFor
  2487. * to be counted string
  2488. * @return number of occurances
  2489. */
  2490. public static int getOccurenceString( String string, String searchFor ) {
  2491. if ( string == null || string.length() == 0 ) {
  2492. return 0;
  2493. }
  2494. int counter = 0;
  2495. int len = searchFor.length();
  2496. if ( len > 0 ) {
  2497. int start = string.indexOf( searchFor );
  2498. while ( start != -1 ) {
  2499. start = string.indexOf( searchFor, start + len );
  2500. }
  2501. }
  2502. return counter;
  2503. }
  2504. public static String[] GetAvailableFontNames() {
  2505. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  2506. Font[] fonts = ge.getAllFonts();
  2507. String[] FontName = new String[fonts.length];
  2508. for ( int i = 0; i < fonts.length; i++ ) {
  2509. FontName[i] = fonts[i].getFontName();
  2510. }
  2511. return FontName;
  2512. }
  2513. public static String getKettlePropertiesFileHeader() {
  2514. StringBuilder out = new StringBuilder();
  2515. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line01", BuildVersion
  2516. .getInstance().getVersion() )
  2517. + CR );
  2518. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line02" ) + CR );
  2519. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line03" ) + CR );
  2520. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line04" ) + CR );
  2521. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line05" ) + CR );
  2522. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line06" ) + CR );
  2523. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line07" ) + CR );
  2524. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line08" ) + CR );
  2525. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line09" ) + CR );
  2526. out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line10" ) + CR );
  2527. return out.toString();
  2528. }
  2529. /**
  2530. * Mask XML content. i.e. protect with CDATA;
  2531. *
  2532. * @param content
  2533. * content
  2534. * @return protected content
  2535. */
  2536. public static String protectXMLCDATA( String content ) {
  2537. if ( isEmpty( content ) ) {
  2538. return content;
  2539. }
  2540. return "<![CDATA[" + content + "]]>";
  2541. }
  2542. /**
  2543. * Get the number of occurances of searchFor in string.
  2544. *
  2545. * @param string
  2546. * String to be searched
  2547. * @param searchFor
  2548. * to be counted string
  2549. * @return number of occurances
  2550. */
  2551. public static int getOcuranceString( String string, String searchFor ) {
  2552. if ( string == null || string.length() == 0 ) {
  2553. return 0;
  2554. }
  2555. Pattern p = Pattern.compile( searchFor );
  2556. Matcher m = p.matcher( string );
  2557. int count = 0;
  2558. while ( m.find() ) {
  2559. ++count;
  2560. }
  2561. return count;
  2562. }
  2563. /**
  2564. * Mask XML content. i.e. replace characters with &values;
  2565. *
  2566. * @param content
  2567. * content
  2568. * @return masked content
  2569. */
  2570. public static String escapeXml( String content ) {
  2571. if ( isEmpty( content ) ) {
  2572. return content;
  2573. }
  2574. return StringEscapeUtils.escapeXml( content );
  2575. }
  2576. public static String Lpad( String valueToPad, String filler, int size ) {
  2577. if ( size == 0 ) {
  2578. return valueToPad;
  2579. }
  2580. while ( valueToPad.length() < size ) {
  2581. valueToPad = filler + valueToPad;
  2582. }
  2583. return valueToPad;
  2584. }
  2585. public static String Rpad( String valueToPad, String filler, int size ) {
  2586. if ( size == 0 ) {
  2587. return valueToPad;
  2588. }
  2589. while ( valueToPad.length() < size ) {
  2590. valueToPad = valueToPad + filler;
  2591. }
  2592. return valueToPad;
  2593. }
  2594. public static boolean classIsOrExtends( Class<?> clazz, Class<?> superClass ) {
  2595. if ( clazz.equals( Object.class ) ) {
  2596. return false;
  2597. }
  2598. if ( clazz.equals( superClass ) ) {
  2599. return true;
  2600. }
  2601. return classIsOrExtends( clazz.getSuperclass(), superClass );
  2602. }
  2603. }