just before adding authorization service.
[photos] / src / main / java / org / wamblee / photos / model / plumbing / Producer.java
1 /*
2  * Copyright 2005-2013 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.photos.model.plumbing;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.security.Principal;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import javax.enterprise.context.ApplicationScoped;
25 import javax.enterprise.context.SessionScoped;
26 import javax.enterprise.inject.Produces;
27 import javax.inject.Inject;
28 import javax.persistence.EntityManager;
29 import javax.persistence.PersistenceContext;
30 import javax.servlet.http.HttpServletRequest;
31
32 import org.apache.log4j.Logger;
33 import org.wamblee.cache.Cache;
34 import org.wamblee.cache.EhCache;
35 import org.wamblee.io.ClassPathResource;
36 import org.wamblee.io.InputResource;
37 import org.wamblee.photos.concurrent.ConcurrentAlbum;
38 import org.wamblee.photos.model.Album;
39 import org.wamblee.photos.model.PhotoEntry;
40 import org.wamblee.photos.model.filesystem.FileSystemAlbum;
41 import org.wamblee.security.authentication.GroupSet;
42 import org.wamblee.security.authentication.Md5HexMessageDigester;
43 import org.wamblee.security.authentication.MessageDigester;
44 import org.wamblee.security.authentication.NameValidator;
45 import org.wamblee.security.authentication.RegexpNameValidator;
46 import org.wamblee.security.authentication.User;
47 import org.wamblee.security.authentication.UserAdminInitializer;
48 import org.wamblee.security.authentication.UserAdministration;
49 import org.wamblee.security.authentication.UserAdministrationImpl;
50 import org.wamblee.security.authentication.UserSet;
51 import org.wamblee.security.authentication.jpa.JpaGroupSet;
52 import org.wamblee.security.authentication.jpa.JpaUserSet;
53
54 /**
55  * @author Erik Brakkee
56  * 
57  */
58 public class Producer {
59
60     private static final Logger LOGGER = Logger.getLogger(Producer.class
61         .getName());
62
63     private static final String APP_CONFIG_RESOURCE = "META-INF/org.wamblee.photos.properties";
64
65     @Inject
66     private HttpServletRequest request;
67
68     @PersistenceContext
69     private EntityManager entityManager;
70
71     private Configuration getCOnfiguration() {
72         LOGGER.info("Initializing configuration");
73         Configuration config;
74         try {
75             config = new Configuration(new ClassPathResource(
76                 APP_CONFIG_RESOURCE).getInputStream());
77         } catch (IOException e) {
78             throw new RuntimeException(
79                 "Could not read application configuration property classpath resource " +
80                     APP_CONFIG_RESOURCE, e);
81         }
82         return config;
83     }
84
85     @Produces
86     @ApplicationScoped
87     public UserAdministration getUserAdmin() {
88         LOGGER.info("Initializing user administration");
89         try {
90             NameValidator passwordvalidator = new RegexpNameValidator(".{5,}",
91                 "INVALID_PASSWORD", "Password must have at least 5 characters");
92             InputResource cacheConfig = new ClassPathResource(
93                 "META-INF/ehcache.xml");
94             Cache<String, User> userCache = new EhCache(cacheConfig, "users");
95             MessageDigester passwordEncoder = new Md5HexMessageDigester();
96             UserSet userset = new JpaUserSet(userCache, passwordvalidator,
97                 passwordEncoder, entityManager);
98             GroupSet groupset = new JpaGroupSet(entityManager);
99             NameValidator uservalidator = new RegexpNameValidator(
100                 "[a-zA-Z]+[a-zA-Z0-9]*", "INVALID_USERNAME",
101                 "User name must consist of alphanumeric characters only");
102             NameValidator groupvalidator = new RegexpNameValidator(
103                 "[a-zA-Z]+[a-zA-Z0-9]*", "INVALID_GROUPNAME",
104                 "Group name must consist of alphanumeric characters only");
105
106             UserAdministration admin = new UserAdministrationImpl(userset,
107                 groupset, uservalidator, groupvalidator);
108             UserAdminInitializer initializer = new UserAdminInitializer(admin,
109                 new String[] { "erik", "admin" }, new String[] { "users",
110                     "administrators" }, new String[] { "abc123", "abc123" });
111             return admin;
112         } catch (IOException e) {
113             throw new RuntimeException(
114                 "Could not initialize user administration", e);
115         }
116     }
117
118     @Produces
119     @ApplicationScoped
120     @AllPhotos
121     public Album getAllPhotos() {
122         LOGGER.info("Initializing photo album");
123
124         try {
125             File dir = new File(getCOnfiguration().getPath());
126             InputResource cacheConfig = new ClassPathResource(
127                 "META-INF/ehcache.xml");
128             Cache<String, ArrayList<PhotoEntry>> photoCache = new EhCache<String, ArrayList<PhotoEntry>>(
129                 cacheConfig, "photos");
130             Album fileSystemAlbum = new FileSystemAlbum(dir, "/", photoCache);
131             Album concurrentAlbum = new ConcurrentAlbum(fileSystemAlbum);
132
133             return concurrentAlbum;
134         } catch (IOException e) {
135             throw new RuntimeException("Could not initialize photo album", e);
136         }
137     }
138
139     @Produces
140     @SessionScoped
141     @AuthorizedPhotos
142     public Album getAuthorizedPhotos() {
143         LOGGER.info("Initializing authorized photos for current session");
144
145         return null;
146     }
147
148     @Produces
149     @SessionScoped
150     public User getUser() {
151         LOGGER.info("Initializing user object for current session");
152
153         Principal userPrincipal = request.getUserPrincipal();
154         if (userPrincipal == null) {
155             // CDI: cannot return null from this method.
156             throw new RuntimeException("No authenticated user");
157         }
158         String username = userPrincipal.getName();
159         List<User> users = entityManager
160             .createNamedQuery(User.QUERY_FIND_BY_NAME)
161             .setParameter(User.NAME_PARAM, username).getResultList();
162         if (users.size() > 1) {
163             throw new RuntimeException("More than one user found for '" +
164                 username + "'");
165         }
166         if (users.isEmpty()) {
167             throw new RuntimeException("No authenticated user");
168         }
169         return users.get(0);
170     }
171
172 }