/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache license, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.internna.iwebmvc.spring.binding;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.internna.iwebmvc.core.crypto.Decipherer;
import org.internna.iwebmvc.model.core.Audio;
import org.internna.iwebmvc.model.core.PlayList;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.utils.StringUtils;
/**
* Binder for Multiple Audio entity.
*
* @author Jose Noheda
* @since 1.0
*/
public class PlayListBinder extends PropertyEditorSupport {
private static final Log log = LogFactory.getLog(PlayListBinder.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
private Decipherer decipherer;
public PlayListBinder(Decipherer decipherer) {
this.decipherer = decipherer;
}
@SuppressWarnings("unchecked")
public Audio getAudio(String text) throws IllegalArgumentException {
Audio doc = new Audio();
Properties properties = new Properties();
try {
properties.load(IOUtils.toInputStream(text));
String uri = properties.getProperty("uri");
Assert.isEncrypted(decipherer, uri);
if (doc == null) doc = new Audio();
doc.setUri(decipherer.decrypt(uri));
doc.setMimeType(properties.getProperty("mimeType"));
doc.setIdentifier(properties.getProperty("identifier"));
doc.setCreated(dateFormat.parse(properties.getProperty("created")));
doc.setSizeInBytes(Long.parseLong(properties.getProperty("sizeInBytes")));
return doc;
} catch (Exception ex) {
if (log.isDebugEnabled()) log.debug("Could not completely bind [" + text + "] as an Audio: " + ex.getMessage());
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public void setAsText(String text) throws IllegalArgumentException {
PlayList docs = (PlayList) getValue();
if (docs == null) docs = new PlayList();
for (String doc : text.split("##")) {
if (StringUtils.hasText(doc)) {
if (doc.startsWith("-")) {
Iterator<Audio> it = docs.getPlayList().iterator();
while (it.hasNext()) {
Audio d = it.next();
if (doc.substring(1).equals(d.getUri())) it.remove();
}
} else {
Audio document = getAudio(doc);
if (document != null) docs.addAudio(document);
}
}
}
setValue(docs);
}
}