001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.registry;
016    
017    import com.liferay.portal.kernel.util.PredicateFilter;
018    import com.liferay.registry.Registry;
019    import com.liferay.registry.RegistryUtil;
020    import com.liferay.registry.ServiceReference;
021    import com.liferay.registry.ServiceTrackerCustomizer;
022    
023    /**
024     * @author Roberto D??az
025     */
026    public class ServiceTrackerCustomizerFactory {
027    
028            public static <S> ServiceTrackerCustomizer<S, S> create(
029                    final PredicateFilter<S> predicateFilter) {
030    
031                    return new ServiceTrackerCustomizer<S, S>() {
032    
033                            @Override
034                            public S addingService(ServiceReference<S> serviceReference) {
035                                    Registry registry = RegistryUtil.getRegistry();
036    
037                                    S service = registry.getService(serviceReference);
038    
039                                    try {
040                                            if (predicateFilter.filter(service)) {
041                                                    return service;
042                                            }
043                                    }
044                                    catch (Exception e) {
045                                    }
046    
047                                    registry.ungetService(serviceReference);
048    
049                                    return null;
050                            }
051    
052                            @Override
053                            public void removedService(
054                                    ServiceReference<S> serviceReference, S service) {
055                            }
056    
057                            @Override
058                            public void modifiedService(
059                                    ServiceReference<S> serviceReference, S service) {
060    
061                                    Registry registry = RegistryUtil.getRegistry();
062    
063                                    registry.ungetService(serviceReference);
064                            }
065                    };
066            }
067    
068    }