/*
* Copyright 2009-2010 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.dwr;
import org.directwebremoting.ConversionException;
import org.directwebremoting.extend.InboundVariable;
import org.directwebremoting.extend.NonNestedOutboundVariable;
import org.directwebremoting.extend.OutboundContext;
import org.directwebremoting.extend.OutboundVariable;
import org.directwebremoting.util.LocalUtil;
import org.internna.iwebmvc.IWebMvcException;
import org.internna.iwebmvc.crypto.Cipherer;
import org.internna.iwebmvc.crypto.Decipherer;
import org.internna.iwebmvc.model.UUID;
import org.internna.iwebmvc.utils.Assert;
import org.springframework.beans.factory.annotation.Required;
import static org.internna.iwebmvc.utils.StringUtils.hasText;
/**
* DWR converter for UUID objects from/to an encrypted String
*
* @author Jose Noheda
*/
public class EncryptedUUIDConverter extends AbstractConverter {
private Cipherer cipherer;
private Decipherer decipherer;
@Required public void setCipherer(Cipherer cipherer) {
this.cipherer = cipherer;
}
@Required public void setDecipherer(Decipherer decipherer) {
this.decipherer = decipherer;
}
@Override public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
if (!data.isNull()) {
try {
String id = LocalUtil.urlDecode(data.getValue());
if (hasText(id)) {
Assert.isEncrypted(decipherer, id);
return new UUID(decipherer.decrypt(id));
}
} catch (Exception e) {
throw new ConversionException(paramType, new IWebMvcException("Could not convert UUID from: " + data, e));
}
}
return null;
}
@Override public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws ConversionException {
try {
return new NonNestedOutboundVariable(data == null ? "null" : "'" + cipherer.encrypt(((UUID) data).toString()) + "'");
} catch (Exception e) {
throw new ConversionException(data.getClass(), new IWebMvcException("Could not generate encrypted UUID from: " + data, e));
}
}
}