add AddPeer command
[jSite2.git] / src / net / pterodactylus / util / fcp / FcpUtils.java
1 /**
2  * © 2008 INA Service GmbH
3  */
4 package net.pterodactylus.util.fcp;
5
6 import java.util.StringTokenizer;
7 import java.util.concurrent.atomic.AtomicLong;
8
9 /**
10  * Helper class with utility methods for the FCP protocol.
11  * 
12  * @author <a href="mailto:dr@ina-germany.de">David Roden</a>
13  * @version $Id$
14  */
15 public class FcpUtils {
16
17         /** Counter for unique identifiers. */
18         private static AtomicLong counter = new AtomicLong();
19
20         /**
21          * Returns a unique identifier.
22          * 
23          * @return A unique identifier
24          */
25         public static String getUniqueIdentifier() {
26                 return new StringBuilder().append(System.currentTimeMillis()).append('-').append(counter.getAndIncrement()).toString();
27         }
28
29         /**
30          * Parses an integer field, separated by ‘;’ and returns the parsed values.
31          * 
32          * @param field
33          *            The field to parse
34          * @return An array with the parsed values
35          * @throws NumberFormatException
36          *             if a value can not be converted to a number
37          */
38         public static int[] decodeMultiIntegerField(String field) throws NumberFormatException {
39                 StringTokenizer fieldTokens = new StringTokenizer(field, ";");
40                 int[] result = new int[fieldTokens.countTokens()];
41                 int counter = 0;
42                 while (fieldTokens.hasMoreTokens()) {
43                         String fieldToken = fieldTokens.nextToken();
44                         result[counter++] = Integer.valueOf(fieldToken);
45                 }
46                 return result;
47         }
48
49         /**
50          * Encodes the given integer array into a string, separating the values by
51          * ‘;’.
52          * 
53          * @param values
54          *            The values to encode
55          * @return The encoded values
56          */
57         public static String encodeMultiIntegerField(int[] values) {
58                 StringBuilder encodedField = new StringBuilder();
59                 for (int value: values) {
60                         if (encodedField.length() > 0) {
61                                 encodedField.append(';');
62                         }
63                         encodedField.append(value);
64                 }
65                 return encodedField.toString();
66         }
67
68 }