001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 * $Id$
012 */
013
014package org.nuxeo.runtime.model.impl;
015
016import java.io.IOException;
017import java.io.InputStream;
018
019import org.nuxeo.common.xmap.Context;
020import org.nuxeo.common.xmap.XMap;
021import org.nuxeo.common.xmap.XValueFactory;
022import org.nuxeo.runtime.Version;
023import org.nuxeo.runtime.model.ComponentName;
024import org.nuxeo.runtime.model.RuntimeContext;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class ComponentDescriptorReader {
030
031    private final XMap xmap;
032
033    public ComponentDescriptorReader() {
034        xmap = new XMap();
035        xmap.setValueFactory(ComponentName.class, new XValueFactory() {
036            @Override
037            public Object deserialize(Context context, String value) {
038                return new ComponentName(value);
039            }
040
041            @Override
042            public String serialize(Context context, Object value) {
043                if (value != null) {
044                    return value.toString();
045                }
046                return null;
047            }
048        });
049        xmap.setValueFactory(Version.class, new XValueFactory() {
050            @Override
051            public Object deserialize(Context context, String value) {
052                return Version.parseString(value);
053            }
054
055            @Override
056            public String serialize(Context context, Object value) {
057                if (value != null) {
058                    return value.toString();
059                }
060                return null;
061            }
062        });
063        xmap.register(RegistrationInfoImpl.class);
064    }
065
066    public RegistrationInfoImpl read(RuntimeContext ctx, InputStream in) throws IOException {
067        Object[] result = xmap.loadAll(new XMapContext(ctx), in);
068        if (result.length > 0) {
069            return (RegistrationInfoImpl) result[0];
070        }
071        return null;
072    }
073
074}