1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.neo4j.server.rest.repr;
21
22 import org.neo4j.helpers.Service;
23 import org.neo4j.server.rest.repr.formats.JsonFormat;
24
25 import javax.ws.rs.core.MediaType;
26 import java.net.URI;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 public final class RepresentationFormatRepository
32 {
33 private final Map<MediaType, RepresentationFormat> formats;
34 private final ExtensionInjector injector;
35
36 public RepresentationFormatRepository( ExtensionInjector injector )
37 {
38 this.injector = injector;
39 this.formats = new HashMap<MediaType, RepresentationFormat>();
40 for ( RepresentationFormat format : Service.load( RepresentationFormat.class ) )
41 {
42 formats.put( format.mediaType, format );
43 }
44 }
45
46 public OutputFormat outputFormat( List<MediaType> acceptable, URI baseUri )
47 {
48 for ( MediaType type : acceptable )
49 {
50 RepresentationFormat format = formats.get( type );
51 if ( format != null )
52 {
53 return new OutputFormat( format, baseUri, injector );
54 }
55 }
56
57 return new OutputFormat( useDefault( acceptable ), baseUri, injector );
58 }
59
60 public InputFormat inputFormat( MediaType type )
61 {
62 if ( type == null )
63 {
64 return useDefault();
65 }
66
67 RepresentationFormat format = formats.get( type );
68 if ( format != null )
69 {
70 return format;
71 }
72
73 format = formats.get( new MediaType( type.getType(), type.getSubtype() ) );
74 if ( format != null )
75 {
76 return format;
77 }
78
79 return useDefault( type );
80 }
81
82 private DefaultFormat useDefault( final List<MediaType> acceptable )
83 {
84 return useDefault( acceptable.toArray( new MediaType[ acceptable.size() ] ) );
85 }
86
87 private DefaultFormat useDefault( final MediaType... type )
88 {
89 return new DefaultFormat( new JsonFormat(), formats.keySet(), type );
90 }
91 }