Skip to main content
summaryrefslogtreecommitdiffstats
blob: c897ac70c3798c28c0465d6ed81a0ffc03833cc7 (plain) (blame)
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
/*
 * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.internal.util.om.pref;

import org.eclipse.net4j.internal.util.bundle.OM;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * @author Eike Stepper
 */
public final class ArrayPreference extends Preference<String[]>
{
  private static final String SEPARATOR = ","; //$NON-NLS-1$

  private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$

  public ArrayPreference(Preferences preferences, String name, String[] defaultValue)
  {
    super(preferences, name, defaultValue);
  }

  @Override
  protected String getString()
  {
    String[] array = getValue();
    if (array == null || array.length == 0)
    {
      return null;
    }

    StringBuilder builder = new StringBuilder();
    for (String element : array)
    {
      if (builder.length() != 0)
      {
        builder.append(SEPARATOR);
        builder.append(" "); //$NON-NLS-1$
      }

      try
      {
        String encoded = URLEncoder.encode(element, UTF_8);
        builder.append(encoded);
      }
      catch (UnsupportedEncodingException ex)
      {
        OM.LOG.error(ex);
        return null;
      }
    }

    return builder.toString();
  }

  @Override
  protected String[] convert(String value)
  {
    String[] array = value.split(SEPARATOR);
    if (array == null || array.length == 0)
    {
      return Preferences.DEFAULT_ARRAY;
    }

    for (int i = 0; i < array.length; i++)
    {
      try
      {
        array[i] = URLDecoder.decode(array[i].trim(), UTF_8);
      }
      catch (UnsupportedEncodingException ex)
      {
        OM.LOG.error(ex);
        return null;
      }
    }

    return array;
  }

  public Type getType()
  {
    return Type.ARRAY;
  }

  @Override
  public String toString()
  {
    return getName() + " = " + Arrays.asList(getValue());
  }
}

Back to the top