aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/plugin/provisioning/ProvisioningServiceImpl.java
blob: b545d761481fc5cd75eb88328d20878f87fd76f4 (plain)
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.plugin.provisioning;

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import java.util.regex.*;

import javax.swing.*;

import net.java.sip.communicator.service.httputil.*;
import net.java.sip.communicator.service.provisioning.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.Logger;
import net.java.sip.communicator.plugin.desktoputil.*;

import org.apache.http.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.resources.*;
import org.jitsi.util.*;
import org.osgi.framework.*;
// disambiguation

/**
 * Provisioning service.
 *
 * @author Sebastien Vincent
 */
public class ProvisioningServiceImpl
    implements ProvisioningService
{
    /**
     * Logger of this class
     */
    private static final Logger logger
        = Logger.getLogger(ProvisioningServiceImpl.class);

    /**
     * Name of the UUID property.
     */
    public static final String PROVISIONING_UUID_PROP
        = "net.java.sip.communicator.UUID";

    /**
     * Name of the provisioning URL in the configuration service.
     */
    private static final String PROPERTY_PROVISIONING_URL
        = "net.java.sip.communicator.plugin.provisioning.URL";

    /**
     * Name of the provisioning username in the configuration service
     * authentication).
     */
    static final String PROPERTY_PROVISIONING_USERNAME
        = "net.java.sip.communicator.plugin.provisioning.auth.USERNAME";

    /**
     * Name of the provisioning password in the configuration service (HTTP
     * authentication).
     */
    static final String PROPERTY_PROVISIONING_PASSWORD
        = "net.java.sip.communicator.plugin.provisioning.auth";

    /**
     * Name of the property that contains the provisioning method (i.e. DHCP,
     * DNS, manual, ...).
     */
    private static final String PROVISIONING_METHOD_PROP
        = "net.java.sip.communicator.plugin.provisioning.METHOD";

    /**
     * Name of the property, whether provisioning is mandatory.
     */
    private static final String PROPERTY_PROVISIONING_MANDATORY
        = "net.java.sip.communicator.plugin.provisioning.MANDATORY";

    /**
     * Name of the property that contains enforce prefix list (separated by
     * pipe) for the provisioning. The retrieved configuration properties will
     * be checked against these prefixes to avoid having incorrect content in
     * the configuration file (such as HTML content resulting of HTTP error).
     */
    private static final String PROVISIONING_ALLOW_PREFIX_PROP
        = "provisioning.ALLOW_PREFIX";

    /**
     * Name of the enforce prefix property.
     */
    private static final String PROVISIONING_ENFORCE_PREFIX_PROP
        = "provisioning.ENFORCE_PREFIX";


    /**
     * List of allowed configuration prefixes.
     */
    private List<String> allowedPrefixes = new ArrayList<String>();

    /**
     * Authentication username.
     */
    private static String provUsername = null;

    /**
     * Authentication password.
     */
    private static String provPassword = null;

    /**
     * Prefix that can be used to indicate a property that will be
     * set as a system property.
     */
    private static final String SYSTEM_PROP_PREFIX = "${system}.";

     /**
      * Constructor.
      */
     public ProvisioningServiceImpl()
     {
         // check if UUID is already configured
         String uuid = (String)ProvisioningActivator.getConfigurationService().
             getProperty(PROVISIONING_UUID_PROP);

         if(uuid == null || uuid.equals(""))
         {
             uuid = UUID.randomUUID().toString();
             ProvisioningActivator.getConfigurationService().setProperty(
                 PROVISIONING_UUID_PROP, uuid);
         }

     }

     /**
      * Starts provisioning.
      *
      * @param url provisioning URL
      */
     void start(String url)
     {
         if(url == null)
         {
             /* try to see if provisioning URL is stored in properties */
             url = getProvisioningUri();
         }

         if(!StringUtils.isNullOrEmpty(url))
         {
             InputStream data = retrieveConfigurationFile(url);

             if(data != null)
             {
                 /* store the provisioning URL in local configuration in case
                  * the provisioning discovery failed (DHCP/DNS unavailable, ...)
                  */
                 ProvisioningActivator.getConfigurationService().setProperty(
                         PROPERTY_PROVISIONING_URL, url);

                 updateConfiguration(data);
             }
         }
     }

     /**
      * Indicates if the provisioning has been enabled.
      *
      * @return <tt>true</tt> if the provisioning is enabled, <tt>false</tt> -
      * otherwise
      */
     public String getProvisioningMethod()
     {
         String provMethod
             = ProvisioningActivator.getConfigurationService().getString(
                 PROVISIONING_METHOD_PROP);

         if (provMethod == null || provMethod.length() <= 0)
         {
             provMethod = ProvisioningActivator.getResourceService().
                 getSettingsString(
                     "plugin.provisioning.DEFAULT_PROVISIONING_METHOD");

             if (provMethod != null && provMethod.length() > 0)
                 setProvisioningMethod(provMethod);
         }

         return provMethod;
     }

     /**
      * Enables the provisioning with the given method. If the provisioningMethod
      * is null disables the provisioning.
      *
      * @param provisioningMethod the provisioning method
      */
     public void setProvisioningMethod(String provisioningMethod)
     {
         ProvisioningActivator.getConfigurationService().setProperty(
             PROVISIONING_METHOD_PROP, provisioningMethod);
     }

     /**
      * Returns the provisioning URI.
      *
      * @return the provisioning URI
      */
     public String getProvisioningUri()
     {
         String provUri
             = ProvisioningActivator.getConfigurationService().getString(
                 PROPERTY_PROVISIONING_URL);

         if (provUri == null || provUri.length() <= 0)
         {
             provUri = ProvisioningActivator.getResourceService().
                 getSettingsString(
                     "plugin.provisioning.DEFAULT_PROVISIONING_URI");

             if (provUri != null && provUri.length() > 0)
                 setProvisioningUri(provUri);
         }
         return provUri;
     }

     /**
      * Sets the provisioning URI.
      *
      * @param uri the provisioning URI to set
      */
     public void setProvisioningUri(String uri)
     {
         ProvisioningActivator.getConfigurationService().setProperty(
             PROPERTY_PROVISIONING_URL, uri);
     }

    /**
     * Returns provisioning username.
     *
     * @return provisioning username
     */
    public String getProvisioningUsername()
    {
        return provUsername;
    }

    /**
     * Returns provisioning password.
     *
     * @return provisioning password
     */
    public String getProvisioningPassword()
    {
        return provPassword;
    }

    /**
     * Retrieve configuration file from provisioning URL.
     * This method is blocking until configuration file is retrieved from the
     * network or if an exception happen
     *
     * @param url provisioning URL
     * @return Stream of provisioning data
     */
    private InputStream retrieveConfigurationFile(String url)
    {
        return retrieveConfigurationFile(url, null);
    }

    /**
     * Retrieve configuration file from provisioning URL.
     * This method is blocking until configuration file is retrieved from the
     * network or if an exception happen
     *
     * @param url provisioning URL
     * @param parameters the already filled parameters if any.
     * @return Stream of provisioning data
     */
    private InputStream retrieveConfigurationFile(String url,
                                           List<NameValuePair> parameters)
    {
        try
        {
            String arg = null;
            String args[] = null;

            URL u = new URL(url);
            InetAddress ipaddr =
                ProvisioningActivator.getNetworkAddressManagerService().
                    getLocalHost(InetAddress.getByName(u.getHost()));

            // Get any system environment identified by ${env.xyz}
            Pattern p = Pattern.compile("\\$\\{env\\.([^\\}]*)\\}");
            Matcher m = p.matcher(url);
            StringBuffer sb = new StringBuffer();
            while(m.find())
            {
                String value = System.getenv(m.group(1));
                if(value != null)
                {
                    m.appendReplacement(sb, Matcher.quoteReplacement(value));
                }
            }
            m.appendTail(sb);
            url = sb.toString();

            // Get any system property variable identified by ${system.xyz}
            p = Pattern.compile("\\$\\{system\\.([^\\}]*)\\}");
            m = p.matcher(url);
            sb = new StringBuffer();
            while(m.find())
            {
                String value = System.getProperty(m.group(1));
                if(value != null)
                {
                    m.appendReplacement(sb, Matcher.quoteReplacement(value));
                }
            }
            m.appendTail(sb);
            url = sb.toString();

            if(url.indexOf("${home.location}") != -1)
            {
                url = url.replace("${home.location}",
                    ProvisioningActivator.getConfigurationService()
                        .getScHomeDirLocation());
            }

            if(url.indexOf("${home.name}") != -1)
            {
                url = url.replace("${home.name}",
                    ProvisioningActivator.getConfigurationService()
                        .getScHomeDirName());
            }

            if(url.indexOf("${uuid}") != -1)
            {
                url = url.replace("${uuid}",
                    (String)ProvisioningActivator.getConfigurationService()
                        .getProperty(PROVISIONING_UUID_PROP));
            }

            if(url.indexOf("${osname}") != -1)
            {
                url = url.replace("${osname}", System.getProperty("os.name"));
            }

            if(url.indexOf("${arch}") != -1)
            {
                url = url.replace("${arch}", System.getProperty("os.arch"));
            }

            if(url.indexOf("${resx}") != -1 || url.indexOf("${resy}") != -1)
            {
                Rectangle screen = ScreenInformation.getScreenBounds();

                if(url.indexOf("${resx}") != -1)
                {
                    url = url.replace("${resx}", String.valueOf(screen.width));
                }

                if(url.indexOf("${resy}") != -1)
                {
                    url = url.replace("${resy}", String.valueOf(screen.height));
                }
            }

            if(url.indexOf("${build}") != -1)
            {
                url = url.replace("${build}",
                        System.getProperty("sip-communicator.version"));
            }

            if(url.indexOf("${locale}") != -1)
            {
                String locale =
                    ProvisioningActivator.getConfigurationService().getString(
                        ResourceManagementService.DEFAULT_LOCALE_CONFIG);
                if(locale == null)
                    locale = "";

                url = url.replace("${locale}", locale);
            }

            if(url.indexOf("${ipaddr}") != -1)
            {
                url = url.replace("${ipaddr}", ipaddr.getHostAddress());
            }

            if(url.indexOf("${hostname}") != -1)
            {
                String name;
                if(OSUtils.IS_WINDOWS)
                {
                    // avoid reverse DNS lookup
                    name = System.getenv("COMPUTERNAME");
                }
                else
                {
                    name = ipaddr.getHostName();
                }
                url = url.replace("${hostname}", name);
            }

            if(url.indexOf("${hwaddr}") != -1)
            {
                if(ipaddr != null)
                {
                    /* find the hardware address of the interface
                     * that has this IP address
                     */
                    Enumeration<NetworkInterface> en =
                        NetworkInterface.getNetworkInterfaces();

                    while(en.hasMoreElements())
                    {
                        NetworkInterface iface = en.nextElement();

                        Enumeration<InetAddress> enInet =
                            iface.getInetAddresses();

                        while(enInet.hasMoreElements())
                        {
                            InetAddress inet = enInet.nextElement();

                            if(inet.equals(ipaddr))
                            {
                                byte hw[] =
                                    ProvisioningActivator.
                                        getNetworkAddressManagerService().
                                            getHardwareAddress(iface);

                                if(hw == null)
                                    continue;

                                StringBuffer buf =
                                    new StringBuffer();

                                for(byte h : hw)
                                {
                                    int hi = h >= 0 ? h : h + 256;
                                    String t = new String(
                                            (hi <= 0xf) ? "0" : "");
                                    t += Integer.toHexString(hi);
                                    buf.append(t);
                                    buf.append(":");
                                }

                                buf.deleteCharAt(buf.length() - 1);

                                url = url.replace("${hwaddr}",
                                        buf.toString());

                                break;
                            }
                        }
                    }
                }
            }

            if(url.contains("?"))
            {
                /* do not handle URL of type http://domain/index.php? (no
                 * parameters)
                 */
                if((url.indexOf('?') + 1) != url.length())
                {
                    arg = url.substring(url.indexOf('?') + 1);
                    args = arg.split("&");
                }
                url = url.substring(0, url.indexOf('?'));
            }

            ArrayList<String> paramNames = null;
            ArrayList<String> paramValues = null;
            int usernameIx = -1;
            int passwordIx = -1;

            if(args != null && args.length > 0)
            {
                paramNames = new ArrayList<String>(args.length);
                paramValues = new ArrayList<String>(args.length);

                String usernameParam = "${username}";
                String passwordParam = "${password}";

                for(int i = 0; i < args.length; i++)
                {
                    String s = args[i];

                    int equalsIndex = s.indexOf("=");
                    String currentParamName = null;

                    if (equalsIndex > -1)
                    {
                        currentParamName = s.substring(0, equalsIndex);
                    }

                    // pre loaded value we will reuse.
                    String preloadedParamValue =
                        getParamValue(parameters, currentParamName);

                    // If we find the username or password parameter at this
                    // stage we replace it with an empty string.
                    // or if we have an already filled value we will reuse it.
                    if(s.indexOf(usernameParam) != -1)
                    {
                        if(preloadedParamValue != null)
                        {
                            s = s.replace(usernameParam, preloadedParamValue);
                        }
                        else
                            s = s.replace(usernameParam, "");
                        usernameIx = paramNames.size();
                    }
                    else if(s.indexOf(passwordParam) != -1)
                    {
                        if(preloadedParamValue != null)
                        {
                            s = s.replace(passwordParam, preloadedParamValue);
                        }
                        else
                            s = s.replace(passwordParam, "");
                        passwordIx = paramNames.size();
                    }

                    if (equalsIndex > -1)
                    {
                        paramNames.add(currentParamName);
                        paramValues.add(s.substring(equalsIndex + 1));
                    }
                    else
                    {
                        if(logger.isInfoEnabled())
                        {
                            logger.info(
                                    "Invalid provisioning request parameter: \""
                                    + s + "\", is replaced by \"" + s + "=\"");
                        }
                        paramNames.add(s);
                        paramValues.add("");
                    }
                }
            }

            HttpUtils.HTTPResponseResult res = null;
            Throwable errorWhileProvisioning = null;
            try
            {
                res =
                    HttpUtils.postForm(
                        url,
                        PROPERTY_PROVISIONING_USERNAME,
                        PROPERTY_PROVISIONING_PASSWORD,
                        paramNames,
                        paramValues,
                        usernameIx,
                        passwordIx,
                        new HttpUtils.RedirectHandler()
                        {
                            @Override
                            public boolean handleRedirect(
                                String location,
                                List<NameValuePair> parameters)
                            {
                                if(!hasParams(location))
                                    return false;

                                // if we have parameters proceed
                                retrieveConfigurationFile(location, parameters);

                                return true;
                            }

                            @Override
                            public boolean hasParams(String location)
                            {
                                return location.contains("${");
                            }
                        });
            }
            catch(Throwable t)
            {
                logger.error("Error posting form", t);
                errorWhileProvisioning = t;
            }

            // if there was an error in retrieving stop
            if(res == null)
            {
                // if canceled, lets check whether provisioning is
                // mandatory
                if(ProvisioningActivator.getConfigurationService().getBoolean(
                    PROPERTY_PROVISIONING_MANDATORY, false))
                {
                    String errorMsg;
                    if(errorWhileProvisioning != null)
                        errorMsg = errorWhileProvisioning.getLocalizedMessage();
                    else
                        errorMsg = "";

                    ErrorDialog ed = new ErrorDialog(
                        null,
                        ProvisioningActivator.getResourceService()
                            .getI18NString("plugin.provisioning.PROV_FAILED"),
                        ProvisioningActivator.getResourceService()
                            .getI18NString("plugin.provisioning.PROV_FAILED_MSG",
                                            new String[]{errorMsg}),
                        errorWhileProvisioning);
                    ed.setModal(true);
                    ed.showDialog();

                    // as shutdown service is not started and other bundles
                    // are scheduled to start, stop all of them
                    {
                        for(Bundle b : ProvisioningActivator.bundleContext
                                            .getBundles())
                        {
                            try
                            {
                                // skip our Bundle avoiding stopping us while
                                // starting and NPE in felix
                                if(ProvisioningActivator.bundleContext
                                    .equals(b.getBundleContext()))
                                {
                                    continue;
                                }
                                b.stop();
                            }
                            catch (BundleException ex)
                            {
                                logger.error(
                                    "Failed to being gentle stop " +
                                        b.getLocation(), ex);
                            }
                        }
                    }
                }

                // stop processing
                return null;
            }

            String userPass[] = res.getCredentials();
            if(userPass[0] != null && userPass[1] != null)
            {
                provUsername = userPass[0];
                provPassword = userPass[1];
            }

            InputStream in = res.getContent();

            // Skips ProgressMonitorInputStream wrapper on Android
            if(!OSUtils.IS_ANDROID)
            {
                // Chain a ProgressMonitorInputStream to the
                // URLConnection's InputStream
                final ProgressMonitorInputStream pin;
                pin = new ProgressMonitorInputStream(null, u.toString(), in);

                // Set the maximum value of the ProgressMonitor
                ProgressMonitor pm = pin.getProgressMonitor();
                pm.setMaximum((int)res.getContentLength());

                // Uses ProgressMonitorInputStream if available
                return pin;
            }

            return in;
        }
        catch (Exception e)
        {
            if (logger.isInfoEnabled())
                logger.info("Error retrieving provisioning file!", e);
            return null;
        }
    }

    /**
     * Search param value for the supplied name.
     * @param parameters the parameters can be null.
     * @param paramName the name to search.
     * @return the corresponding parameter value.
     */
    private static String getParamValue(List<NameValuePair> parameters,
                                        String paramName)
    {
        if(parameters == null || paramName == null)
            return null;

        for(NameValuePair nv : parameters)
        {
            if(nv.getName().equals(paramName))
                return nv.getValue();
        }

        return null;
    }

    /**
     * Update configuration with properties retrieved from provisioning URL.
     *
     * @param data Provisioning data
     */
    private void updateConfiguration(final InputStream data)
    {
        Properties fileProps = new OrderedProperties();
        InputStream in = null;

        try
        {
            in = new BufferedInputStream(data);
            fileProps.load(in);

            Iterator<Map.Entry<Object, Object> > it
                = fileProps.entrySet().iterator();

            while(it.hasNext())
            {
                Map.Entry<Object, Object> entry = it.next();
                String key = (String)entry.getKey();
                Object value = entry.getValue();

                // skip empty keys, prevent them going into the configuration
                if(key.trim().length() == 0)
                    continue;

                if(key.equals(PROVISIONING_ALLOW_PREFIX_PROP))
                {
                    String prefixes[] = ((String)value).split("\\|");

                    /* updates allowed prefixes list */
                    for(String s : prefixes)
                    {
                        allowedPrefixes.add(s);
                    }
                    continue;
                }
                else if(key.equals(PROVISIONING_ENFORCE_PREFIX_PROP))
                {
                    checkEnforcePrefix((String)value);
                    continue;
                }

                /* check that properties is allowed */
                if(!isPrefixAllowed(key))
                {
                    continue;
                }

                processProperty(key, value);
            }

            try
            {
                /* save and reload the "new" configuration */
                ProvisioningActivator.getConfigurationService().
                    storeConfiguration();
                ProvisioningActivator.getConfigurationService().
                    reloadConfiguration();
            }
            catch(Exception e)
            {
                logger.error("Cannot reload configuration");
            }
        }
        catch(IOException e)
        {
            logger.warn("Error during load of provisioning file");
        }
        finally
        {
            try
            {
                in.close();
            }
            catch(IOException e)
            {
            }
        }
    }

    /**
     * Check if a property name belongs to the allowed prefixes.
     *
     * @param key property key name
     * @return true if key is allowed, false otherwise
     */
    private boolean isPrefixAllowed(String key)
    {
        if(allowedPrefixes.size() > 0)
        {
            for(String s : allowedPrefixes)
            {
                if(key.startsWith(s))
                {
                    return true;
                }
            }

            /* current property prefix is not allowed */
            return false;
        }
        else
        {
            /* no allowed prefixes configured so key is valid by default */
            return true;
        }
    }

    /**
     * Process a new property. If value equals "${null}", it means to remove the
     * property in the configuration service. If the key name end with
     * "PASSWORD", its value is encrypted through credentials storage service,
     * otherwise the property is added/updated in the configuration service.
     *
     * @param key property key name
     * @param value property value
     */
    private void processProperty(String key, Object value)
    {
        if((value instanceof String) && value.equals("${null}"))
        {
            ProvisioningActivator.getConfigurationService().removeProperty(key);
        }
        else if(key.endsWith(".PASSWORD"))
        {
            /* password => credentials storage service */
            ProvisioningActivator.getCredentialsStorageService().storePassword(
                    key.substring(0, key.lastIndexOf(".")),
                    (String)value);

            if(logger.isInfoEnabled())
                logger.info(key +"=<password hidden>");

            return;
        }
        else if(key.startsWith(SYSTEM_PROP_PREFIX))
        {
            String sysKey = key.substring(
                SYSTEM_PROP_PREFIX.length(), key.length());

            System.setProperty(sysKey, (String)value);
        }
        else
        {
            ProvisioningActivator.getConfigurationService().setProperty(key,
                value);
        }

        if(logger.isInfoEnabled())
            logger.info(key + "=" + value);
    }

    /**
     * Walk through all properties and make sure all properties keys match
     * a specific set of prefixes defined in configuration.
     *
     * @param enforcePrefix list of enforce prefix.
     */
    private void checkEnforcePrefix(String enforcePrefix)
    {
        ConfigurationService config =
            ProvisioningActivator.getConfigurationService();
        String prefixes[] = null;

        if(enforcePrefix == null)
        {
            return;
        }

        /* must escape the | character */
        prefixes = enforcePrefix.split("\\|");

        /* get all properties */
        for (String key : config.getAllPropertyNames())
        {
            boolean isValid = false;

            for(String k : prefixes)
            {
                if(key.startsWith(k))
                {
                    isValid = true;
                    break;
                }
            }

            /* property name does is not in the enforce prefix list
             * so remove it
             */
            if(!isValid)
            {
                config.removeProperty(key);
            }
        }
    }
}