001// Copyright 2004, 2005 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry.util.io;
016
017import org.apache.hivemind.ApplicationRuntimeException;
018import org.apache.tapestry.Tapestry;
019import org.apache.tapestry.services.DataSqueezer;
020import org.apache.tapestry.util.ComponentAddress;
021
022/**
023 * Squeezes a org.apache.tapestry.ComponentAddress.
024 * 
025 * @author mindbridge
026 * @since 2.2
027 */
028
029public class ComponentAddressAdaptor implements SqueezeAdaptor
030{
031    private static final String PREFIX = "A";
032
033    private static final char SEPARATOR = ',';
034
035    public String getPrefix()
036    {
037        return PREFIX;
038    }
039
040    public Class getDataClass()
041    {
042        return ComponentAddress.class;
043    }
044
045    public String squeeze(DataSqueezer squeezer, Object data)
046    {
047        ComponentAddress address = (ComponentAddress) data;
048
049        // a 'null' id path is encoded as an empty string
050        String idPath = address.getIdPath();
051        if (idPath == null)
052            idPath = "";
053
054        return PREFIX + address.getPageName() + SEPARATOR + idPath;
055    }
056
057    public Object unsqueeze(DataSqueezer squeezer, String string)
058    {
059        int separator = string.indexOf(SEPARATOR);
060        if (separator < 0)
061            throw new ApplicationRuntimeException(Tapestry
062                    .getMessage("ComponentAddressAdaptor.no-separator"));
063
064        String pageName = string.substring(1, separator);
065        String idPath = string.substring(separator + 1);
066        if (idPath.equals(""))
067            idPath = null;
068
069        return new ComponentAddress(pageName, idPath);
070    }
071
072}