Search in sources :

Example 16 with Factory

use of com.opensymphony.xwork2.inject.Factory in project onebusaway-application-modules by camsys.

the class MultiActionProxyFactory method setActionMappers.

@Inject(MAPPINGS)
public void setActionMappers(String list) {
    if (list != null) {
        String[] tokens = list.split(",");
        for (String token : tokens) {
            String[] kvp = token.split("=");
            String key = kvp[0];
            String name = kvp[1];
            ActionProxyFactory factory = container.getInstance(ActionProxyFactory.class, name);
            if (factory != null) {
                _prefixedActionProxyFactories.add(new Prefixed<ActionProxyFactory>(key, factory));
            } else {
                throw new IllegalStateException("unknown ActionProxyFactory " + name);
            }
        }
    }
}
Also used : ActionProxyFactory(com.opensymphony.xwork2.ActionProxyFactory) DefaultActionProxyFactory(com.opensymphony.xwork2.DefaultActionProxyFactory) Inject(com.opensymphony.xwork2.inject.Inject)

Example 17 with Factory

use of com.opensymphony.xwork2.inject.Factory in project ipt by gbif.

the class TranslationActionTest method setup.

@BeforeEach
public void setup() throws Exception {
    // mock needed managers
    SimpleTextProvider mockTextProvider = mock(SimpleTextProvider.class);
    LocaleProviderFactory localeProviderFactory = new DefaultLocaleProviderFactory();
    AppConfig mockCfg = mock(AppConfig.class);
    ResourceManager mockResourceManager = mock(ResourceManager.class);
    SourceManager mockSourceManager = mock(SourceManager.class);
    VocabulariesManager mockVocabManager = mock(VocabulariesManager.class);
    TranslationAction.Translation translation = new TranslationAction.Translation();
    RegistrationManager mockRegistrationManager = mock(RegistrationManager.class);
    Container container = mock(Container.class);
    // mock getting list of values back for BasisOfRecord field/column in source
    Set<String> values = new LinkedHashSet<>();
    values.add("spe");
    values.add("obs");
    values.add("fos");
    when(mockSourceManager.inspectColumn(any(SourceBase.class), anyInt(), anyInt(), anyInt())).thenReturn(values);
    // mock getI18nVocab - only called in prepare()
    Map<String, String> mockVocab = new HashMap<>();
    mockVocab.put("NomenclaturalChecklist", "Nomenclatural Checklist");
    mockVocab.put("MachineObservation", "Machine Observation");
    when(mockVocabManager.getI18nVocab(anyString(), anyString(), anyBoolean())).thenReturn(mockVocab);
    // initialize new Resource
    Resource resource = new Resource();
    String resourceShortName = "TestResource";
    resource.setShortname(resourceShortName);
    // initialize new ExtensionMapping
    ExtensionMapping mapping = new ExtensionMapping();
    // add source to mapping
    mapping.setSource(new TextFileSource());
    ExtensionFactory factory = ExtensionFactoryTest.getFactory();
    Extension e = factory.build(ExtensionFactoryTest.class.getResourceAsStream("/extensions/dwc_occurrence.xml"));
    // ensure rowType for Extension is set
    if (e.getRowType() == null) {
        e.setRowType(Constants.DWC_ROWTYPE_TAXON);
    }
    // add extension to ExtensionMapping
    mapping.setExtension(e);
    // create map of source value
    TreeMap<String, String> sourceValues = new TreeMap<>();
    sourceValues.put("k1", "spe");
    sourceValues.put("k2", "obs");
    // create map of translation values
    TreeMap<String, String> translatedValues = new TreeMap<>();
    translatedValues.put("k1", "Preserved Specimen");
    translatedValues.put("k2", "observation");
    // create map of translations that get persisted
    Map<String, String> persistedTranslations = new HashMap<>();
    persistedTranslations.put("spe", "Preserved Specimen");
    persistedTranslations.put("obs", "observation");
    // initialize PropertyMapping for BasisOfRecord term
    PropertyMapping field = new PropertyMapping();
    // set ConceptTerm
    field.setTerm(DwcTerm.basisOfRecord);
    // set index
    field.setIndex(1);
    // add translations to field
    field.setTranslation(persistedTranslations);
    // add set of PropertyMapping, including field, to ExtensionMapping
    Set<PropertyMapping> fields = new TreeSet<>();
    fields.add(field);
    mapping.setFields(fields);
    // add ExtensionMapping to resource, with mapping ID 0
    List<ExtensionMapping> mappings = new LinkedList<>();
    mappings.add(mapping);
    resource.setMappings(mappings);
    // mock resourceManager.get - called only in ManagerBaseAction.prepare()
    when(mockResourceManager.get(anyString())).thenReturn(resource);
    // mock a locale provider
    when(container.getInstance(LocaleProviderFactory.class)).thenReturn(localeProviderFactory);
    // create mock Action
    action = new TranslationAction(mockTextProvider, mockCfg, mockRegistrationManager, mockResourceManager, mockSourceManager, mockVocabManager, translation);
    action.setContainer(container);
    // initialize ExtensionProperty representing BasisOfRecord field on Occurrence core Extension
    ExtensionProperty property = mapping.getExtension().getProperty(field.getTerm());
    // set a vocabulary for the BasisOfRecord field
    // mock creation of BasisOfRecord vocabulary
    VocabularyConcept concept = new VocabularyConcept();
    concept.setIdentifier("PreservedSpecimen");
    concept.setUri("http://rs.tdwg.org/dwc/dwctype/PreservedSpecimen");
    // preferred titles
    Set<VocabularyTerm> preferredTerms = new HashSet<>();
    VocabularyTerm term = new VocabularyTerm();
    term.setLang("en");
    term.setTitle("Preserved Specimen");
    preferredTerms.add(term);
    concept.setPreferredTerms(preferredTerms);
    // alternative titles
    Set<VocabularyTerm> alternateTerms = new HashSet<>();
    term = new VocabularyTerm();
    term.setLang("en");
    term.setTitle("Conserved Specimen");
    alternateTerms.add(term);
    concept.setAlternativeTerms(alternateTerms);
    Vocabulary vocab = new Vocabulary();
    List<VocabularyConcept> concepts = new ArrayList<>();
    concepts.add(concept);
    vocab.setConcepts(concepts);
    vocab.setUriString("http://rs.gbif.org/vocabulary/dwc/basis_of_record");
    property.setVocabulary(vocab);
    // create sessionScoped Translation
    // populate sessionScoped Translation with translations
    action.getTrans().setTmap(mapping.getExtension().getRowType(), property, sourceValues, translatedValues);
    // set various properties on Action
    action.setField(field);
    action.setExtensionMapping(mapping);
    action.setProperty(property);
    // mock servlet request
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    // the mapping id is 0 - relates to resource's List<ExtensionMapping> mappings
    when(mockRequest.getParameter(TranslationAction.REQ_PARAM_MAPPINGID)).thenReturn("0");
    when(mockRequest.getParameter(TranslationAction.REQ_PARAM_ROWTYPE)).thenReturn(Constants.DWC_ROWTYPE_OCCURRENCE);
    when(mockRequest.getParameter(TranslationAction.REQ_PARAM_TERM)).thenReturn(DwcTerm.basisOfRecord.qualifiedName());
    when(mockRequest.getParameter(Constants.REQ_PARAM_RESOURCE)).thenReturn(resourceShortName);
    action.setServletRequest(mockRequest);
    // ensure the resource is set
    action.setResource(resource);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Vocabulary(org.gbif.ipt.model.Vocabulary) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) HttpServletRequest(javax.servlet.http.HttpServletRequest) Container(com.opensymphony.xwork2.inject.Container) TreeSet(java.util.TreeSet) LocaleProviderFactory(com.opensymphony.xwork2.LocaleProviderFactory) DefaultLocaleProviderFactory(com.opensymphony.xwork2.DefaultLocaleProviderFactory) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) AppConfig(org.gbif.ipt.config.AppConfig) RegistrationManager(org.gbif.ipt.service.admin.RegistrationManager) ExtensionFactoryTest(org.gbif.ipt.model.factory.ExtensionFactoryTest) SourceBase(org.gbif.ipt.model.SourceBase) Resource(org.gbif.ipt.model.Resource) VocabularyConcept(org.gbif.ipt.model.VocabularyConcept) TextFileSource(org.gbif.ipt.model.TextFileSource) ResourceManager(org.gbif.ipt.service.manage.ResourceManager) VocabulariesManager(org.gbif.ipt.service.admin.VocabulariesManager) TreeMap(java.util.TreeMap) LinkedList(java.util.LinkedList) Extension(org.gbif.ipt.model.Extension) ExtensionProperty(org.gbif.ipt.model.ExtensionProperty) ExtensionMapping(org.gbif.ipt.model.ExtensionMapping) ExtensionFactory(org.gbif.ipt.model.factory.ExtensionFactory) VocabularyTerm(org.gbif.ipt.model.VocabularyTerm) SimpleTextProvider(org.gbif.ipt.struts2.SimpleTextProvider) PropertyMapping(org.gbif.ipt.model.PropertyMapping) SourceManager(org.gbif.ipt.service.manage.SourceManager) DefaultLocaleProviderFactory(com.opensymphony.xwork2.DefaultLocaleProviderFactory) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 18 with Factory

use of com.opensymphony.xwork2.inject.Factory in project struts by apache.

the class FreemarkerResult method createModel.

/**
 * Build the instance of the ScopesHashModel, including JspTagLib support
 * <p>
 * Objects added to the model are
 * </p>
 *
 * <ul>
 * <li>Application - servlet context attributes hash model
 * <li>JspTaglibs - jsp tag lib factory model
 * <li>Request - request attributes hash model
 * <li>Session - session attributes hash model
 * <li>request - the HttpServletRequst object for direct access
 * <li>response - the HttpServletResponse object for direct access
 * <li>stack - the OgnLValueStack instance for direct access
 * <li>ognl - the instance of the OgnlTool
 * <li>action - the action itself
 * <li>exception - optional : the JSP or Servlet exception as per the servlet spec (for JSP Exception pages)
 * <li>struts - instance of the StrutsUtil class
 * </ul>
 *
 * @return TemplateModel returns the created template model
 * @throws TemplateModelException in case of errors during creating the model
 */
protected TemplateModel createModel() throws TemplateModelException {
    ServletContext servletContext = ServletActionContext.getServletContext();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    ValueStack stack = ActionContext.getContext().getValueStack();
    Object action = null;
    // Added for NullPointException
    if (invocation != null)
        action = invocation.getAction();
    return freemarkerManager.buildTemplateModel(stack, action, servletContext, request, response, wrapper);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ValueStack(com.opensymphony.xwork2.util.ValueStack) ServletContext(javax.servlet.ServletContext) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 19 with Factory

use of com.opensymphony.xwork2.inject.Factory in project struts by apache.

the class PackageBasedActionConfigBuilder method buildConfiguration.

@SuppressWarnings("unchecked")
protected void buildConfiguration(Set<Class> classes) {
    Map<String, PackageConfig.Builder> packageConfigs = new HashMap<>();
    for (Class<?> actionClass : classes) {
        Actions actionsAnnotation = actionClass.getAnnotation(Actions.class);
        Action actionAnnotation = actionClass.getAnnotation(Action.class);
        // Skip classes that can't be instantiated
        if (cannotInstantiate(actionClass)) {
            LOG.trace("Class [{}] did not pass the instantiation test and will be ignored", actionClass.getName());
            continue;
        }
        if (eagerLoading) {
            // Tell the ObjectFactory about this class
            try {
                objectFactory.getClassInstance(actionClass.getName());
            } catch (ClassNotFoundException e) {
                LOG.error("Object Factory was unable to load class [{}]", actionClass.getName(), e);
                throw new StrutsException("Object Factory was unable to load class " + actionClass.getName(), e);
            }
        }
        // Determine the action package
        String actionPackage = actionClass.getPackage().getName();
        LOG.debug("Processing class [{}] in package [{}]", actionClass.getName(), actionPackage);
        Set<String> allowedMethods = getAllowedMethods(actionClass);
        // Determine the default namespace and action name
        List<String> namespaces = determineActionNamespace(actionClass);
        for (String namespace : namespaces) {
            String defaultActionName = determineActionName(actionClass);
            PackageConfig.Builder defaultPackageConfig = getPackageConfig(packageConfigs, namespace, actionPackage, actionClass, null);
            // Verify that the annotations have no errors and also determine if the default action
            // configuration should still be built or not.
            Map<String, List<Action>> map = getActionAnnotations(actionClass);
            Set<String> actionNames = new HashSet<>();
            boolean hasDefaultMethod = ReflectionTools.containsMethod(actionClass, DEFAULT_METHOD);
            if (!map.containsKey(DEFAULT_METHOD) && hasDefaultMethod && actionAnnotation == null && actionsAnnotation == null && (alwaysMapExecute || map.isEmpty())) {
                boolean found = false;
                for (List<Action> actions : map.values()) {
                    for (Action action : actions) {
                        // Check if there are duplicate action names in the annotations.
                        String actionName = action.value().equals(Action.DEFAULT_VALUE) ? defaultActionName : action.value();
                        if (actionNames.contains(actionName)) {
                            throw new ConfigurationException("The action class [" + actionClass + "] contains two methods with an action name annotation whose value " + "is the same (they both might be empty as well).");
                        } else {
                            actionNames.add(actionName);
                        }
                        // Check this annotation is the default action
                        if (action.value().equals(Action.DEFAULT_VALUE)) {
                            found = true;
                        }
                    }
                }
                // Build the default
                if (!found) {
                    createActionConfig(defaultPackageConfig, actionClass, defaultActionName, DEFAULT_METHOD, null, allowedMethods);
                }
            }
            // Build the actions for the annotations
            for (Map.Entry<String, List<Action>> entry : map.entrySet()) {
                String method = entry.getKey();
                List<Action> actions = entry.getValue();
                for (Action action : actions) {
                    PackageConfig.Builder pkgCfg = defaultPackageConfig;
                    if (action.value().contains("/") && !slashesInActionNames) {
                        pkgCfg = getPackageConfig(packageConfigs, namespace, actionPackage, actionClass, action);
                    }
                    createActionConfig(pkgCfg, actionClass, defaultActionName, method, action, allowedMethods);
                }
            }
            // where the action mapper is the one that finds the right method at runtime
            if (map.isEmpty() && mapAllMatches && actionAnnotation == null && actionsAnnotation == null) {
                createActionConfig(defaultPackageConfig, actionClass, defaultActionName, null, actionAnnotation, allowedMethods);
            }
            // if there are @Actions or @Action at the class level, create the mappings for them
            String methodName = hasDefaultMethod ? DEFAULT_METHOD : null;
            if (actionsAnnotation != null) {
                List<Action> actionAnnotations = checkActionsAnnotation(actionsAnnotation);
                for (Action actionAnnotation2 : actionAnnotations) createActionConfig(defaultPackageConfig, actionClass, defaultActionName, methodName, actionAnnotation2, allowedMethods);
            } else if (actionAnnotation != null)
                createActionConfig(defaultPackageConfig, actionClass, defaultActionName, methodName, actionAnnotation, allowedMethods);
        }
    }
    buildIndexActions(packageConfigs);
    // Add the new actions to the configuration
    Set<String> packageNames = packageConfigs.keySet();
    for (String packageName : packageNames) {
        configuration.addPackageConfig(packageName, packageConfigs.get(packageName).build());
    }
}
Also used : StrutsException(org.apache.struts2.StrutsException) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException)

Example 20 with Factory

use of com.opensymphony.xwork2.inject.Factory in project struts by apache.

the class JavaTemplateEngine method setThemeClasses.

/**
 * Allows for providing custom theme classes (implementations of the org.apache.struts2.views.java.Theme) interface
 * for custom rendering of tags using the javatemplates engine
 *
 * @param themeClasses a comma delimited list of custom theme class names
 */
@Inject(value = JavaTemplateConstants.STRUTS_JAVATEMPLATES_CUSTOM_THEMES, required = false)
public void setThemeClasses(String themeClasses) {
    StringTokenizer customThemes = new StringTokenizer(themeClasses, ",");
    while (customThemes.hasMoreTokens()) {
        String themeClass = customThemes.nextToken().trim();
        try {
            LOG.info("Registering custom theme [{}] to javatemplates engine", themeClass);
            ObjectFactory factory = ActionContext.getContext().getContainer().getInstance(ObjectFactory.class);
            Theme theme = (Theme) factory.buildBean(themeClass, new HashMap<String, Object>());
            themes.add(theme);
        } catch (ClassCastException cce) {
            LOG.error("Invalid java them class [{}]. Class does not implement 'org.apache.struts2.views.java.Theme' interface", themeClass, cce);
        } catch (ClassNotFoundException cnf) {
            LOG.error("Invalid java theme class [{}]. Class not found!", themeClass, cnf);
        } catch (Exception e) {
            LOG.error("Could not find messages file [{}].properties. Skipping!", themeClass, e);
        }
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) ObjectFactory(com.opensymphony.xwork2.ObjectFactory) HashMap(java.util.HashMap) SimpleTheme(org.apache.struts2.views.java.simple.SimpleTheme) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) StrutsException(org.apache.struts2.StrutsException) Inject(com.opensymphony.xwork2.inject.Inject)

Aggregations

ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)10 ObjectFactory (com.opensymphony.xwork2.ObjectFactory)7 ValueStack (com.opensymphony.xwork2.util.ValueStack)5 DefaultFileManagerFactory (com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory)5 ActionProxyFactory (com.opensymphony.xwork2.ActionProxyFactory)4 InterceptorMapping (com.opensymphony.xwork2.config.entities.InterceptorMapping)4 Context (com.opensymphony.xwork2.inject.Context)4 ArrayList (java.util.ArrayList)4 StrutsException (org.apache.struts2.StrutsException)4 ActionContext (com.opensymphony.xwork2.ActionContext)3 DefaultActionProxyFactory (com.opensymphony.xwork2.DefaultActionProxyFactory)3 FileManager (com.opensymphony.xwork2.FileManager)3 ContainerBuilder (com.opensymphony.xwork2.inject.ContainerBuilder)3 Factory (com.opensymphony.xwork2.inject.Factory)3 StubConfigurationProvider (com.opensymphony.xwork2.test.StubConfigurationProvider)3 DefaultFileManager (com.opensymphony.xwork2.util.fs.DefaultFileManager)3 LocatableProperties (com.opensymphony.xwork2.util.location.LocatableProperties)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3