001// Copyright 2012 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.tapestry5.internal.services; 016 017import org.apache.tapestry5.commons.util.CollectionFactory; 018import org.apache.tapestry5.ioc.internal.util.InternalUtils; 019import org.apache.tapestry5.json.JSONArray; 020import org.apache.tapestry5.services.javascript.InitializationPriority; 021 022import java.util.ArrayList; 023import java.util.List; 024import java.util.Map; 025import java.util.Set; 026 027public class ModuleInitsManager 028{ 029 private final Set<String> pureInits = CollectionFactory.newSet(); 030 031 private final Map<InitializationPriority, List<Object>> inits = CollectionFactory.newMap(); 032 033 private int initCount; 034 035 public void addInitialization(InitializationPriority priority, String moduleName, String functionName, JSONArray arguments) 036 { 037 assert priority != null; 038 assert InternalUtils.isNonBlank(moduleName); 039 040 String name = functionName == null ? moduleName : moduleName + ":" + functionName; 041 042 if ((arguments == null || arguments.length() == 0)) 043 { 044 if (pureInits.contains(name)) 045 { 046 // A degenerate case is a pure init added repeatedly with different priorities. That isn't handled: 047 // the first priority wins. 048 return; 049 } 050 051 pureInits.add(name); 052 InternalUtils.addToMapList(inits, priority, name); 053 } else 054 { 055 056 JSONArray init = new JSONArray(); 057 058 init.put(name); 059 060 init.putAll(arguments); 061 062 InternalUtils.addToMapList(inits, priority, init); 063 } 064 065 initCount++; 066 } 067 068 /** 069 * Returns all previously added inits, sorted by {@link InitializationPriority}, then by order in which they 070 * were added. 071 */ 072 public List<?> getSortedInits() 073 { 074 List<Object> result = new ArrayList<Object>(initCount); 075 076 for (InitializationPriority p : InitializationPriority.values()) 077 { 078 List<Object> initsForPriority = inits.get(p); 079 080 if (initsForPriority != null) 081 { 082 result.addAll(initsForPriority); 083 } 084 } 085 086 return result; 087 } 088}