summaryrefslogtreecommitdiff
path: root/tools/gnu/classpath/tools/orbd/PersistentMap.java
blob: 6c6164d21f47350e39d2dff71cd3a2f19c854241 (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
/* PersistentMap.java -- The persistent object naming map
 Copyright (C) 2006 Free Software Foundation, Inc.

 This file is part of GNU Classpath.

 GNU Classpath is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2, or (at your option)
 any later version.

 GNU Classpath is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNU Classpath; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 02110-1301 USA.

 Linking this library statically or dynamically with other modules is
 making a combined work based on this library.  Thus, the terms and
 conditions of the GNU General Public License cover the whole
 combination.

 As a special exception, the copyright holders of this library give you
 permission to link this library with independent modules to produce an
 executable, regardless of the license terms of these independent
 modules, and to copy and distribute the resulting executable under
 terms of your choice, provided that you also meet, for each linked
 independent module, the terms and conditions of the license of that
 module.  An independent module is a module which is not derived from
 or based on this library.  If you modify this library, you may extend
 this exception to your version of the library, but you are not
 obligated to do so.  If you do not wish to do so, delete this
 exception statement from your version. */


package gnu.classpath.tools.orbd;

import gnu.CORBA.NamingService.NamingMap;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextPackage.AlreadyBound;
import org.omg.CosNaming.NamingContextPackage.InvalidName;

/**
 * The persistent object naming map for the persistent naming service. The
 * inherited (super.) naming map implementation is transient and is used as a
 * cache. During the normal work, the naming map does not read from the disk,
 * just stores the changes there. Map only reads from the disk when it starts.
 * 
 * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
 */
public class PersistentMap
    extends NamingMap
{
  /**
   * The data entry.
   */
  public static class Entry
  {
    String id;

    String kind;

    String ior;

    /**
     * Get the name component node.
     */
    public NameComponent getComponent()
    {
      return new NameComponent(id, kind);
    }

    /**
     * Write the naming map entry to the output stream.
     */
    public void write(OutputStream out) throws IOException
    {
      // Format: id.kind <eoln> ior <eoln><eoln>
      out.write(getKey(id, kind).getBytes());
      out.write('\n');
      out.write(ior.getBytes());
      out.write('\n');
      out.close();
    }

    /**
     * Read the name component from the input stream
     */
    public boolean read(BufferedReader in) throws IOException
    {
      String key = in.readLine();
      String xior = in.readLine();

      if (key != null && xior != null)
        {
          if (key.length() < 2)
            {
              // A single char key cannot have the kind part.
              id = key;
              kind = "";
            }
          else
            {
              // Search for the id/kind splitter, dot:
              int iks = - 1;
              for (int i = 1; i < key.length(); i++)
                {
                  if (key.charAt(i) == '.')
                    // The id is separated from kind by dot, unless preceeded by
                    // the
                    // escape character, \.
                    if (key.charAt(i - 1) != '\\')
                      {
                        iks = i;
                        break;
                      }
                }

              // May also end by dot, if the kind field is missing.
              if (iks < 0)
                {
                  id = key;
                  kind = "";
                }
              else if (iks == key.length() - 1)
                {
                  id = key.substring(0, key.length() - 1);
                  kind = "";
                }
              else
                {
                  id = key.substring(0, iks);
                  kind = key.substring(iks + 1);
                }
            }
          ior = xior;
          return true;
        }
      else
        return false;
    }

    /**
     * Get the key value from the name component.
     * 
     * @param id the component id
     * @param kind the component kind
     * @return the key value
     */
    public String getKey(String id, String kind)
    {
      StringBuffer b = new StringBuffer(id.length() + 8);
      appEscaping(b, id);
      b.append('.');
      if (kind != null && kind.length() > 0)
        appEscaping(b, kind);
      return b.toString();
    }

    /**
     * Append the contents of the string to this string buffer, inserting the
     * escape sequences, where required.
     * 
     * @param b a buffer to append the contents to.
     * @param s a string to append.
     */
    void appEscaping(StringBuffer b, String s)
    {
      char c;
      for (int i = 0; i < s.length(); i++)
        {
          c = s.charAt(i);
          switch (c)
            {
            case '.':
            case '/':
            case '\\':
              b.append('\\');
              b.append(c);
              break;

            default:
              b.append(c);
              break;
            }
        }
    }
  }

  /**
   * The file, where the persistent naming map stores the information. The
   * format of this file is n*(id LF kind LF ior LFLF).
   */
  public final File file;

  /**
   * The naming service ORB, used to obtain and produce the object stringified
   * references.
   */
  ORB orb;
  
  /**
   * If true, all existing data on the file system are discarded.
   */
  boolean reset;

  /**
   * Create the persistent map that stores information in the given file.
   * 
   * @param an_orb the naming service ORB, used to obtain and produce the object
   *          stringified references.
   * @param mapFile the file, where the persistent information is stored.
   * @param a_reset if true, the previous naming data are discarded. If false
   *          (normally expected), they are loaded from the persistent memory to
   *          provide the persistence.
   */
  public PersistentMap(ORB an_orb, File mapFile, boolean a_reset)
  {
    super();
    orb = an_orb;
    file = mapFile;
    reset = a_reset;

    // Initialise the persistent map with existing data.
    if (file.exists() && ! reset)
      {

        BufferedReader in;
        try
          {
            FileInputStream fin = new FileInputStream(file);
            in = new BufferedReader(new InputStreamReader(fin));
            Entry e = new Entry();
            boolean ok;

            while (e.read(in))
              {
                org.omg.CORBA .Object object = string_to_object(e.ior);
                orb.connect(object);
                map.put(e.getComponent(), object);
              }
          }
        catch (Exception ex)
          {
            InternalError ierr = new InternalError(file.getAbsolutePath());
            ierr.initCause(ex);
            throw ierr;
          }
      }
  }
  
  /**
   * Restore object from its string description.
   * 
   * @param description the string, describing the object
   * 
   * @return the object.
   */
  protected org.omg.CORBA.Object string_to_object(String description)
  {
    return orb.string_to_object(description);
  }
  
  /**
   * Convert the object to its string description
   * 
   * @param object the object to convert
   * @return the string description of the object
   */
  protected String object_to_string(org.omg.CORBA .Object object)
  {
      return orb.object_to_string(object);    
  }

  /**
   * Put the given GIOP object, specifying the given name as a key. If the entry
   * with the given name already exists, or if the given object is already
   * mapped under another name, the {@link AlreadyBound} exception will be
   * thrown.
   * 
   * @param name the name
   * @param object the object
   */
  public void bind(NameComponent name, org.omg.CORBA.Object object)
      throws AlreadyBound, InvalidName
  {
    if (!containsKey(name))
      {
        super.bind(name, object);
        register(name, object);
      }
    else
      throw new AlreadyBound(name.id + "." + name.kind);
  }

  /**
   * Put the given CORBA object, specifying the given name as a key. Remove all
   * pre - existing mappings for the given name and object.
   * 
   * @param name the name.
   * @param object the object
   */
  public void rebind(NameComponent name, org.omg.CORBA.Object object)
      throws InvalidName
  {
    if (containsKey(name))
      {
        org.omg.CORBA.Object existing = get(name);
        String ior = object_to_string(object);
        String xior = object_to_string(existing);
        
        // Same name and same ior - nothing to do.
        if (ior.equals(xior))
          return;
        else
          remove(name);
      }

    Iterator iter = entries().iterator();
    Map.Entry item;

    // Remove the existing mapping for the given object, if present.
    while (iter.hasNext())
      {
        item = (Map.Entry) iter.next();
        if (item.getValue().equals(object))
          iter.remove();
      }

    map.put(name, object);
    register(name, object);
  }

  /**
   * Removes the given name, if present.
   * 
   * @param name a name to remove.
   */
  public void remove(NameComponent name)
  {
    super.remove(name);
    unregister(name);
  }

  /**
   * Register this name - object pair in the persistent storage.
   * 
   * @param name the name.
   * @param object the object
   */
  public void register(NameComponent name, org.omg.CORBA.Object object)
  {
    // If this key is already known, and this is the same object,
    // then return without action.
    String ior = object_to_string(object);

    synchronized (file)
      {
        try
          {
            FileOutputStream fou;

            if (! file.exists())
              fou = new FileOutputStream(file);
            else
              fou = new FileOutputStream(file, true);

            Entry e = new Entry();
            e.id = name.id;
            e.kind = name.kind;
            e.ior = ior;
            e.write(fou);
            fou.close();
          }
        catch (Exception e)
          {
            InternalError ierr = new InternalError(file.getAbsolutePath());
            ierr.initCause(e);
            throw ierr;
          }
      }
  }

  /**
   * Remove this name from the persistent storage.
   * 
   * @param name the name to remove
   */
  public void unregister(NameComponent name)
  {
    synchronized (file)
      {
        try
          {
            File nf = new File(file.getParent(), file.getName() + "_t");
            FileInputStream fin = new FileInputStream(file);
            FileOutputStream fou = new FileOutputStream(nf);
            BufferedOutputStream ou = new BufferedOutputStream(fou);

            BufferedReader in = new BufferedReader(new InputStreamReader(fin));
            String s;
            String nk = name.kind;
            if (nk == null)
              nk = "";

            Entry e = new Entry();

            while (e.read(in))
              {
                if (e.id.equals(name.id) && e.kind.equals(nk))
                  {
                    // Do nothing - skip.
                  }
                else
                  {
                    e.write(ou);
                  }
              }

            File deleteIt = new File(file.getParent(), file.getName() + "_d");
            if (deleteIt.exists())
              deleteIt.delete();

            if (! file.renameTo(deleteIt))
              throw new IOException(file.getAbsolutePath() + " rename failed");

            if (! nf.renameTo(file))
              throw new IOException(file.getAbsolutePath() + " rename failed");
          }
        catch (Exception e)
          {
            InternalError ierr = new InternalError(file.getAbsolutePath());
            ierr.initCause(e);
            throw ierr;
          }
      }
  }
}