Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 03646974789c4b303dd21c8056ce503bf69b618b (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
103
104
105
106
107
108
/***************************************************************************
 * Copyright (c) 2004-2007 Eike Stepper, Germany.
 * 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.util.tests;

import org.eclipse.net4j.util.io.ExtendedDataInput;
import org.eclipse.net4j.util.io.ExtendedDataOutput;
import org.eclipse.net4j.util.io.IOUtil;
import org.eclipse.net4j.util.io.SortedFileMap;

import java.io.File;
import java.io.IOException;

/**
 * @author Eike Stepper
 */
public class SortedFileMapTest extends AbstractOMTest
{
  public void testMap() throws Exception
  {
    File file = new File("testMap.dat");
    if (file.exists())
    {
      file.delete();
    }

    SortedFileMap<Integer, String> map = null;

    try
    {
      map = new TestMap(file);
      for (int i = 0; i < 500; i++)
      {
        map.put(i, "Value " + i);
      }

      for (int i = 0; i < 500; i++)
      {
        String value = map.get(i);
        System.out.println(value);
      }
    }
    finally
    {
      IOUtil.close(map);
    }
  }

  /**
   * @author Eike Stepper
   */
  public static final class TestMap extends SortedFileMap<Integer, String>
  {
    public TestMap(File file)
    {
      super(file, "rw");
    }

    @Override
    public int getKeySize()
    {
      return 4;
    }

    @Override
    protected Integer readKey(ExtendedDataInput in) throws IOException
    {
      return in.readInt();
    }

    @Override
    protected void writeKey(ExtendedDataOutput out, Integer key) throws IOException
    {
      out.writeInt(key);
    }

    @Override
    public int getValueSize()
    {
      return 20;
    }

    @Override
    protected String readValue(ExtendedDataInput in) throws IOException
    {
      return in.readString();
    }

    @Override
    protected void writeValue(ExtendedDataOutput out, String value) throws IOException
    {
      byte[] bytes = value.getBytes();
      if (bytes.length + 4 > getValueSize())
      {
        throw new IllegalArgumentException("Value size of " + getValueSize() + " exceeded: " + value);
      }

      out.writeByteArray(bytes);
    }
  }
}

Back to the top