Search in sources :

Example 16 with PostConstruct

use of jakarta.annotation.PostConstruct in project rubia-forums by flashboss.

the class ViewCategory method execute.

// ui actions supported by this
// bean----------------------------------------------------------------------------------------------------
/**
 * this generates the category and its corresponding forums
 */
@PostConstruct
public void execute() {
    try {
        // try to extract categoryId
        int categoryId = -1;
        String c = getParameter(p_categoryId);
        if (c != null && c.trim().length() > 0) {
            categoryId = Integer.parseInt(c);
            // Setting flag that category has been selected.
            categorySelected = true;
        }
        // Luca Stancapiano start
        // get the forumInstanceId where this forum should be added
        int forumInstanceId = userPreferences.getForumInstanceId();
        this.forumLastPosts = forumsModule.findLastPostsOfForums(forumInstanceId);
        // setup category related data to be displayed
        if (categoryId == -1) {
            // process a default level category
            // Luca Stancapiano
            Collection<CategoryBean> cour = forumsModule.findCategoriesFetchForums(forumInstanceId);
            if (cour != null) {
                for (CategoryBean currentCategory : cour) processCategory(currentCategory);
            }
        } else {
            // process the specifed category
            CategoryBean currentCategory = forumsModule.findCategoryById(categoryId);
            if (currentCategory != null) {
                processCategory(currentCategory);
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}
Also used : CategoryBean(it.vige.rubia.dto.CategoryBean) JSFUtil.handleException(it.vige.rubia.ui.JSFUtil.handleException) PostConstruct(jakarta.annotation.PostConstruct)

Example 17 with PostConstruct

use of jakarta.annotation.PostConstruct in project rubia-forums by flashboss.

the class AdminController method startService.

/**
 * Start the admin controller as service
 */
@PostConstruct
public void startService() {
    try {
        // load the selected category if a categoryid is found
        // fetch the category to be edited/deleted
        int categoryId = -1;
        String cour = getParameter(p_categoryId);
        if (cour != null && cour.trim().length() > 0) {
            categoryId = parseInt(cour);
        }
        if (categoryId != -1) {
            CategoryBean category = null;
            try {
                category = forumsModule.findCategoryById(categoryId);
            } catch (ModuleException e) {
            // Category was deleted
            }
            if (category != null) {
                categoryName = category.getTitle();
                selectedCategory = category.getId().intValue();
            }
        }
        // load the selected forum is a forumid is found
        // fetch the forum to be edited/deleted
        int forumId = -1;
        String forumIdStr = getParameter(p_forumId);
        if (forumIdStr != null && forumIdStr.trim().length() > 0) {
            forumId = parseInt(forumIdStr);
        }
        if (forumId != -1) {
            ForumBean forum = null;
            try {
                forum = forumsModule.findForumById(forumId);
            } catch (ModuleException e) {
            // Forum was deleted
            }
            if (forum != null) {
                forumName = forum.getName();
                forumDescription = forum.getDescription();
                selectedCategory = forum.getCategory().getId().intValue();
                selectedForum = forum.getId().intValue();
            }
        }
        // Checking for editModes flags
        String editCatStr = getParameter(EDIT_CATEGORY);
        if (editCatStr != null && editCatStr.trim().length() > 0) {
            editCategoryMode = Boolean.valueOf(editCatStr).booleanValue();
        }
        String editForStr = getParameter(EDIT_FORUM);
        if (editForStr != null && editForStr.trim().length() > 0) {
            editForumMode = Boolean.valueOf(editForStr).booleanValue();
        }
        // Checking for addModes flags
        String addCatStr = getParameter(ADD_CATEGORY);
        if (addCatStr != null && addCatStr.trim().length() > 0) {
            addCategoryMode = Boolean.valueOf(addCatStr).booleanValue();
        }
        String addForStr = getParameter(ADD_FORUM);
        if (addForStr != null && addForStr.trim().length() > 0) {
            addForumMode = Boolean.valueOf(addForStr).booleanValue();
        }
    } catch (Exception e) {
        handleException(e);
    }
}
Also used : CategoryBean(it.vige.rubia.dto.CategoryBean) ForumBean(it.vige.rubia.dto.ForumBean) ModuleException(it.vige.rubia.ModuleException) JSFUtil.handleException(it.vige.rubia.ui.JSFUtil.handleException) ModuleException(it.vige.rubia.ModuleException) PostConstruct(jakarta.annotation.PostConstruct)

Example 18 with PostConstruct

use of jakarta.annotation.PostConstruct in project tomee by apache.

the class Assembler method postConstructResources.

private void postConstructResources(final Set<String> resourceIds, final ClassLoader classLoader, final Context containerSystemContext, final AppContext appContext) throws NamingException, OpenEJBException {
    final Thread thread = Thread.currentThread();
    final ClassLoader oldCl = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(classLoader);
        final List<ResourceInfo> resourceList = config.facilities.resources;
        for (final ResourceInfo resourceInfo : resourceList) {
            if (!resourceIds.contains(resourceInfo.id)) {
                continue;
            }
            if (isTemplatizedResource(resourceInfo)) {
                continue;
            }
            try {
                Class<?> clazz;
                try {
                    clazz = classLoader.loadClass(resourceInfo.className);
                } catch (final ClassNotFoundException cnfe) {
                    // custom classpath
                    clazz = containerSystemContext.lookup(OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id).getClass();
                }
                final boolean initialize = "true".equalsIgnoreCase(String.valueOf(resourceInfo.properties.remove("InitializeAfterDeployment")));
                final AnnotationFinder finder = Proxy.isProxyClass(clazz) ? null : new AnnotationFinder(new ClassesArchive(ancestors(clazz)));
                final List<Method> postConstructs = finder == null ? Collections.<Method>emptyList() : finder.findAnnotatedMethods(PostConstruct.class);
                final List<Method> preDestroys = finder == null ? Collections.<Method>emptyList() : finder.findAnnotatedMethods(PreDestroy.class);
                resourceInfo.postConstructMethods = new ArrayList<>();
                resourceInfo.preDestroyMethods = new ArrayList<>();
                addMethodsToResourceInfo(resourceInfo.postConstructMethods, PostConstruct.class, postConstructs);
                addMethodsToResourceInfo(resourceInfo.preDestroyMethods, PreDestroy.class, preDestroys);
                CreationalContext<?> creationalContext = null;
                Object originalResource = null;
                if (!postConstructs.isEmpty() || initialize) {
                    originalResource = containerSystemContext.lookup(OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id);
                    Object resource = originalResource;
                    if (resource instanceof Reference) {
                        resource = unwrapReference(resource);
                        this.bindResource(resourceInfo.id, resource, true);
                    }
                    try {
                        // wire up CDI
                        if (appContext != null && appContext.getWebBeansContext() != null) {
                            final BeanManagerImpl beanManager = appContext.getWebBeansContext().getBeanManagerImpl();
                            if (beanManager.isInUse()) {
                                creationalContext = beanManager.createCreationalContext(null);
                                OWBInjector.inject(beanManager, resource, creationalContext);
                            }
                        }
                        if (!"none".equals(resourceInfo.postConstruct)) {
                            if (resourceInfo.postConstruct != null) {
                                final Method p = clazz.getDeclaredMethod(resourceInfo.postConstruct);
                                if (!p.isAccessible()) {
                                    SetAccessible.on(p);
                                }
                                p.invoke(resource);
                            }
                            for (final Method m : postConstructs) {
                                if (!m.isAccessible()) {
                                    SetAccessible.on(m);
                                }
                                m.invoke(resource);
                            }
                        }
                    } catch (final Exception e) {
                        logger.fatal("Error calling @PostConstruct method on " + resource.getClass().getName());
                        throw new OpenEJBException(e);
                    }
                }
                if (!"none".equals(resourceInfo.preDestroy)) {
                    if (resourceInfo.preDestroy != null) {
                        final Method p = clazz.getDeclaredMethod(resourceInfo.preDestroy);
                        if (!p.isAccessible()) {
                            SetAccessible.on(p);
                        }
                        preDestroys.add(p);
                    }
                    if (!preDestroys.isEmpty() || creationalContext != null) {
                        final String name = OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id;
                        if (originalResource == null) {
                            originalResource = containerSystemContext.lookup(name);
                        }
                        this.bindResource(resourceInfo.id, new ResourceInstance(name, originalResource, preDestroys, creationalContext), true);
                    }
                }
                // log unused now for these resources now we built the resource completely and @PostConstruct can have used injected properties
                if (resourceInfo.unsetProperties != null && !isPassthroughType(resourceInfo)) {
                    final Set<String> unsetKeys = resourceInfo.unsetProperties.stringPropertyNames();
                    for (final String key : unsetKeys) {
                        // don't use keySet to auto filter txMgr for instance and not real properties!
                        unusedProperty(resourceInfo.id, logger, key);
                    }
                }
            } catch (final Exception e) {
                logger.fatal("Error calling PostConstruct method on " + resourceInfo.id);
                logger.fatal("Resource " + resourceInfo.id + " could not be initialized. Application will be undeployed.");
                throw new OpenEJBException(e);
            }
        }
    } finally {
        thread.setContextClassLoader(oldCl);
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) ConnectorReference(org.apache.openejb.core.ConnectorReference) ContextualJndiReference(org.apache.openejb.core.ivm.naming.ContextualJndiReference) JndiUrlReference(org.apache.openejb.core.ivm.naming.JndiUrlReference) Reference(org.apache.openejb.core.ivm.naming.Reference) ResourceReference(org.apache.webbeans.spi.api.ResourceReference) LazyObjectReference(org.apache.openejb.core.ivm.naming.LazyObjectReference) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) InvalidObjectException(java.io.InvalidObjectException) DefinitionException(jakarta.enterprise.inject.spi.DefinitionException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(jakarta.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) ValidationException(jakarta.validation.ValidationException) UndeployException(org.apache.openejb.UndeployException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) ContainerSystemPreDestroy(org.apache.openejb.assembler.classic.event.ContainerSystemPreDestroy) PreDestroy(jakarta.annotation.PreDestroy) PostConstruct(jakarta.annotation.PostConstruct) AnnotationFinder(org.apache.xbean.finder.AnnotationFinder)

Example 19 with PostConstruct

use of jakarta.annotation.PostConstruct in project tomee by apache.

the class ResourceInjector method invokePostConstruct.

public void invokePostConstruct() {
    boolean accessible = false;
    for (Method method : getPostConstructMethods()) {
        PostConstruct pc = method.getAnnotation(PostConstruct.class);
        if (pc != null) {
            try {
                ReflectionUtil.setAccessible(method);
                method.invoke(target);
            } catch (IllegalAccessException e) {
                LOG.log(Level.WARNING, "INJECTION_COMPLETE_NOT_VISIBLE", method);
            } catch (InvocationTargetException e) {
                LOG.log(Level.WARNING, "INJECTION_COMPLETE_THREW_EXCEPTION", e);
            } finally {
                ReflectionUtil.setAccessible(method, accessible);
            }
        }
    }
}
Also used : Method(java.lang.reflect.Method) PostConstruct(jakarta.annotation.PostConstruct) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 20 with PostConstruct

use of jakarta.annotation.PostConstruct in project tomee by apache.

the class EMailServiceImpl method init.

@PostConstruct
public void init() {
    // Properties documented here: https://wiki.apache.org/velocity/VelocityAndWeblogic
    final Properties prop = new Properties();
    prop.setProperty(VELOCITY_RESOURCE_LOADER_KEY, VELOCITY_RESOURCE_LOADER);
    prop.setProperty(VELOCITY_RESOURCE_CLASS_LOADER_KEY, VELOCITY_RESOURCE_CLASS_LOADER);
    velocityEngine = new VelocityEngine();
    velocityEngine.init(prop);
    /* Ensures that smtp authentication mechanism works as configured */
    boolean authenticate = "true".equals(mailSession.getProperty("mail.smtp.auth"));
    if (authenticate) {
        final String username = mailSession.getProperty("mail.smtp.user");
        final String password = mailSession.getProperty("mail.smtp.password");
        final URLName url = new URLName(mailSession.getProperty("mail.transport.protocol"), mailSession.getProperty("mail.smtp.host"), -1, null, username, null);
        mailSession.setPasswordAuthentication(url, new PasswordAuthentication(username, password));
    } else {
        LOGGER.warn("Using EMailService without SMTP auth configured. This might be valid, but could also be dangerous!");
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) Properties(java.util.Properties) PostConstruct(jakarta.annotation.PostConstruct)

Aggregations

PostConstruct (jakarta.annotation.PostConstruct)76 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 IOException (java.io.IOException)6 Date (java.util.Date)6 PostBean (it.vige.rubia.dto.PostBean)4 JSFUtil.handleException (it.vige.rubia.ui.JSFUtil.handleException)4 ArrayList (java.util.ArrayList)4 ForumBean (it.vige.rubia.dto.ForumBean)3 FacesContext (jakarta.faces.context.FacesContext)3 Method (java.lang.reflect.Method)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 ApplicationAssociate (com.sun.faces.application.ApplicationAssociate)2 HTTPServer (io.prometheus.client.exporter.HTTPServer)2 ModuleException (it.vige.rubia.ModuleException)2 CategoryBean (it.vige.rubia.dto.CategoryBean)2 TopicBean (it.vige.rubia.dto.TopicBean)2 SessionScoped (jakarta.enterprise.context.SessionScoped)2 Typed (jakarta.enterprise.inject.Typed)2 ClientWindow (jakarta.faces.lifecycle.ClientWindow)2 Serializable (java.io.Serializable)2