Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: de81202291d8e308e37a0919364649c247961a35 (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
/*
 * Copyright (c) 2004-2014 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.util.container;

import org.eclipse.net4j.util.container.IContainer.Persistence;
import org.eclipse.net4j.util.io.IORuntimeException;
import org.eclipse.net4j.util.io.IOUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Collection;

/**
 * @author Eike Stepper
 * @since 3.5
 */
public abstract class ContainerPersistence<E> implements Persistence<E>
{
  public Collection<E> loadElements() throws IORuntimeException
  {
    InputStream out = null;

    try
    {
      out = openInputStream();
      ObjectInputStream oos = new ObjectInputStream(new BufferedInputStream(out));

      @SuppressWarnings("unchecked")
      Collection<E> elements = (Collection<E>)oos.readObject();
      return elements;
    }
    catch (IOException ex)
    {
      throw new IORuntimeException(ex);
    }
    catch (ClassNotFoundException ex)
    {
      throw new IORuntimeException(ex);
    }
    finally
    {
      IOUtil.closeSilent(out);
    }
  }

  public void saveElements(Collection<E> elements) throws IORuntimeException
  {
    OutputStream out = null;

    try
    {
      out = openOutputStream();

      ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(out));
      oos.writeObject(elements);
      oos.flush();
    }
    catch (IOException ex)
    {
      throw new IORuntimeException(ex);
    }
    finally
    {
      IOUtil.closeSilent(out);
    }
  }

  protected abstract InputStream openInputStream() throws IOException;

  protected abstract OutputStream openOutputStream() throws IOException;
}

Back to the top