Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 38b79352c511e8a9842196db9009d830b180714e (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
/***************************************************************************
 * Copyright (c) 2004 - 2008 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.ui.dnd;

import org.eclipse.net4j.util.internal.ui.bundle.OM;
import org.eclipse.net4j.util.io.ExtendedDataInputStream;
import org.eclipse.net4j.util.io.ExtendedDataOutputStream;

import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Eike Stepper
 */
public abstract class DNDTransfer<TYPE> extends ByteArrayTransfer
{
  private String typeName;

  private int typeID;

  protected DNDTransfer(String typeName)
  {
    this.typeName = typeName;
    typeID = registerType(typeName);
  }

  @Override
  protected int[] getTypeIds()
  {
    return new int[] { typeID };
  }

  @Override
  protected String[] getTypeNames()
  {
    return new String[] { typeName };
  }

  @Override
  protected void javaToNative(Object object, TransferData transferData)
  {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ExtendedDataOutputStream out = new ExtendedDataOutputStream(baos);
    byte[] bytes = null;

    try
    {
      writeObject(out, ((TYPE)object));
      out.close();
      bytes = baos.toByteArray();
    }
    catch (Exception ex)
    {
      OM.LOG.error(ex);
    }

    if (bytes != null)
    {
      super.javaToNative(bytes, transferData);
    }
  }

  @Override
  protected Object nativeToJava(TransferData transferData)
  {
    byte[] bytes = (byte[])super.nativeToJava(transferData);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ExtendedDataInputStream in = new ExtendedDataInputStream(bais);

    try
    {
      return readObject(in);
    }
    catch (Exception ex)
    {
      OM.LOG.error(ex);
      return null;
    }
  }

  protected abstract void writeObject(ExtendedDataOutputStream out, TYPE object) throws IOException;

  protected abstract TYPE readObject(ExtendedDataInputStream in) throws IOException;
}

Back to the top