1 package fr.ifremer.quadrige2.magicdraw.helper;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.Properties;
32
33 import javax.swing.JOptionPane;
34
35 import com.nomagic.magicdraw.ui.dialogs.MDDialogParentProvider;
36
37 public class PropertiesHelper {
38
39
40 protected PropertiesHelper() {
41
42 }
43
44 public static Properties loadProperties(String propertyFile, ClassLoader classLoader) {
45 if (propertyFile == null) {
46 throw new IllegalArgumentException("argument 'propertyFile' could not be null or empty");
47 }
48 Properties properties = new Properties();
49 InputStream is = null;
50 try {
51 if (new File(propertyFile).exists()) {
52 is = new FileInputStream(new File(propertyFile));
53 } else {
54 is = classLoader.getResourceAsStream(propertyFile);
55 }
56 if (is == null) {
57 JOptionPane.showMessageDialog(MDDialogParentProvider.getProvider().getDialogParent(), "Could not load properties file '"
58 + propertyFile + "' in the plugin classloader. Please check 'plugin.xml' file validity");
59 return null;
60 }
61
62 properties.load(is);
63 } catch (IOException e) {
64 JOptionPane.showMessageDialog(MDDialogParentProvider.getProvider().getDialogParent(),
65 "Error while loadinf the properties file '" + propertyFile);
66 return null;
67 } finally {
68 if (is != null) {
69 try {
70 is.close();
71 } catch (IOException ex) {
72
73 }
74 }
75 }
76 return properties;
77 }
78
79
80 public static String getProperty(Properties properties, String key) {
81 String result = properties.getProperty(key);
82 if (result == null || result.trim().length() == 0) {
83 throw new IllegalArgumentException(String.format(
84 "Mandatory property [%s] not found in properties file. Could not enable [Teamwork redirection port] action",
85 key));
86 }
87 return result;
88 }
89 public static int getPropertyAsInt(Properties properties, String key) {
90 String value = properties.getProperty(key);
91 if (value == null || value.trim().length() == 0) {
92 throw new IllegalArgumentException(String.format(
93 "Mandatory property [%s] not found in properties file. Could not enable [Teamwork redirection port] action",
94 key));
95 }
96 int result;
97 try {
98 result = Integer.parseInt(value);
99
100 } catch(NumberFormatException e) {
101 result = -1;
102 }
103 if (result < 0) {
104 throw new IllegalArgumentException(String.format(
105 "Bad property format [%s]: should be a positive integer. Could not enable [Teamwork redirection port] action",
106 key));
107 }
108 return result;
109 }
110 }