Project

General

Profile

« Previous | Next » 

Revision d907eaa7

Added by Andreas Kohlbecker almost 13 years ago

modifications in cdmlib for #2206 (modify the means to find images for the data portal)

View differences:

.gitattributes
937 937
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/location/PointTest.java -text
938 938
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/location/TdwgAreaTest.java -text
939 939
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/media/MediaTest.java -text
940
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/media/MediaUtilsTest.java -text
940 941
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/molecular/MolecularTest.java -text
941 942
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/name/BacterialNameTest.java -text
942 943
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/name/BotanicalNameTest.java -text
......
1557 1558
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/dto/tdwg/voc/TaxonName.java -text
1558 1559
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/dto/tdwg/voc/TaxonRelationshipTerm.java -text
1559 1560
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/dto/tdwg/voc/Team.java -text
1560
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/editor/ClassPropertyEditor.java -text
1561
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/editor/CdmTypePropertyEditor.java -text
1561 1562
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/editor/DateTimeEditor.java -text
1562 1563
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/editor/IsoDateTimeEditor.java -text
1563 1564
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/editor/LSIDAuthorityPropertyEditor.java -text
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/media/Media.java
1 1
/**
2 2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy 
3
* European Distributed Institute of Taxonomy
4 4
* http://www.e-taxonomy.eu
5
* 
5
*
6 6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7 7
* See LICENSE.TXT at the top of this package for the full license terms.
8 8
*/
......
57 57
import eu.etaxonomy.cdm.validation.Level2;
58 58

  
59 59
/**
60
 * A {@link Media media} is any kind of media that represents a media object. 
61
 * This media object can have multiple {@link MediaRepresentation media representations} that differ in MIME-type 
62
 * and/or quality. 
63
 * E.g. 
64
 * (1) an image can have a tiff and a jpg media representation. 
65
 * (2) an formatted text can have a text/html or an application/pdf representation. 
60
 * A {@link Media media} is any kind of media that represents a media object.
61
 * This media object can have multiple {@link MediaRepresentation media representations} that differ in MIME-type
62
 * and/or quality.
63
 * E.g.
64
 * (1) an image can have a tiff and a jpg media representation.
65
 * (2) an formatted text can have a text/html or an application/pdf representation.
66 66
 * @author m.doering
67 67
 * @version 1.0
68 68
 * @created 08-Nov-2007 13:06:34
......
81 81
@Audited
82 82
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
83 83
public class Media extends IdentifiableEntity implements Cloneable, IMultiLanguageTextHolder {
84
	private static final long serialVersionUID = -1927421567263473658L;
85
	@SuppressWarnings("unused")
86
	private static final Logger logger = Logger.getLogger(Media.class);
84
    private static final long serialVersionUID = -1927421567263473658L;
85
    @SuppressWarnings("unused")
86
    private static final Logger logger = Logger.getLogger(Media.class);
87 87

  
88 88
    // TODO once hibernate annotations support custom collection type
89
	// private MultilanguageText title = new MultilanguageText();
90
	@XmlElement(name = "MediaTitle")
89
    // private MultilanguageText title = new MultilanguageText();
90
    @XmlElement(name = "MediaTitle")
91 91
    @XmlJavaTypeAdapter(MultilanguageTextAdapter.class)
92 92
    @OneToMany(fetch = FetchType.LAZY)
93 93
    @IndexedEmbedded
94 94
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE,CascadeType.DELETE, CascadeType.DELETE_ORPHAN, CascadeType.REFRESH})
95 95
    @NotNull
96 96
    @NotEmpty(groups = Level2.class)
97
	private Map<Language,LanguageString> title = new HashMap<Language,LanguageString>();
98
	
99
	//creation date of the media (not of the record) 
100
	@XmlElement(name = "MediaCreated", type= String.class)
101
	@XmlJavaTypeAdapter(DateTimeAdapter.class)
102
	@Type(type="dateTimeUserType")
103
	@Basic(fetch = FetchType.LAZY)
104
	private DateTime mediaCreated;
105
	
106
	 // TODO once hibernate annotations support custom collection type
107
	// private MultilanguageText description = new MultilanguageText();
108
	@XmlElement(name = "MediaDescription")
97
    private Map<Language,LanguageString> title = new HashMap<Language,LanguageString>();
98

  
99
    //creation date of the media (not of the record)
100
    @XmlElement(name = "MediaCreated", type= String.class)
101
    @XmlJavaTypeAdapter(DateTimeAdapter.class)
102
    @Type(type="dateTimeUserType")
103
    @Basic(fetch = FetchType.LAZY)
104
    private DateTime mediaCreated;
105

  
106
     // TODO once hibernate annotations support custom collection type
107
    // private MultilanguageText description = new MultilanguageText();
108
    @XmlElement(name = "MediaDescription")
109 109
    @XmlJavaTypeAdapter(MultilanguageTextAdapter.class)
110 110
    @OneToMany(fetch = FetchType.LAZY)
111 111
    @IndexedEmbedded
112 112
    @JoinTable(name = "Media_Description")
113 113
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE,CascadeType.DELETE,CascadeType.DELETE_ORPHAN, CascadeType.REFRESH})
114 114
    @NotNull
115
	private Map<Language,LanguageString> description = new HashMap<Language,LanguageString>();
116
	
117
	//A single medium such as a picture can have multiple representations in files. 
118
	//Common are multiple resolutions or file formats for images for example
119
	@XmlElementWrapper(name = "MediaRepresentations")
120
	@XmlElement(name = "MediaRepresentation")
121
	@OneToMany(mappedBy="media",fetch = FetchType.LAZY)
122
	@Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.DELETE, CascadeType.DELETE_ORPHAN, CascadeType.REFRESH})
123
	@NotNull
124
	@NotEmpty(groups = Level2.class)
125
	private Set<MediaRepresentation> representations = new HashSet<MediaRepresentation>();
126
	
127
	@XmlElement(name = "Artist")
128
	@XmlIDREF
129
	@XmlSchemaType(name = "IDREF")
130
	@ManyToOne(fetch = FetchType.LAZY)
131
	@IndexedEmbedded
132
	@Cascade(CascadeType.SAVE_UPDATE)
133
	private AgentBase artist;
134

  
135

  
136
	/**
137
	 * Factory method
138
	 * @return
139
	 */
140
	public static Media NewInstance(){
141
		return new Media();
142
	}
143
	
144

  
145
	/**
146
	 * Factory method which creates a new media, adds a reprsentation including mime type and suffix information
147
	 * and adds to the later a representation part for a given uri and size
148
	 * Returns <code>null</code> if uri is empty
149
	 * @return Media
150
	 */
151
	public static Media NewInstance(URI uri, Integer size, String mimeType, String suffix){
152
		MediaRepresentation representation = MediaRepresentation.NewInstance(mimeType, suffix, uri, size);
153
		if (representation == null){
154
			return null;
155
		}
156
		Media media = new Media();
157
		media.addRepresentation(representation);
158
		return media;
159
	}
160
	
161
	/**
162
	 * Constructor
163
	 */
164
	protected Media() {
165
		super();
166
		setMediaCacheStrategy();
167
	}
168

  
169
	private void setMediaCacheStrategy() {
170
		if (getClass() == Media.class){
171
			this.cacheStrategy = MediaDefaultCacheStrategy.NewInstance();
172
		}
173
		
174
	}
175

  
176

  
177
	public Set<MediaRepresentation> getRepresentations(){
178
		if(representations == null) {
179
			this.representations = new HashSet<MediaRepresentation>();
180
		}
181
		return this.representations;
182
	}
183

  
184
	@SuppressWarnings("deprecation")
185
	public void addRepresentation(MediaRepresentation representation){
186
		if (representation != null){
187
			this.getRepresentations().add(representation);
188
			representation.setMedia(this);
189
		}
190
	}
191
	
192
	@SuppressWarnings("deprecation")
193
	public void removeRepresentation(MediaRepresentation representation){
194
		this.getRepresentations().remove(representation);
195
		if (representation != null){
196
			representation.setMedia(null);
197
		}
198

  
199
	}
200

  
201
	public AgentBase getArtist(){
202
		return this.artist;
203
	}
204
	
205
	public void setArtist(AgentBase artist){
206
		this.artist = artist;
207
	}
115
    private Map<Language,LanguageString> description = new HashMap<Language,LanguageString>();
116

  
117
    //A single medium such as a picture can have multiple representations in files.
118
    //Common are multiple resolutions or file formats for images for example
119
    @XmlElementWrapper(name = "MediaRepresentations")
120
    @XmlElement(name = "MediaRepresentation")
121
    @OneToMany(mappedBy="media",fetch = FetchType.LAZY)
122
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.DELETE, CascadeType.DELETE_ORPHAN, CascadeType.REFRESH})
123
    @NotNull
124
    @NotEmpty(groups = Level2.class)
125
    private Set<MediaRepresentation> representations = new HashSet<MediaRepresentation>();
126

  
127
    @XmlElement(name = "Artist")
128
    @XmlIDREF
129
    @XmlSchemaType(name = "IDREF")
130
    @ManyToOne(fetch = FetchType.LAZY)
131
    @IndexedEmbedded
132
    @Cascade(CascadeType.SAVE_UPDATE)
133
    private AgentBase artist;
134

  
135

  
136
    /**
137
     * Factory method
138
     * @return
139
     */
140
    public static Media NewInstance(){
141
        return new Media();
142
    }
143

  
144

  
145
    /**
146
     * Factory method which creates a new media, adds a reprsentation including mime type and suffix information
147
     * and adds to the later a representation part for a given uri and size
148
     * Returns <code>null</code> if uri is empty
149
     * @return Media
150
     */
151
    public static Media NewInstance(URI uri, Integer size, String mimeType, String suffix){
152
        MediaRepresentation representation = MediaRepresentation.NewInstance(mimeType, suffix, uri, size);
153
        if (representation == null){
154
            return null;
155
        }
156
        Media media = new Media();
157
        media.addRepresentation(representation);
158
        return media;
159
    }
160

  
161
    /**
162
     * Constructor
163
     */
164
    protected Media() {
165
        super();
166
        setMediaCacheStrategy();
167
    }
168

  
169
    private void setMediaCacheStrategy() {
170
        if (getClass() == Media.class){
171
            this.cacheStrategy = MediaDefaultCacheStrategy.NewInstance();
172
        }
173

  
174
    }
175

  
176

  
177
    public Set<MediaRepresentation> getRepresentations(){
178
        if(representations == null) {
179
            this.representations = new HashSet<MediaRepresentation>();
180
        }
181
        return this.representations;
182
    }
183

  
184
    @SuppressWarnings("deprecation")
185
    public void addRepresentation(MediaRepresentation representation){
186
        if (representation != null){
187
            this.getRepresentations().add(representation);
188
            representation.setMedia(this);
189
        }
190
    }
191

  
192
    @SuppressWarnings("deprecation")
193
    public void removeRepresentation(MediaRepresentation representation){
194
        this.getRepresentations().remove(representation);
195
        if (representation != null){
196
            representation.setMedia(null);
197
        }
198

  
199
    }
200

  
201
    public AgentBase getArtist(){
202
        return this.artist;
203
    }
204

  
205
    public void setArtist(AgentBase artist){
206
        this.artist = artist;
207
    }
208 208

  
209 209
//************************ title / title cache *********************************
210
	
211
	public LanguageString getTitle(){
212
		return getTitle(Language.DEFAULT());
213
	}
214
	
215
	public LanguageString getTitle(Language language){
216
		return title.get(language);
217
	}
218
	
219
	@Transient
220
	public Map<Language,LanguageString> getAllTitles(){
221
		if(title == null) {
222
			this.title = new HashMap<Language,LanguageString>();
223
		}
224
		return this.title;
225
	}
226
	/**
227
	 * Adds the languageString to the {@link MultilanguageText multilanguage text} 
228
	 * used to be the title of <i>this</i> media.
229
	 * 
230
	 * @param title		the languageString with the title in a particular language
231
	 * @see    	   		#getTitle()
232
	 * @see    	   		#putTitle(Language String)
233
	 * @deprecated		should follow the put semantic of maps, this method will be removed in v4.0
234
	 * 					Use the {@link #putTitle(LanguageString) putTitle} method instead
235
	 */
236
	@Deprecated
237
	public void addTitle(LanguageString title){
238
		this.putTitle(title);
239
	}
240
	public void putTitle(LanguageString title){
241
		this.title.put(title.getLanguage(), title);
242
	}
243
	
244
	/**
245
	 * Creates a {@link LanguageString language string} based on the given text string
246
	 * and the given {@link Language language} and adds it to the {@link MultilanguageText multilanguage text} 
247
	 * used to be the title of <i>this</i> media.
248
	 * 
249
	 * @param text		the title in a particular language
250
	 * @param language	the language in which the title string is formulated
251
	 * @see    	   		#getTitle()
252
	 * @see    	   		#putTitle(LanguageString)
253
	 * @deprecated		should follow the put semantic of maps, this method will be removed in v4.0
254
	 * 					Use the {@link #putTitle(Language, String) putTitle} method instead
255
	 */
256
	@Deprecated
257
	public void addTitle(String title, Language language){
258
		this.putTitle(language, title);
259
	}
260
	/**
261
	 * Creates a {@link LanguageString language string} based on the given text string
262
	 * and the given {@link Language language} and adds it to the {@link MultilanguageText multilanguage text} 
263
	 * used to be the title of <i>this</i> media.
264
	 * 
265
	 * @param language	the language in which the title string is formulated
266
	 * @param text		the title in a particular language
267
	 * 
268
	 * @see    	   		#getTitle()
269
	 * @see    	   		#putTitle(LanguageString)
270
	 */
271
	public void putTitle(Language language, String title){
272
		this.title.put(language, LanguageString.NewInstance(title, language));
273
	}
274
	
275
	public void removeTitle(Language language){
276
		this.title.remove(language);
277
	}
278
	
279

  
280
	@Transient 
281
	public String getTitleCacheByLanguage(Language lang){
282
		if (cacheStrategy != null){
283
			return ((MediaDefaultCacheStrategy)cacheStrategy).getTitleCacheByLanguage(this, lang);
284
		}else{
285
			return null;
286
		}
287
			
288
	}
289
	
290
	
291
	/*
292
	 * (non-Javadoc)
293
	 * @see eu.etaxonomy.cdm.model.common.IdentifiableEntity#setTitleCache(java.lang.String)
294
	 */
295
	@Override
296
	public void setTitleCache(String titleCache) {
297
		putTitle(LanguageString.NewInstance(titleCache, Language.DEFAULT()));
298
	}
299
	
300
	/* (non-Javadoc)
301
	 * @see eu.etaxonomy.cdm.model.common.IIdentifiableEntity#getTitleCache()
302
	 */
303
	@Override
304
	public String getTitleCache(){
305
		if (protectedTitleCache){
306
			return this.titleCache;			
307
		}
308
		// is title dirty, i.e. equal NULL?
309
		if (titleCache == null){
310
			this.titleCache = generateTitle();
311
			this.titleCache = getTruncatedCache(this.titleCache) ;
312
		}else{
313
			//do the same as listeners on dependend objects like representations parts
314
			//are not yet installed
315
			this.titleCache = generateTitle();
316
			this.titleCache = getTruncatedCache(this.titleCache) ;
317
		}
318
		return titleCache;
319
	}
320
	
321
	
322
	
323

  
324
	public DateTime getMediaCreated(){
325
		return this.mediaCreated;
326
	}
327
	
328
	public void setMediaCreated(DateTime mediaCreated){
329
		this.mediaCreated = mediaCreated;
330
	}
331

  
332
	//************* Descriptions
333

  
334
	public Map<Language,LanguageString> getAllDescriptions(){
335
		if(this.description == null) {
336
			this.description = new HashMap<Language,LanguageString>();
337
		}
338
		return this.description;
339
	}
340
	
341
	public LanguageString getDescription(Language language){
342
		return getAllDescriptions().get(language);
343
	}
344
	
345
	public void addDescription(LanguageString description){
346
		this.description.put(description.getLanguage(), description);
347
	}
348
	
349
	public void addDescription(String text, Language language){
350
		this.description.put(language, LanguageString.NewInstance(text, language));
351
	}
352
	
353
	public void removeDescription(Language language){
354
		this.description.remove(language);
355
	}
356
	
210

  
211
    public LanguageString getTitle(){
212
        return getTitle(Language.DEFAULT());
213
    }
214

  
215
    public LanguageString getTitle(Language language){
216
        return title.get(language);
217
    }
218

  
219
    @Transient
220
    public Map<Language,LanguageString> getAllTitles(){
221
        if(title == null) {
222
            this.title = new HashMap<Language,LanguageString>();
223
        }
224
        return this.title;
225
    }
226
    /**
227
     * Adds the languageString to the {@link MultilanguageText multilanguage text}
228
     * used to be the title of <i>this</i> media.
229
     *
230
     * @param title		the languageString with the title in a particular language
231
     * @see    	   		#getTitle()
232
     * @see    	   		#putTitle(Language String)
233
     * @deprecated		should follow the put semantic of maps, this method will be removed in v4.0
234
     * 					Use the {@link #putTitle(LanguageString) putTitle} method instead
235
     */
236
    @Deprecated
237
    public void addTitle(LanguageString title){
238
        this.putTitle(title);
239
    }
240
    public void putTitle(LanguageString title){
241
        this.title.put(title.getLanguage(), title);
242
    }
243

  
244
    /**
245
     * Creates a {@link LanguageString language string} based on the given text string
246
     * and the given {@link Language language} and adds it to the {@link MultilanguageText multilanguage text}
247
     * used to be the title of <i>this</i> media.
248
     *
249
     * @param text		the title in a particular language
250
     * @param language	the language in which the title string is formulated
251
     * @see    	   		#getTitle()
252
     * @see    	   		#putTitle(LanguageString)
253
     * @deprecated		should follow the put semantic of maps, this method will be removed in v4.0
254
     * 					Use the {@link #putTitle(Language, String) putTitle} method instead
255
     */
256
    @Deprecated
257
    public void addTitle(String title, Language language){
258
        this.putTitle(language, title);
259
    }
260
    /**
261
     * Creates a {@link LanguageString language string} based on the given text string
262
     * and the given {@link Language language} and adds it to the {@link MultilanguageText multilanguage text}
263
     * used to be the title of <i>this</i> media.
264
     *
265
     * @param language	the language in which the title string is formulated
266
     * @param text		the title in a particular language
267
     *
268
     * @see    	   		#getTitle()
269
     * @see    	   		#putTitle(LanguageString)
270
     */
271
    public void putTitle(Language language, String title){
272
        this.title.put(language, LanguageString.NewInstance(title, language));
273
    }
274

  
275
    public void removeTitle(Language language){
276
        this.title.remove(language);
277
    }
278

  
279

  
280
    @Transient
281
    public String getTitleCacheByLanguage(Language lang){
282
        if (cacheStrategy != null){
283
            return ((MediaDefaultCacheStrategy)cacheStrategy).getTitleCacheByLanguage(this, lang);
284
        }else{
285
            return null;
286
        }
287

  
288
    }
289

  
290

  
291
    /*
292
     * (non-Javadoc)
293
     * @see eu.etaxonomy.cdm.model.common.IdentifiableEntity#setTitleCache(java.lang.String)
294
     */
295
    @Override
296
    public void setTitleCache(String titleCache) {
297
        putTitle(LanguageString.NewInstance(titleCache, Language.DEFAULT()));
298
    }
299

  
300
    /* (non-Javadoc)
301
     * @see eu.etaxonomy.cdm.model.common.IIdentifiableEntity#getTitleCache()
302
     */
303
    @Override
304
    public String getTitleCache(){
305
        if (protectedTitleCache){
306
            return this.titleCache;
307
        }
308
        // is title dirty, i.e. equal NULL?
309
        if (titleCache == null){
310
            this.titleCache = generateTitle();
311
            this.titleCache = getTruncatedCache(this.titleCache) ;
312
        }else{
313
            //do the same as listeners on dependend objects like representations parts
314
            //are not yet installed
315
            this.titleCache = generateTitle();
316
            this.titleCache = getTruncatedCache(this.titleCache) ;
317
        }
318
        return titleCache;
319
    }
320

  
321

  
322

  
323

  
324
    public DateTime getMediaCreated(){
325
        return this.mediaCreated;
326
    }
327

  
328
    public void setMediaCreated(DateTime mediaCreated){
329
        this.mediaCreated = mediaCreated;
330
    }
331

  
332
    //************* Descriptions
333

  
334
    public Map<Language,LanguageString> getAllDescriptions(){
335
        if(this.description == null) {
336
            this.description = new HashMap<Language,LanguageString>();
337
        }
338
        return this.description;
339
    }
340

  
341
    public LanguageString getDescription(Language language){
342
        return getAllDescriptions().get(language);
343
    }
344

  
345
    public void addDescription(LanguageString description){
346
        this.description.put(description.getLanguage(), description);
347
    }
348

  
349
    public void addDescription(String text, Language language){
350
        this.description.put(language, LanguageString.NewInstance(text, language));
351
    }
352

  
353
    public void removeDescription(Language language){
354
        this.description.remove(language);
355
    }
356

  
357 357
//************************* CLONE **************************/
358
	
359
	
360
	/* (non-Javadoc)
361
	 * @see java.lang.Object#clone()
362
	 */
363
	@Override
364
	public Object clone() throws CloneNotSupportedException{
365
		Media result = (Media)super.clone();
366
		//description
367
		result.description = new HashMap<Language, LanguageString>();
368
		for (Language language: this.description.keySet()){
369
			result.description.put(language, this.description.get(language));
370
		}
371
		//title
372
		result.title = new HashMap<Language, LanguageString>();
373
		for (Language language: this.title.keySet()){
374
			result.title.put(language, this.title.get(language));
375
		}
376
		//media representations
377
		result.representations = new HashSet<MediaRepresentation>();
378
		for (MediaRepresentation mediaRepresentation: this.representations){
379
			result.representations.add((MediaRepresentation)mediaRepresentation.clone());
380
		}
381
		//no changes to: artist
382
		return result;
383
	}
384
	
385
	public int compareTo(Object o) {
386
		return 0;
387
	}
388
	
389
	
390
	
358

  
359

  
360
    /* (non-Javadoc)
361
     * @see java.lang.Object#clone()
362
     */
363
    @Override
364
    public Object clone() throws CloneNotSupportedException{
365
        Media result = (Media)super.clone();
366
        //description
367
        result.description = new HashMap<Language, LanguageString>();
368
        for (Language language: this.description.keySet()){
369
            result.description.put(language, this.description.get(language));
370
        }
371
        //title
372
        result.title = new HashMap<Language, LanguageString>();
373
        for (Language language: this.title.keySet()){
374
            result.title.put(language, this.title.get(language));
375
        }
376
        //media representations
377
        result.representations = new HashSet<MediaRepresentation>();
378
        for (MediaRepresentation mediaRepresentation: this.representations){
379
            result.representations.add((MediaRepresentation)mediaRepresentation.clone());
380
        }
381
        //no changes to: artist
382
        return result;
383
    }
384

  
385
    public int compareTo(Object o) {
386
        return 0;
387
    }
388

  
389

  
390

  
391 391
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/media/MediaUtils.java
1 1
package eu.etaxonomy.cdm.model.media;
2 2

  
3 3
import java.util.ArrayList;
4
import java.util.Collection;
5
import java.util.Collections;
6
import java.util.HashSet;
7
import java.util.Iterator;
4 8
import java.util.List;
5 9
import java.util.NoSuchElementException;
10
import java.util.Set;
6 11
import java.util.SortedMap;
7 12
import java.util.TreeMap;
8 13
import java.util.regex.Matcher;
......
12 17

  
13 18
public class MediaUtils {
14 19

  
15
	private static final Logger logger = Logger.getLogger(MediaUtils.class);
16
	
17
	/**
18
	 * @param mimeTypeRegexes
19
	 * @param size
20
	 * @param widthOrDuration
21
	 * @param height
22
	 * @return
23
	 * 
24
	 * 
25
	 */
26
	public static MediaRepresentation findBestMatchingRepresentation(Media media, Integer size, Integer height, Integer widthOrDuration, String[] mimeTypes){
27
		// find best matching representations of each media
28
		SortedMap<Integer, MediaRepresentation> prefRepresentations 
29
			= orderMediaRepresentations(media, mimeTypes, size, widthOrDuration, height);
30
			try {
31
				// take first one and remove all other representations
32
				MediaRepresentation prefOne = prefRepresentations.get(prefRepresentations.firstKey());
33
				
34
				return prefOne;
35
				
36
			} catch (NoSuchElementException nse) {
37
				/* IGNORE */
38
			}
39
			return null;
40
		}
41
	
42
	/**
43
	 * @param mediaList
44
	 * @param mimeTypes
45
	 * @param sizeTokens
46
	 * @param widthOrDuration
47
	 * @param height
48
	 * @param size
49
	 * @return
50
	 */
51
	public static List<Media> findPreferredMedia(List<Media> mediaList,
52
			String[] mimeTypes, String[] sizeTokens, Integer widthOrDuration,
53
			Integer height, Integer size) {
54
		for(int i=0; i<mimeTypes.length; i++){
55
			mimeTypes[i] = mimeTypes[i].replace(':', '/');
56
		}
57
		
58
		if(sizeTokens.length > 0){
59
			try {
60
				size = Integer.valueOf(sizeTokens[0]);
61
			} catch (NumberFormatException nfe) {
62
				/* IGNORE */
63
			}
64
		}
65
		if(sizeTokens.length > 1){
66
			try {
67
				widthOrDuration = Integer.valueOf(sizeTokens[1]);
68
			} catch (NumberFormatException nfe) {
69
				/* IGNORE */
70
			}
71
		}
72
		if(sizeTokens.length > 2){
73
			try {
74
				height = Integer.valueOf(sizeTokens[2]);
75
			} catch (NumberFormatException nfe) {
76
				/* IGNORE */
77
			}
78
		}
79
		
80
		List<Media> returnMedia = new ArrayList<Media>(mediaList.size());
81
		if(mediaList != null){
82
			for(Media media : mediaList){
83
				SortedMap<Integer, MediaRepresentation> prefRepresentations 
84
					= orderMediaRepresentations(media, mimeTypes, size, widthOrDuration, height);
85
				try {
86
					// take first one and remove all other representations
87
					MediaRepresentation prefOne = prefRepresentations.get(prefRepresentations.firstKey());
88
					for (MediaRepresentation representation : media.getRepresentations()) {
89
						if (representation != prefOne) {
90
							media.removeRepresentation(representation);
91
						}
92
					}
93
					returnMedia.add(media);
94
				} catch (NoSuchElementException nse) {
95
					logger.debug(nse);
96
					/* IGNORE */
97
				}
98
			}
99
		}
100
		return returnMedia;
101
	}
102
	
103
	/**
104
	 * @param media
105
	 * @param mimeTypeRegexes
106
	 * @param size
107
	 * @param widthOrDuration
108
	 * @param height
109
	 * @return
110
	 * 
111
	 * TODO move into a media utils class
112
	 * TODO implement the quality filter  
113
	 
114
	public static SortedMap<String, MediaRepresentation> orderMediaRepresentations(Media media, String[] mimeTypeRegexes,
115
			Integer size, Integer widthOrDuration, Integer height) {
116
		SortedMap<String, MediaRepresentation> prefRepr = new TreeMap<String, MediaRepresentation>();
117
		for (String mimeTypeRegex : mimeTypeRegexes) {
118
			// getRepresentationByMimeType
119
			Pattern mimeTypePattern = Pattern.compile(mimeTypeRegex);
120
			int representationCnt = 0;
121
			for (MediaRepresentation representation : media.getRepresentations()) {
122
				int dwa = 0;
123
				if(representation.getMimeType() == null){
124
					prefRepr.put((dwa + representationCnt++) + "_NA", representation);
125
				} else {
126
					Matcher mather = mimeTypePattern.matcher(representation.getMimeType());
127
					if (mather.matches()) {
128
	
129
						/* TODO the quality filter part is being skipped 
130
						 * // look for representation with the best matching parts
131
						for (MediaRepresentationPart part : representation.getParts()) {
132
							if (part instanceof ImageFile) {
133
								ImageFile image = (ImageFile) part;
134
								int dw = image.getWidth() * image.getHeight() - height * widthOrDuration;
135
								if (dw < 0) {
136
									dw *= -1;
137
								}
138
								dwa += dw;
139
							}
140
							dwa = (representation.getParts().size() > 0 ? dwa / representation.getParts().size() : 0);
141
						}
142
						prefRepr.put((dwa + representationCnt++) + '_' + representation.getMimeType(), representation);
143
											
144
						// preferred mime type found => end loop
145
						break;
146
					}
147
				}
148
			}
149
		}
150
		return prefRepr;
151
	}
152

  
153
	*/
154
	/**
155
	 * @param mimeTypeRegexes
156
	 * @param size
157
	 * @param widthOrDuration
158
	 * @param height
159
	 * @return
160
	 * 
161
	 * 
162
	 */
163
	private static SortedMap<Integer, MediaRepresentation> orderMediaRepresentations(Media media, String[] mimeTypeRegexes,
164
			Integer size, Integer widthOrDuration, Integer height) {
165
		
166
		SortedMap<Integer, MediaRepresentation> prefRepr = new TreeMap<Integer, MediaRepresentation>();
167
//		SortedMap<String, MediaRepresentation> sortedForSizeDistance = new TreeMap<String, MediaRepresentation>();		
168
//		String keyString = "";
169
		
170
		size = (size == null ? new Integer(0) : size );
171
		widthOrDuration = (widthOrDuration == null ? new Integer(0) : widthOrDuration);
172
		height = (height == null ? new Integer(0) : height);
173
		mimeTypeRegexes = (mimeTypeRegexes == null ? new String[]{} : mimeTypeRegexes);
174
		
175
		if(media != null){
176
			
177
			for (String mimeTypeRegex : mimeTypeRegexes) {
178
				// getRepresentationByMimeType
179
				Pattern mimeTypePattern = Pattern.compile(mimeTypeRegex);
180
				int representationCnt = 0;
181
				for (MediaRepresentation representation : media.getRepresentations()) {
182
					if(representation.getMimeType() != null){
183
						Matcher mather = mimeTypePattern.matcher(representation.getMimeType());
184
						if (mather.matches()) {
185
							int dwa = 0;
186
							
187
							//first the size is used for comparison
188
							for (MediaRepresentationPart part : representation.getParts()) {
189
								if (part.getSize()!= null){
190
									int sizeOfPart = part.getSize();
191
									int distance = sizeOfPart - size;
192
									if (distance < 0) {
193
										distance*= -1;
194
									}
195
									dwa += distance;
196
								}
197
								//if height and width/duration is defined, add this information, too
198
								if (height != 0 && widthOrDuration != 0){
199
									int dw = 0;
200
									
201
									if (part instanceof ImageFile) {
202
										ImageFile image = (ImageFile) part;
203
										dw = image.getWidth() * image.getHeight() - height * widthOrDuration;
204
									}
205
									else if (part instanceof MovieFile){
206
										MovieFile movie = (MovieFile) part;
207
										dw = movie.getDuration() - widthOrDuration;
208
												
209
									}else if (part instanceof AudioFile){
210
										AudioFile audio = (AudioFile) part;
211
										dw = audio.getDuration() - widthOrDuration;
212
										
213
									}
214
									if (dw < 0) {
215
										dw *= -1;
216
									}
217
									dwa += dw;
218
									
219
								}
220
							}
221
							dwa = (representation.getParts().size() > 0 ? dwa / representation.getParts().size() : 0);
222
							
223
							//keyString =(dwa + representationCnt++) + '_' + representation.getMimeType();
224
							
225
							prefRepr.put((dwa + representationCnt++), representation);
226
						}
227
					}		
228
				}										
229
			}
230
		}
231
		return prefRepr;
232
	}
20
    private static final Logger logger = Logger.getLogger(MediaUtils.class);
21

  
22
    /**
23
     * @param representationPartType TODO
24
     * @param size
25
     * @param height
26
     * @param widthOrDuration
27
     * @param mimeTypeRegexes
28
     * @return
29
     *
30
     *
31
     */
32
    public static MediaRepresentation findBestMatchingRepresentation(Media media, Class<? extends MediaRepresentationPart> representationPartType, Integer size, Integer height, Integer widthOrDuration, String[] mimeTypes){
33
        // find best matching representations of each media
34
        SortedMap<Integer, MediaRepresentation> prefRepresentations
35
            = filterAndOrderMediaRepresentations(media.getRepresentations(), null, mimeTypes, size, widthOrDuration, height);
36
            try {
37
                // take first one and remove all other representations
38
                MediaRepresentation prefOne = prefRepresentations.get(prefRepresentations.firstKey());
39

  
40
                return prefOne;
41

  
42
            } catch (NoSuchElementException nse) {
43
                /* IGNORE */
44
            }
45
            return null;
46
        }
47

  
48
    /**
49
     *
50
     * @param mediaList
51
     * @param representationPartType TODO
52
     * @param mimeTypes
53
     * @param sizeTokens
54
     * @param widthOrDuration
55
     * @param height
56
     * @param size
57
     * @return
58
     */
59
    public static List<Media> findPreferredMedia(List<Media> mediaList,
60
            Class<? extends MediaRepresentationPart> representationPartType, String[] mimeTypes, String[] sizeTokens,
61
            Integer widthOrDuration, Integer height, Integer size) {
62

  
63
        if(mimeTypes != null) {
64
            for(int i=0; i<mimeTypes.length; i++){
65
                mimeTypes[i] = mimeTypes[i].replace(':', '/');
66
            }
67
        }
68

  
69
        if(sizeTokens != null) {
70
            if(sizeTokens.length > 0){
71
                try {
72
                    size = Integer.valueOf(sizeTokens[0]);
73
                } catch (NumberFormatException nfe) {
74
                    /* IGNORE */
75
                }
76
            }
77
            if(sizeTokens.length > 1){
78
                try {
79
                    widthOrDuration = Integer.valueOf(sizeTokens[1]);
80
                } catch (NumberFormatException nfe) {
81
                    /* IGNORE */
82
                }
83
            }
84
            if(sizeTokens.length > 2){
85
                try {
86
                    height = Integer.valueOf(sizeTokens[2]);
87
                } catch (NumberFormatException nfe) {
88
                    /* IGNORE */
89
                }
90
            }
91
        }
92

  
93
        List<Media> returnMediaList = new ArrayList<Media>(mediaList.size());
94
        if(mediaList != null){
95
            for(Media media : mediaList){
96

  
97
                Set<MediaRepresentation> candidateRepresentations = new HashSet<MediaRepresentation>();
98
                candidateRepresentations.addAll(media.getRepresentations());
99

  
100
                SortedMap<Integer, MediaRepresentation> prefRepresentations
101
                    = filterAndOrderMediaRepresentations(candidateRepresentations, representationPartType, mimeTypes, size, widthOrDuration, height);
102
                try {
103
                    if(prefRepresentations.size() > 0){
104
                        // Media.representations is a set
105
                        // so it cannot retain the sorting which has been found by filterAndOrderMediaRepresentations()
106
                        // thus we take first one and remove all other representations
107

  
108
                        media.getRepresentations().clear();
109
                        media.addRepresentation(prefRepresentations.get(prefRepresentations.firstKey()));
110
                        returnMediaList.add(media);
111
                    }
112
                } catch (NoSuchElementException nse) {
113
                    logger.debug(nse);
114
                    /* IGNORE */
115
                }
116

  
117
            }
118
        }
119
        return returnMediaList;
120
    }
121

  
122
    /**
123
     * @param media
124
     * @param mimeTypeRegexes
125
     * @param size
126
     * @param widthOrDuration
127
     * @param height
128
     * @return
129
     *
130
     * TODO move into a media utils class
131
     * TODO implement the quality filter
132

  
133
    public static SortedMap<String, MediaRepresentation> orderMediaRepresentations(Media media, String[] mimeTypeRegexes,
134
            Integer size, Integer widthOrDuration, Integer height) {
135
        SortedMap<String, MediaRepresentation> prefRepr = new TreeMap<String, MediaRepresentation>();
136
        for (String mimeTypeRegex : mimeTypeRegexes) {
137
            // getRepresentationByMimeType
138
            Pattern mimeTypePattern = Pattern.compile(mimeTypeRegex);
139
            int representationCnt = 0;
140
            for (MediaRepresentation representation : media.getRepresentations()) {
141
                int dwa = 0;
142
                if(representation.getMimeType() == null){
143
                    prefRepr.put((dwa + representationCnt++) + "_NA", representation);
144
                } else {
145
                    Matcher mather = mimeTypePattern.matcher(representation.getMimeType());
146
                    if (mather.matches()) {
147

  
148
                        /* TODO the quality filter part is being skipped
149
                         * // look for representation with the best matching parts
150
                        for (MediaRepresentationPart part : representation.getParts()) {
151
                            if (part instanceof ImageFile) {
152
                                ImageFile image = (ImageFile) part;
153
                                int dw = image.getWidth() * image.getHeight() - height * widthOrDuration;
154
                                if (dw < 0) {
155
                                    dw *= -1;
156
                                }
157
                                dwa += dw;
158
                            }
159
                            dwa = (representation.getParts().size() > 0 ? dwa / representation.getParts().size() : 0);
160
                        }
161
                        prefRepr.put((dwa + representationCnt++) + '_' + representation.getMimeType(), representation);
162

  
163
                        // preferred mime type found => end loop
164
                        break;
165
                    }
166
                }
167
            }
168
        }
169
        return prefRepr;
170
    }
171

  
172
    */
173
    /**
174
     * @param mimeTypeRegexes
175
     * @param size
176
     * @param widthOrDuration
177
     * @param height
178
     * @return
179
     *
180
     *
181
     */
182
    private static SortedMap<Integer, MediaRepresentation> filterAndOrderMediaRepresentations(Set<MediaRepresentation> mediaRepresentations,
183
            Class<? extends MediaRepresentationPart> representationPartType, String[] mimeTypeRegexes,
184
            Integer size, Integer widthOrDuration, Integer height) {
185

  
186
        SortedMap<Integer, MediaRepresentation> prefRepr = new TreeMap<Integer, MediaRepresentation>();
187

  
188

  
189
        size = (size == null ? new Integer(0) : size );
190
        widthOrDuration = (widthOrDuration == null ? new Integer(0) : widthOrDuration);
191
        height = (height == null ? new Integer(0) : height);
192
        mimeTypeRegexes = (mimeTypeRegexes == null ? new String[]{".*"} : mimeTypeRegexes);
193

  
194
        for (String mimeTypeRegex : mimeTypeRegexes) {
195
            // getRepresentationByMimeType
196
            Pattern mimeTypePattern = Pattern.compile(mimeTypeRegex);
197
            int representationCnt = 0;
198
            for (MediaRepresentation representation : mediaRepresentations) {
199

  
200
                List<MediaRepresentationPart> matchingParts = new ArrayList<MediaRepresentationPart>();
201

  
202

  
203
                // check MIME type
204
                boolean mimeTypeOK = representation.getMimeType() == null || mimeTypePattern.matcher(representation.getMimeType()).matches();
205
                logger.debug("mimeTypeOK: " + Boolean.valueOf(mimeTypeOK).toString());
206

  
207
                int dwa = 0;
208

  
209

  
210
                //first the size is used for comparison
211
                for (MediaRepresentationPart part : representation.getParts()) {
212

  
213
                    // check representationPartType
214
                    boolean representationPartTypeOK = representationPartType == null || part.getClass().isAssignableFrom(representationPartType);
215
                    logger.debug("representationPartTypeOK: " + Boolean.valueOf(representationPartTypeOK).toString());
216

  
217
                    if ( !(representationPartTypeOK && mimeTypeOK) ) {
218
                        continue;
219
                    }
220

  
221
                    logger.debug(part + " matches");
222
                    matchingParts.add(part);
223

  
224
                    if (part.getSize()!= null){
225
                        int sizeOfPart = part.getSize();
226
                        int distance = sizeOfPart - size;
227
                        if (distance < 0) {
228
                            distance*= -1;
229
                        }
230
                        dwa += distance;
231
                    }
232

  
233
                    //if height and width/duration is defined, add this information, too
234
                    if (height != 0 && widthOrDuration != 0){
235
                        int durationWidthWeight = 0;
236

  
237
                        if (part instanceof ImageFile) {
238
                            ImageFile image = (ImageFile) part;
239
                            durationWidthWeight = image.getWidth() * image.getHeight() - height * widthOrDuration;
240
                        }
241
                        else if (part instanceof MovieFile){
242
                            MovieFile movie = (MovieFile) part;
243
                            durationWidthWeight = movie.getDuration() - widthOrDuration;
244

  
245
                        }else if (part instanceof AudioFile){
246
                            AudioFile audio = (AudioFile) part;
247
                            durationWidthWeight = audio.getDuration() - widthOrDuration;
248

  
249
                        }
250
                        if (durationWidthWeight < 0) {
251
                            durationWidthWeight *= -1;
252
                        }
253
                        dwa += durationWidthWeight;
254

  
255
                    }
256
                } // loop parts
257
                logger.debug("matchingParts.size():" + matchingParts.size());
258
                if(matchingParts.size() > 0 ){
259
                    dwa = dwa / matchingParts.size();
260

  
261
                    representation.getParts().clear();
262
                    representation.getParts().addAll(matchingParts);
263

  
264
                    //keyString =(dwa + representationCnt++) + '_' + representation.getMimeType();
265

  
266
                    prefRepr.put((dwa + representationCnt++), representation);
267
                }
268
            } // loop representations
269
        } // loop mime types
270
        logger.debug(prefRepr.size() + " preferred representations found");
271
        return prefRepr;
272
    }
233 273
}
cdmlib-model/src/test/java/eu/etaxonomy/cdm/model/media/MediaTest.java
1 1
// $Id$
2 2
/**
3 3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy 
4
* European Distributed Institute of Taxonomy
5 5
* http://www.e-taxonomy.eu
6
* 
6
*
7 7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8 8
* See LICENSE.TXT at the top of this package for the full license terms.
9 9
*/
......
35 35
 * @version 1.0
36 36
 */
37 37
public class MediaTest {
38
	@SuppressWarnings("unused")
39
	private static final Logger logger = Logger.getLogger(MediaTest.class);
40

  
41
	private Media media1; 
42
	private Team team1;
43
	private MediaRepresentation mediaRepresentation1;
44
	private MediaRepresentation mediaRepresentation2;
45
	private MediaRepresentationPart mediaRepresentationPart1;
46
	private MediaRepresentationPart mediaRepresentationPart2;
47
	private LanguageString languageString1;
48
	private final String germanDescription = "media1Desc2";
49
	private Rights rights1;
50
	private LanguageString languageString2;
51
	private static URI uriString1;
52
	private static URI uriString2;
53
	
54
	/**
55
	 * @throws java.lang.Exception
56
	 */
57
	@BeforeClass
58
	public static void setUpBeforeClass() throws Exception {
59
		DefaultTermInitializer termInitializer = new DefaultTermInitializer();
60
		termInitializer.initialize();
61
		try {
62
			uriString1 = new URI("http://Pathtoimage1/");
63
			uriString2 = new URI("http://Path_to_image_2/");
64
		} catch (Exception e) {
65
			e.printStackTrace();
66
			Assert.fail("Error in URI syntax");
67
		}
68
		
69
	}
70

  
71
	/**
72
	 * @throws java.lang.Exception
73
	 */
74
	@AfterClass
75
	public static void tearDownAfterClass() throws Exception {
76
	}
77

  
78
	/**
79
	 * @throws java.lang.Exception
80
	 */
81
	@Before
82
	public void setUp() throws Exception {
83
		media1 = Media.NewInstance();
84
		team1 = Team.NewInstance();
85
		media1.setArtist(team1);
86
		media1.setMediaCreated(new DateTime(2002, 1,1,0,0,0,0));
87
		languageString1 = LanguageString.NewInstance("media1Desc", Language.DEFAULT());
88
		media1.addDescription(languageString1);
89
		media1.addDescription("media1Desc2", Language.GERMAN());
90
		mediaRepresentation1 = MediaRepresentation.NewInstance();
91
		mediaRepresentation2 = MediaRepresentation.NewInstance();
92
		mediaRepresentation1.setMimeType("MimeType1");
93
		mediaRepresentation2.setMimeType("MimeType1");
94
		mediaRepresentationPart1 = ImageFile.NewInstance(uriString1, 100);
95
		mediaRepresentationPart2 = ImageFile.NewInstance(uriString2, 1000);
96
		((ImageFile) mediaRepresentationPart1).setHeight(100);
97
		((ImageFile) mediaRepresentationPart1).setWidth(100);
98
		
99
		((ImageFile) mediaRepresentationPart2).setHeight(100);
100
		((ImageFile) mediaRepresentationPart2).setWidth(100);
101
		
102
		mediaRepresentation1.addRepresentationPart(mediaRepresentationPart1);
103
		mediaRepresentation2.addRepresentationPart(mediaRepresentationPart2);
104
		media1.addRepresentation(mediaRepresentation1);
105
		media1.addRepresentation(mediaRepresentation2);
106
		rights1 = Rights.NewInstance();
107
		media1.addRights(rights1);
108
		
109
		languageString2 = LanguageString.NewInstance("media1Title", Language.DEFAULT());
110
		media1.putTitle(languageString2);
111
		
112
	}
113

  
114
	/**
115
	 * @throws java.lang.Exception
116
	 */
117
	@After
118
	public void tearDown() throws Exception {
119
	}
120

  
121
//***************** TESTS *********************************/	
122
	
123
	/**
124
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#clone()}.
125
	 */
126
	@Test
127
	public void testClone() {
128
		try {
129
			Media mediaClone = (Media)media1.clone();
130
			Assert.assertSame("Artist must be the same", team1, mediaClone.getArtist());
131
			Assert.assertTrue("Clone must have a default language description", mediaClone.getAllDescriptions().containsKey(Language.DEFAULT()));
132
			Assert.assertSame("Description1 must be the same", languageString1, mediaClone.getAllDescriptions().get(Language.DEFAULT()) );
133
			Assert.assertTrue("Clone must have a german description", mediaClone.getAllDescriptions().containsKey(Language.GERMAN()));
134
			Assert.assertEquals("German description must equal media1Desc2", germanDescription, mediaClone.getAllDescriptions().get(Language.GERMAN()).getText() );
135
			
136
			Assert.assertEquals("Media created year must be 2002", 2002, mediaClone.getMediaCreated().getYear());
137
			Assert.assertEquals("Number of media representations must be 2", 2, mediaClone.getRepresentations().size());
138
			Assert.assertNotSame("Only media representation must not be mediaRepresentation1", mediaRepresentation1, mediaClone.getRepresentations().iterator().next());
139
			Assert.assertEquals("Only meda representation must have same MimeType as mediaRepresentation1", mediaRepresentation1.getMimeType(), mediaClone.getRepresentations().iterator().next().getMimeType());
140
			Assert.assertTrue("Rights must contain rights1", mediaClone.getRights().contains(rights1));
141
		
142
			Assert.assertTrue("Clone must have a default language title", mediaClone.getAllTitles().containsKey(Language.DEFAULT()));
143
			Assert.assertSame("Title must be the same", languageString2, mediaClone.getAllTitles().get(Language.DEFAULT()) );
144
			
145
		} catch (CloneNotSupportedException e) {
146
			Assert.fail("Media must be cloneable");
147
		}
148
		
149
	}
150

  
151
	/**
152
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#addRepresentation(eu.etaxonomy.cdm.model.media.MediaRepresentation)}.
153
	 */
154
	@Test
155
	public void testAddRepresentation() {
156
		Assert.assertTrue("Representations must contain mediaRepresentation1", media1.getRepresentations().contains(mediaRepresentation1));
157
	}
158

  
159
	/**
160
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#removeRepresentation(eu.etaxonomy.cdm.model.media.MediaRepresentation)}.
161
	 */
162
	@Test
163
	public void testRemoveRepresentation() {
164
		Assert.assertTrue("Representations must contain mediaRepresentation1", media1.getRepresentations().contains(mediaRepresentation1));
165
		media1.removeRepresentation(mediaRepresentation1);
166
		Assert.assertFalse("Representations must not contain mediaRepresentation1", media1.getRepresentations().contains(mediaRepresentation1));
167
		Assert.assertEquals("Number of representations must be 1", 1, media1.getRepresentations().size());
168
		media1.removeRepresentation(mediaRepresentation2);
169
		Assert.assertFalse("Representations must not contain mediaRepresentation2", media1.getRepresentations().contains(mediaRepresentation2));
170
		Assert.assertEquals("Number of representations must be 0", 0, media1.getRepresentations().size());
171
	}
172

  
173
	/**
174
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#addRights(eu.etaxonomy.cdm.model.media.Rights)}.
175
	 */
176
	@Test
177
	public void testAddRights() {
178
		Assert.assertTrue("Rights must contain rights1", media1.getRights().contains(rights1));
179
	}
180

  
181
	/**
182
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#removeRights(eu.etaxonomy.cdm.model.media.Rights)}.
183
	 */
184
	@Test
185
	public void testRemoveRights() {
186
		Assert.assertTrue("Rights must contain rights1", media1.getRights().contains(rights1));
187
		media1.removeRights(rights1);
188
		Assert.assertFalse("Rights must not contain rights1", media1.getRights().contains(rights1));
189
		Assert.assertEquals("Number of rights must be 0", 0, media1.getRights().size());	
190
	}
191

  
192
	/**
193
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#addTitle(eu.etaxonomy.cdm.model.common.LanguageString)}.
194
	 */
195
	@Test
196
	public void testAddTitle() {
197
		Assert.assertSame("Title must be the same", languageString2, media1.getAllTitles().get(Language.DEFAULT()) );
198
	}
199

  
200
	/**
201
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#removeTitle(eu.etaxonomy.cdm.model.common.Language)}.
202
	 */
203
	@Test
204
	public void testRemoveTitle() {
205
		Assert.assertSame("Title must be the same", languageString2, media1.getAllTitles().get(Language.DEFAULT()) );
206
		media1.removeTitle(Language.GERMAN());
207
		Assert.assertEquals("Number of titles must be 1", 1, media1.getAllTitles().size());
208
		media1.removeTitle(Language.DEFAULT());
209
		Assert.assertEquals("Number of titles must be 0", 0, media1.getAllTitles().size());
210
		Assert.assertFalse("Title must not contain languageString2", languageString2.equals(media1.getAllTitles().get(Language.DEFAULT())));
211
	}
212

  
213
	/**
214
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#getMediaCreated()}.
215
	 */
216
	@Test
217
	public void testGetMediaCreated() {
218
		Assert.assertEquals("Media created year must be 2002", 2002, media1.getMediaCreated().getYear());
219
		
220
	}
221

  
222
	/**
223
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#getDescription()}.
224
	 */
225
	@Test
226
	public void testGetDescription() {
227
		Assert.assertTrue("Clone must have a default language description", media1.getAllDescriptions().containsKey(Language.DEFAULT()));
228
		Assert.assertSame("Description1 must be the same", languageString1, media1.getAllDescriptions().get(Language.DEFAULT()) );
229
	}
230

  
231
	/**
232
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#addDescription(eu.etaxonomy.cdm.model.common.LanguageString)}.
233
	 */
234
	@Test
235
	public void testAddDescriptionLanguageString() {
236
		Assert.assertEquals("Number of descriptions must be 2", 2, media1.getAllDescriptions().size() );
237
		Assert.assertTrue("Clone must have a default language description", media1.getAllDescriptions().containsKey(Language.DEFAULT()));
238
		Assert.assertSame("Description1 must be the same", languageString1, media1.getAllDescriptions().get(Language.DEFAULT()) );
239
		media1.addDescription(languageString2);
240
		Assert.assertEquals("Number of descriptions must be 2", 2, media1.getAllDescriptions().size() );
241
		Assert.assertEquals("Default language description must be languageString2", languageString2, media1.getAllDescriptions().get(Language.DEFAULT()) );
242
	}
243

  
244
	/**
245
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#addDescription(java.lang.String, eu.etaxonomy.cdm.model.common.Language)}.
246
	 */
247
	@Test
248
	public void testAddDescriptionStringLanguage() {
249
		Assert.assertTrue("Clone must have a german language description", media1.getAllDescriptions().containsKey(Language.GERMAN()));
250
		Assert.assertSame("Description1 must be the same", "media1Desc2", media1.getAllDescriptions().get(Language.GERMAN()).getText() );
251
		media1.addDescription("testDesc", Language.DEFAULT());
252
		Assert.assertEquals("Number of descriptions must be 2", 2, media1.getAllDescriptions().size() );
253
		media1.addDescription("testDesc2", Language.DEFAULT());
254
		Assert.assertEquals("Number of descriptions must be 2", 2, media1.getAllDescriptions().size() );
255
		Assert.assertSame("Default language description must be 'testDesc2'", "testDesc2", media1.getAllDescriptions().get(Language.DEFAULT()).getText() );
256
	}
257

  
258
	/**
259
	 * Test method for {@link eu.etaxonomy.cdm.model.media.Media#removeDescription(eu.etaxonomy.cdm.model.common.Language)}.
260
	 */
261
	@Test
262
	public void testRemoveDescription() {
263
		Assert.assertEquals("Number of descriptions must be 2", 2, media1.getAllDescriptions().size() );
264
		Assert.assertTrue("Clone must have a default language description", media1.getAllDescriptions().containsKey(Language.DEFAULT()));
265
		Assert.assertSame("Description1 must be the same", languageString1, media1.getAllDescriptions().get(Language.DEFAULT()) );
266
		media1.removeDescription(Language.JAPANESE());
267
		Assert.assertEquals("Number of descriptions must be 2", 2, media1.getAllDescriptions().size() );
268
		media1.removeDescription(Language.DEFAULT());
269
		Assert.assertEquals("Number of descriptions must be 1", 1, media1.getAllDescriptions().size() );
270
		media1.removeDescription(Language.DEFAULT());
271
		Assert.assertEquals("Number of descriptions must be 1", 1, media1.getAllDescriptions().size() );
272
		media1.removeDescription(Language.GERMAN());
273
		Assert.assertEquals("Number of descriptions must be 0", 0, media1.getAllDescriptions().size() );
274
	}
275
	
276
	@Test
277
	public void testfindBestMatchingRepresentation() {
278
		String[] mimetypes = {".*"};
279
		Assert.assertEquals(mediaRepresentation1, MediaUtils.findBestMatchingRepresentation(media1, 100, 100, 100, mimetypes));
280
		Assert.assertEquals(mediaRepresentation2, MediaUtils.findBestMatchingRepresentation(media1,1000, 100, 100, mimetypes));
281
	
282
	}
38
    @SuppressWarnings("unused")
39
    private static final Logger logger = Logger.getLogger(MediaTest.class);
40

  
41
    private Media media1;
42
    private Team team1;
43
    private MediaRepresentation mediaRepresentation1;
44
    private MediaRepresentation mediaRepresentation2;
45
    private MediaRepresentationPart mediaRepresentationPart1;
46
    private MediaRepresentationPart mediaRepresentationPart2;
47
    private LanguageString languageString1;
48
    private final String germanDescription = "media1Desc2";
49
    private Rights rights1;
50
    private LanguageString languageString2;
51
    private static URI uriString1;
52
    private static URI uriString2;
53

  
54
    /**
55
     * @throws java.lang.Exception
56
     */
57
    @BeforeClass
58
    public static void setUpBeforeClass() throws Exception {
59
        DefaultTermInitializer termInitializer = new DefaultTermInitializer();
60
        termInitializer.initialize();
61
        try {
62
            uriString1 = new URI("http://Pathtoimage1/");
63
            uriString2 = new URI("http://Path_to_image_2/");
64
        } catch (Exception e) {
65
            e.printStackTrace();
66
            Assert.fail("Error in URI syntax");
67
        }
68

  
69
    }
70

  
71
    /**
72
     * @throws java.lang.Exception
73
     */
74
    @AfterClass
75
    public static void tearDownAfterClass() throws Exception {
76
    }
77

  
78
    /**
79
     * @throws java.lang.Exception
80
     */
81
    @Before
82
    public void setUp() throws Exception {
83
        media1 = Media.NewInstance();
84
        team1 = Team.NewInstance();
85
        media1.setArtist(team1);
86
        media1.setMediaCreated(new DateTime(2002, 1,1,0,0,0,0));
87
        languageString1 = LanguageString.NewInstance("media1Desc", Language.DEFAULT());
88
        media1.addDescription(languageString1);
89
        media1.addDescription("media1Desc2", Language.GERMAN());
90
        mediaRepresentation1 = MediaRepresentation.NewInstance();
91
        mediaRepresentation2 = MediaRepresentation.NewInstance();
92
        mediaRepresentation1.setMimeType("MimeType1");
93
        mediaRepresentation2.setMimeType("MimeType1");
94
        mediaRepresentationPart1 = ImageFile.NewInstance(uriString1, 100);
95
        mediaRepresentationPart2 = ImageFile.NewInstance(uriString2, 1000);
96
        ((ImageFile) mediaRepresentationPart1).setHeight(100);
97
        ((ImageFile) mediaRepresentationPart1).setWidth(100);
98

  
99
        ((ImageFile) mediaRepresentationPart2).setHeight(100);
100
        ((ImageFile) mediaRepresentationPart2).setWidth(100);
101

  
102
        mediaRepresentation1.addRepresentationPart(mediaRepresentationPart1);
103
        mediaRepresentation2.addRepresentationPart(mediaRepresentationPart2);
104
        media1.addRepresentation(mediaRepresentation1);
105
        media1.addRepresentation(mediaRepresentation2);
106
        rights1 = Rights.NewInstance();
107
        media1.addRights(rights1);
108

  
109
        languageString2 = LanguageString.NewInstance("media1Title", Language.DEFAULT());
110
        media1.putTitle(languageString2);
111

  
112
    }
113

  
114
    /**
115
     * @throws java.lang.Exception
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff