You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@rave.apache.org by zh...@apache.org on 2011/04/01 02:29:38 UTC
svn commit: r1087520 [11/35] - in
/incubator/rave/donations/ogce-gadget-container: ./ config/
config/shindig-1.1-BETA5/ config/shindig-2.0.0/ db-cleaner/ examples/
examples/src/ examples/src/main/ examples/src/main/java/
examples/src/main/java/cgl/ exa...
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/RedirectionHub.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/RedirectionHub.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/RedirectionHub.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/RedirectionHub.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,127 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.IOException;
+import java.net.URLEncoder;
+
+import javax.servlet.Servlet;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class RedirectionHub {
+ private final static String homeURL = "/index.jsp";
+ private final static String signURL = "/www/sign.jsp";
+ private final static String signInURL = "/signin";
+
+ public static void forward2Home (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response)
+ throws IOException, ServletException {
+ String nextURL = request.getParameter(SignIn.keyNextURL);
+ forward2Home(servlet, request, response, nextURL);
+ }
+
+ public static void forward2Home (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response,
+ String keyNextURLInReqObj, String nextURL)
+ throws IOException, ServletException {
+ if (nextURL != null)
+ request.setAttribute(keyNextURLInReqObj, nextURL);
+ servlet.getServletConfig().getServletContext().getRequestDispatcher(homeURL).forward(request, response);
+ }
+
+ public static void forward2Home (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response,
+ String nextURL)
+ throws IOException, ServletException {
+ if (nextURL != null)
+ request.setAttribute(SignIn.keyNextURLInReqObj, nextURL);
+ servlet.getServletConfig().getServletContext().getRequestDispatcher(homeURL).forward(request, response);
+ }
+
+
+ public static void forward2SignPage (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response, boolean redirects)
+ throws IOException, ServletException {
+ String nextURL = request.getParameter(SignIn.keyNextURL);
+ forward2SignPage(servlet, request, response, nextURL, redirects);
+ }
+
+ public static void forward2SignPage (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response,
+ String keyNextURLInReqObj, String nextURL, boolean redirects)
+ throws IOException, ServletException {
+ if (nextURL != null)
+ request.setAttribute(keyNextURLInReqObj, nextURL);
+
+ if (!redirects)
+ servlet.getServletConfig().getServletContext().getRequestDispatcher(signURL).forward(request, response);
+ else
+ response.sendRedirect(signURL);
+ }
+
+ public static void forward2SignPage (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response,
+ String nextURL, boolean redirects)
+ throws IOException, ServletException {
+ if (nextURL != null)
+ request.setAttribute(SignIn.keyNextURLInReqObj, nextURL);
+
+ if (!redirects)
+ servlet.getServletConfig().getServletContext().getRequestDispatcher(signURL).forward(request, response);
+ else
+ response.sendRedirect(signURL);
+ }
+
+ public static void forward2SignIn (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response, boolean redirects)
+ throws IOException, ServletException {
+ String nextURL = request.getParameter(SignIn.keyNextURL);
+ forward2SignIn(servlet, request, response, nextURL, redirects);
+ }
+
+ public static void forward2SignIn (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response,
+ String keyNextURLInReqObj, String nextURL, boolean redirects)
+ throws IOException, ServletException {
+ if (nextURL != null)
+ request.setAttribute(keyNextURLInReqObj, nextURL);
+ if (!redirects)
+ servlet.getServletConfig().getServletContext().getRequestDispatcher(signInURL).forward(request, response);
+ else
+ response.sendRedirect(signInURL);
+ }
+
+ public static void forward2SignIn (Servlet servlet,
+ HttpServletRequest request, HttpServletResponse response,
+ String nextURL, boolean redirects)
+ throws IOException, ServletException {
+ if (nextURL != null)
+ request.setAttribute(SignIn.keyNextURLInReqObj, nextURL);
+ if (!redirects)
+ servlet.getServletConfig().getServletContext().getRequestDispatcher(signInURL).forward(request, response);
+ else
+ response.sendRedirect(signInURL);
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/ServletSessionMgr.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/ServletSessionMgr.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/ServletSessionMgr.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/ServletSessionMgr.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,48 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+public class ServletSessionMgr {
+ public static final String sessionUserId = "userId";
+
+ /**
+ * Put authenticated user into session.
+ */
+ public static void putAuthenUserInSession (HttpServletRequest request, String screenname) {
+ putAuthenUserInSession(request.getSession(),screenname);
+ }
+
+ public static void putAuthenUserInSession (HttpSession session, String screenname) {
+ session.putValue(sessionUserId, screenname);
+ }
+ public static Object getUserInSession(HttpSession session) {
+ if (session == null) return null;
+ else return session.getAttribute(sessionUserId);
+ }
+ public static Object getUserInSession(HttpServletRequest request) {
+ return getUserInSession(request.getSession(false));
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignIn.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignIn.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignIn.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignIn.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,94 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.IOException;
+import java.util.logging.Logger;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import cgl.shindig.InjectedServlet;
+
+import com.google.inject.Inject;
+
+/** This class handles signin of users. */
+public class SignIn extends InjectedServlet {
+
+ private Logger logger = Logger.getLogger(SignIn.class.getName());
+
+ public static final String keyNextURL = "next";
+ public static final String keyNextURLInReqObj = "next";
+
+ @Inject
+ private SignInController signinCtl;
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException{
+ process(request, response);
+ }
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException{
+ process(request, response);
+ }
+
+ /**
+ * internal method.
+ * authentication result code:
+ * 0 success
+ * 1 authentication information is missing.
+ * the user need to give more information.
+ * 2
+ * 3 authentication failed.
+ *
+ */
+ public void process (HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException{
+
+ /**
+ * We are not using any built-in authentication provided by tomcat for webapp.
+ * So even if we are using two-way SSL authentication in transport layer,
+ * request.getAuthType still returns null.
+ * If we want to integrate it into webapp automatically, several additional steps are needed
+ * - change conf/tomcat-users.xml to add a new role and user names.
+ * user name should be dn of the certificate.
+ * - change web.xml to add sections *security-constraint* and *login-config*.
+
+ request.getAuthType()
+ request.getAuthType().equals(HttpServletRequest.CLIENT_CERT_AUTH))
+ */
+
+ AuthenzResult authenzResult = signinCtl.authenzIntoSession(request, response);
+
+ /* forward to another page based on the state */
+ if (!authenzResult.isSuccessful()){//signin failed
+ RedirectionHub.forward2SignPage(this, request, response, false);
+ } else {
+ //Success so send us to index.jsp
+ RedirectionHub.forward2Home(this, request, response);
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignInController.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignInController.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignInController.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignInController.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,160 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import cgl.shindig.Portal;
+import cgl.shindig.SSLOSGFilter;
+import cgl.shindig.security.SimpleCredentials;
+import cgl.shindig.usermanage.UILayout;
+import cgl.shindig.usermanage.User;
+import cgl.shindig.usermanage.UserDBMgr;
+
+import com.google.inject.Inject;
+
+public class SignInController {
+
+ /** These two variables represents the keys for user name and password input field. */
+ private static final String keyScreenname = "screenname";
+ private static final String keyPassword = "password";
+
+ @Inject
+ private Portal portal;
+
+ public AuthenzResult authenzIntoSession (
+ HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException{
+ AuthenzResult authenzResult = authenticate(request, response);
+
+ int authenzRC = authenzResult.authenzRC;
+ request.setAttribute("action", "signin");
+ request.setAttribute("state", new Integer(authenzRC));
+
+ if(authenzResult.isSuccessful()){ //signin succeeded
+ User user = authenzResult.user;
+ request.setAttribute("user", user);
+ ServletSessionMgr.putAuthenUserInSession(request, user.getScreenname());
+ }
+ return authenzResult;
+ }
+
+ private AuthenzResult authenticate (HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
+ AuthenzResult authenzResult = null;
+ if (SSLOSGFilter.osgDNAttr != null &&
+ request.getAttribute(SSLOSGFilter.osgDNAttr) != null) {
+ System.out.println("--------- osg style authenz -------------");
+ authenzResult = clientCertAuth(request, response);
+ } else {
+ System.out.println("--------- username/password authenz -------------");
+ authenzResult = unamepwdAuth(request, response);
+ }
+ return authenzResult;
+ }
+
+ /**
+ * client side certificate authenz.
+ */
+ private AuthenzResult clientCertAuth (HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ AuthenzResult authenzResult = new AuthenzResult();
+ String dn = (String)request.getAttribute(SSLOSGFilter.osgDNAttr);
+ portalLogin(dn, "", authenzResult);
+
+ return authenzResult;
+ }
+ /**
+ * username/password auth.
+ */
+ private AuthenzResult unamepwdAuth (HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ AuthenzResult authenzResult = new AuthenzResult();
+
+ String screenname = request.getParameter(keyScreenname);
+ String password = request.getParameter(keyPassword);
+
+ /* check validity of input first, and then searches for the user in data base */
+ int state = 0; //state of this operation
+ if( screenname == null || password == null ){ //input is invalid
+ //FIXME Why use these opaque integers? Should use static constant integers with more
+ //descriptive names. Anyway, state==0 is the good state.
+ state = 1;
+ //FIXME? Why directly set this value instead of using a setter?
+ authenzResult.authenzRC = state;
+ }else{
+ //FIXME This is also a little obscure, since authenzResult is being changed in the
+ //method. Portal login should return an integer that is assigned to authenzResult.authenzRC.
+ //Or even return a whole authenzResults object.
+ //This avoids setting the value as a side-effect.
+ portalLogin(screenname, password, authenzResult);
+ }
+ return authenzResult;
+ }
+
+ private void portalLogin (String userId, String password, AuthenzResult authenzResult) {
+ //FIXME? These authenzRC state numbers are confusing.
+ SimpleCredentials creds =
+ new SimpleCredentials(userId, password.toCharArray());
+ if (portal.login(creds, null)) {
+ signInCallback(userId, portal);
+
+ // TODO: maybe it's better to make portal.login method return
+ // authenticated user object?
+ User user = new User();
+ user.setScreenname(userId);
+
+ authenzResult.user = user;
+ authenzResult.authenzRC = 0;
+ } else {
+ //FIXME What is the is the significance of authenzRC==3?
+ authenzResult.authenzRC = 3;
+ }
+ }
+
+ /**
+ * FIXME: This workaround to integrate OSG is ugly.
+ * Needs a more systematic way to do it.
+ *
+ * Not sure I understand why this is being done. It seems to be dynamically deciding if the
+ * user is an OSG user on every sign-in request and updating the layout data.
+ */
+ private void signInCallback(String screenname, Portal portal) {
+ Properties config =
+ portal.getConfig().getSecurityConfig().getSecurityManagerConfig().getUserManagerConfigProps();
+ if (config != null && config.getProperty("subsystem") != null &&
+ config.getProperty("subsystem").equalsIgnoreCase("osg")) {
+ if (UserDBMgr.getUILayoutBySN(screenname) == null) {
+ UserDBMgr.insertUILayout(new UILayout(screenname, SignUp.defaultLayoutData));
+ }
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignUp.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignUp.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignUp.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/SignUp.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,201 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.InputStream;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.logging.Logger;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.io.IOUtils;
+import org.ietf.jgss.GSSCredential;
+
+import xportlets.proxymanager.ProxyManager;
+import xportlets.proxymanager.ProxyStorageException;
+import cgl.shindig.InjectedServlet;
+import cgl.shindig.common.BaseHttpServlet;
+import cgl.shindig.usermanage.UILayout;
+import cgl.shindig.usermanage.User;
+import cgl.shindig.usermanage.UserDBMgr;
+import cgl.shindig.usermanage.UserValidator;
+import cgl.shindig.usermanage.util.ResourceLoader;
+
+
+/** This class handles signup of new users. */
+public class SignUp extends InjectedServlet {
+ private final static Logger logger =
+ Logger.getLogger(SignUp.class.getName());
+
+ /** These variables represents the keys for various input fields. */
+ private static final String keyScreenname = "screenname";
+ private static final String keyPassword = "password";
+ private static final String keyLastname = "lastname";
+ private static final String keyFirstname = "firstname";
+ //private static final String keyAge = "age";
+ private static final String keyDobYear = "dobyear";
+ private static final String keyDobMonth = "dobmonth";
+ private static final String keyDobDay = "dobday";
+ private static final String keyLanguage = "language";
+ private static final String keyTimeZone = "timezone";
+ private static final String keyEmail = "email";
+ private static final String keyGender = "gender";
+ private static final String keyPostcode = "zipcode";
+ private static final String keyCountry = "country";
+
+ // @Inject
+ // private Portal portal;
+
+ //input with following key indicates this is an OpenID signup
+ //Note: for security reason, we must check whether the claimed id has been authenticated.
+ private static final String keyOpenIdFlag = "openid_hidden";
+
+ /* validator for user-input information. */
+ private static final UserValidator uv = new UserValidator();
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, java.io.IOException{
+ String openid = request.getParameter(keyOpenIdFlag);
+ /**
+ //We allow new account requests to be associated with an OpenID account.
+ //If a user logs in first with an OpenID account that is not associated with an
+ //existing user account, the sign-in servlet will kick us over here. If the OpenID
+ //session and the browser session of the sign-up request are the same, then the
+ //new account will be associated with the OpenID URL.
+ */
+ if( openid != null ){ //openid signup
+ System.out.println("openid:"+openid);
+ //When openid authentication succeeds, variable "openid" should be set
+ //in the session. This is done in file OpenIdAuth.java.
+ HttpSession session = request.getSession();
+ System.out.println("openid in session:"+(String)session.getAttribute(OpenIdAuth.OPENID_ID_SESSION));
+ String openidinsession = (String)session.getAttribute(OpenIdAuth.OPENID_ID_SESSION);
+ if( openidinsession == null || openidinsession.compareTo(openid)!=0 )
+ openid = "";
+ }else{
+ openid = "";
+ }
+
+ /* get values for various input fields */
+ String screenname = request.getParameter(keyScreenname);
+ String password = request.getParameter(keyPassword);
+ String lastname = request.getParameter(keyLastname);
+ String firstname = request.getParameter(keyFirstname);
+ String dobyear = request.getParameter(keyDobYear);
+ String dobmonth = request.getParameter(keyDobMonth);
+ String dobday = request.getParameter(keyDobDay);
+ String language = request.getParameter(keyLanguage);
+ String timezone = request.getParameter(keyTimeZone);
+ String email = request.getParameter(keyEmail);
+ String gender = request.getParameter(keyGender);
+ String postcode = request.getParameter(keyPostcode);
+ String country = request.getParameter(keyCountry);
+ // String nextURL = request.getParameter(SIgnIn.keyNextURL);
+ // if (nextURL != null)
+ // request.setAttribute(SignIn.keyNextURLInReqObj, nextURL);
+
+ //String age = request.getParameter(keyAge);
+ Calendar calendar = Calendar.getInstance();
+ calendar.clear();
+ calendar.set(Integer.parseInt(dobyear),
+ Integer.parseInt(dobmonth),
+ Integer.parseInt(dobday));
+ Date dob = calendar.getTime();
+
+ //The "state" notation seems a little brittle. Should just booleans. State 2 is "false because....".
+ //Maybe use an additional "messageToUser" string that provides additional information.
+ int state = 0; //succeed
+
+ User user = new User( screenname, firstname, lastname, dob, language,
+ timezone, email, gender, postcode, openid, password,country );
+ //Check that the input information elements have valid input ranges.
+ if( uv.validate( user ) ){
+ /* update both the user's information and layout information */
+ //This will encrypt the password as a hash.
+ boolean succ = UserDBMgr.insertUser( user );
+ if( succ == true ){
+ //Note the defaultLayoutData string is actually some non-trivial JSON loaded from
+ //a file.
+ UserDBMgr.insertUILayout(new UILayout(user.getScreenname(), defaultLayoutData));
+ proxystoreKeyAdjust(openid, screenname);
+ }else{
+ state = 2; //the user with that screen name has existed.
+ }
+ }else{//the user has input invalid information.
+ state = 1;
+ }
+
+ if( state != 0 ){//sign up failed
+ BaseHttpServlet.markSignupState(request, state);
+ RedirectionHub.forward2SignPage(this, request, response, false);
+ }else{
+ /* if the user signs up a new account successfully, he/she would
+ * log in automatically.
+ *
+ * This should probably be replaced by code that checks a configuration parameter and applies some
+ * logic:
+ *
+ * if (autoAccountCreation==true) RedirectionHub.forward2SignIn(this, request, response, false);
+ * else if (autoAccountCreation==false) RedirectionHub.forward2Hold(this, request, response, false);
+ *
+ * Here, foward2Hold is a new method to be implemented in RedirectionHub that tells the user to
+ * be patient and notifies the administrator(s). Account should be in a disabled state until
+ * enabled by the admin.
+ */
+ RedirectionHub.forward2SignIn(this, request, response, false);
+ }
+ }
+
+ public static void proxystoreKeyAdjust(String openid, String screenname) {
+ //Looks like a workaround method.
+ GSSCredential gssCred = ProxyManager.getDefaultProxy(openid);
+ if (gssCred != null) {
+ try {
+ ProxyManager.removeProxy(openid, gssCred);
+ ProxyManager.addProxy(screenname, gssCred);
+ } catch (ProxyStorageException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ //Static initialization of the defaultLayoutData string. This is loaded in as a big JSON file.
+ public static String defaultLayoutData;
+ private final static String defaultLayoutDataFileName = "defaultLayout.json";
+ static {
+ String relPath = SignUp.class.getPackage().getName().replace( ".", "/");
+ relPath += (relPath.length()==0?"":"/") + defaultLayoutDataFileName;
+ try {
+ InputStream is = ResourceLoader.open("res://"+relPath);
+ defaultLayoutData = IOUtils.toString(is, "UTF-8");
+ IOUtils.closeQuietly(is);
+ } catch(Exception ex) {
+ logger.severe("loading of file \"" + relPath + "\" failed\n" + ex);
+ System.exit(1);
+ }
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdmin.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdmin.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdmin.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdmin.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,733 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.net.URLDecoder;
+
+import cgl.shindig.usermanage.*;
+
+
+/**
+ * This class handles requests from administrators.
+ */
+public class UserAdmin extends HttpServlet {
+ public static SecurityChecker SecurityChecker = new SecurityChecker();
+ public static SecurityChecker DummySecurityChecker = new DummySecurityChecker();
+
+ protected SecurityChecker securityChecker;
+
+ @Override
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+ this.securityChecker = SecurityChecker;
+ }
+
+ private boolean securityCheck(HttpServletRequest request, HttpServletResponse response,
+ UserAdminDispatcher dispatcher){
+ if( dispatcher == null ) return false;
+ UserAdminReq uareq = dispatcher.getUserAdminReq();
+ if( uareq != null ){
+ return securityChecker.isLegal(request, response, uareq);
+ }else
+ return true;
+ }
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ try{
+ UserAdminDispatcher dispatcher = new UserAdminDispatcher(request);
+ if( securityCheck(request, response, dispatcher) )
+ dispatcher.execute(request, response);
+ else
+ illegalOpOutputGen(request, response);
+ }catch(Exception e){
+ }
+ }
+ public void doPut(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ UserAdminDispatcher dispatcher = new UserAdminDispatcher(request);
+ if( securityCheck(request, response, dispatcher) )
+ dispatcher.execute(request, response);
+ else
+ illegalOpOutputGen(request, response);
+ }
+ public void doDelete(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ UserAdminDispatcher dispatcher = new UserAdminDispatcher(request);
+ if( securityCheck(request, response, dispatcher) )
+ dispatcher.execute(request, response);
+ else
+ illegalOpOutputGen(request, response);
+ }
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ UserAdminDispatcher dispatcher = new UserAdminDispatcher(request);
+ if( securityCheck(request, response, dispatcher) )
+ dispatcher.execute(request, response);
+ else
+ illegalOpOutputGen(request, response);
+ }
+
+ /** This function is invoked when the request is illegal which means the user
+ * does not have privilege to execute the operation.
+ */
+ private void illegalOpOutputGen(HttpServletRequest request, HttpServletResponse response){
+ try{
+ String output = "{error: 'You do not have privilege to execute the operation'}";
+ PrintWriter out = response.getWriter();
+ out.write(output);
+ }catch(Exception e){
+ System.out.println("[ERROR]:In function illegalOpOutputGen:" + e);
+ }
+ }
+}
+
+class PathPieces{
+ private List<String> pieces = new ArrayList<String>();
+ private static String delim = "[/ ]";
+ /* parameter should not include protocol, host, port or context path */
+ public PathPieces(String url){
+ int idx = 0;
+ url = url.trim();
+ String []parts = url.split( delim );
+ for(int i = 0 ; i < parts.length ; ++i){
+ if( parts[i].length() == 0 ){
+ continue;
+ }else{
+ pieces.add(parts[i]);
+ }
+ }
+ }
+ public PathPieces(List<String> pieces){
+ this.pieces = pieces;
+ }
+ public String getPart( int idx ){
+ if( idx >= 0 && idx < pieces.size() ){
+ return pieces.get(idx);
+ }
+ return null;
+ }
+ public PathPieces getSubParts(int fromidx, int toidx){
+ List<String> subls = pieces.subList(fromidx, toidx);
+ return new PathPieces(subls);
+ }
+ public PathPieces getSubParts(int fromidx){
+ return getSubParts(fromidx, pieces.size());
+ }
+ public int size(){
+ return pieces.size();
+ }
+}
+
+class UserAdminDispatcher{
+ private UserAdminReq uareq;
+ private String method;
+ public UserAdminReq getUserAdminReq(){
+ return this.uareq;
+ }
+ private static final UserValidator uv = new UserValidator();
+
+ public UserAdminDispatcher(HttpServletRequest request){
+ /*
+ String servletpath = request.getServletPath();
+ servletpath += request.getContextPath();
+ servletpath += request.getPathInfo();
+ servletpath += request.getRequestURI();
+ System.out.println("servletpath:"+servletpath);
+ */
+ String servletpath = request.getRequestURI();
+ String contextpath = request.getContextPath();
+ servletpath = servletpath.substring(contextpath.length());
+ System.out.println("servletpath:"+servletpath);
+
+ PathParser pathparser = new PathParser(servletpath);
+ if( pathparser.isUserAdminReq() ){
+ //check whether user admin operation is required
+ System.out.println("user admin request");
+ uareq = pathparser.getUserAdminReq();
+ }
+ method = request.getMethod();//.toLowerCase();
+ }
+
+ public void execute(HttpServletRequest request, HttpServletResponse response) {
+ try{
+ if( uareq != null ){
+ if( uareq.isGetInfoAllUser() ){
+ System.out.println("get all users");
+ if( UserAdminActions.isGetMethod(method) ){
+ List<User> result = UserAdminHandler.getAllUsers();
+ responseGen(method, result, response);
+ }
+ }
+
+ if( uareq.isGetInfoAllUserAndLayout() ){
+ System.out.println("get all users and layout");
+ if( UserAdminActions.isGetMethod(method) ){
+ Object[] result = UserAdminHandler.getAllUsersAndLayout();
+ responseGen(method, result, response);
+ }
+ }
+
+ if( uareq.isGetInfoAUser() ){
+ System.out.println("single user request");
+ //the operator operates on a specific user
+ String uid = uareq.getUserId();
+ if( UserAdminActions.isGetMethod(method) ){//GET
+ System.out.println("get request");
+ User result = UserAdminHandler.getAUser(uid);
+ responseGen(method, result, response);
+ }
+ if( UserAdminActions.isPostMethod(method) ){//POST
+ System.out.println("post request");
+ User user = UserExtractor.extract(request);
+ if( uv.validate(user) == false ){
+ responseGenIllegal(response);
+ }else if( user.getScreenname().compareTo(uid) != 0 ){
+ responseGenUnmatch(response);
+ }else{
+ System.out.println("post request: get a user");
+ boolean result = UserAdminHandler.addAUser(user);
+ responseGen(method, result, response);
+ }
+ }
+ if( UserAdminActions.isDeleteMethod(method) ){//DELETE
+ System.out.println("delete request");
+ boolean result = UserAdminHandler.deleteAUser(uid);
+ responseGen(method, result, response);
+ }
+ if( UserAdminActions.isPutMethod(method) ){ //PUT
+ System.out.println("put request");
+ User user = UserExtractor.extract(request);
+ if( uv.validate(user, method) == false ){
+ responseGenIllegal(response);
+ }else if( user.getScreenname().compareTo(uid) != 0 ){
+ responseGenUnmatch(response);
+ }else{
+ boolean result = UserAdminHandler.updateAUser(user);
+ responseGen(method, result, response);
+ }
+ }
+ }
+ }
+ }catch(Exception e){
+ System.out.println("in execute:" +e );
+ e.printStackTrace();
+ e.printStackTrace(new PrintWriter(System.out));
+ //TODO generate error message and return it to end user
+ }
+ }
+
+ /** This function is invoked when
+ * the userid in the URL and the userid in the request data(POST)
+ * do NOT match
+ */
+ private void responseGenUnmatch(HttpServletResponse response){
+ try{
+ String output = "{error: 'User ids in request URL and request data do NOT match.'}";
+ PrintWriter out = response.getWriter();
+ out.write(output);
+ }catch(Exception e){
+ System.out.println("[ERROR]:In function responseGenUnmatch:" + e);
+ }
+ }
+ /** This function is invoked when received user information is not compatible with
+ * our field type specification.
+ * E.g. the length of a field value exceeds the specified limit.
+ */
+ private void responseGenIllegal(HttpServletResponse response){
+ try{
+ String output = "{error: 'Value of some fields does not satisfy our requirement'}";
+ PrintWriter out = response.getWriter();
+ out.write(output);
+ }catch(Exception e){
+ System.out.println("[ERROR]:In function responseGenIllegal:" + e);
+ }
+ }
+ private void responseGen(String method, Object result, HttpServletResponse response){
+ String output = "";
+ if( UserAdminActions.isGetMethod(method) ){
+ if( uareq.isGetInfoAllUser() ){
+ output = "{\"succ\":\"get all users successfully\",\"data\":";
+ StringBuilder sb = new StringBuilder();
+ List<User> users = (List<User>)result;
+ sb.append("[");
+ for( int i = 0 ; i < users.size() ; ++i ){
+ if( i != 0 )
+ sb.append(",");
+ sb.append(UserJSONFormatter.format(users.get(i)));
+ }
+ sb.append("]}");
+ output += sb.toString();
+ } else if(uareq.isGetInfoAllUserAndLayout()){
+ output = "{\"succ\":\"get all users and layout successfully\",\"data\":";
+ Object[] usersAndLayout = (Object[]) result;
+ List<User> allUsers = (List<User>) usersAndLayout[0];
+ List<UILayout> allLayout = (List<UILayout>) usersAndLayout[1];
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("[");
+ for( int i = 0 ; i < allUsers.size() ; ++i ){
+ if( i != 0 )
+ sb.append(",");
+ sb.append(UserJSONFormatter.format(allUsers.get(i), allLayout));
+ }
+ sb.append("]}");
+ output += sb.toString();
+ }else if( uareq.isGetInfoAUser() ){
+ User user = (User)result;
+ if( user!=null ){
+ output = "{\"succ\":\"the user information was retrieved successfully\"";
+ output += ", \"data\": " + UserJSONFormatter.format(user) + "}";
+ }else{
+ output = "{\"error\":'the user does not exist'}";
+ }
+ }
+ }else if( UserAdminActions.isPostMethod(method) ){
+ boolean r = (Boolean)result;
+ if(r){
+ output = "{\"succ\":'the user was inserted successfully'}";
+ }else{
+ output = "{\"error\":'the user you want to insert has existed already'}";
+ }
+ }else if( UserAdminActions.isDeleteMethod(method) ){
+ boolean r = (Boolean)result;
+ if(r){
+ output = "{\"succ\":'the user was deleted successfully'}";
+ }else{
+ output = "{\"error\":'the user you want to delete does not exist'}";
+ }
+ }else if( UserAdminActions.isPutMethod(method) ){
+ boolean r = (Boolean)result;
+ if(r){
+ output = "{\"succ\":'information of the user was updated successfully'}";
+ }else{
+ output = "{\"error\":'updating of the user information failed. Maybe the user does not exist.'}";
+ }
+ }
+ try{
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(output);
+ }catch(Exception e){
+ System.out.println("[ERROR]:In function responseGen:" + e);
+ }
+ }
+}
+
+/**
+ * TODO
+ * Implement actual actions.
+ */
+class UserAdminHandler{
+ /**
+ * Get both user data and layout data
+ */
+ public static Object[] getAllUsersAndLayout(){
+ List<User> allUsers = UserDBMgr.getAllUsers();
+ List<UILayout> allLayout = UserDBMgr.getAllLayout();
+ Object[] allUsersAndLayout = new Object[2];
+ allUsersAndLayout[0] = allUsers;
+ allUsersAndLayout[1] = allLayout;
+ return allUsersAndLayout;
+ }
+
+ public static List<User> getAllUsers(){
+ return UserDBMgr.getAllUsers();
+ }
+ /** Get information of a specific user.
+ * @param userid screen name of the user to be searched for
+ * @return return null if the user does not exist. Else return the user.
+ */
+ public static User getAUser(String userid){
+ User user = UserDBMgr.getUserBySN(userid);
+ return user;
+ }
+
+ /** Add a user to our system.
+ * @param user
+ * @return return true if the user is added successfully
+ */
+ public static boolean addAUser(User user){
+ if(UserDBMgr.insertUser(user)){
+ return UserDBMgr.insertUILayout(new UILayout(user.getScreenname(), "[]"));
+ }else{
+ return false;
+ }
+ }
+
+ /** delete a user from our system.
+ * @param userid
+ * @return true if the user is deleted successfully. return false if the user does not exist.
+ */
+ public static boolean deleteAUser(String userid){
+ boolean ret = UserDBMgr.removeUserBySN(userid);
+ if( ret ){
+ return UserDBMgr.delUILayoutBySN(userid);
+ }else
+ return ret;
+ }
+
+ /** update information of a user.
+ * If the user exists already, the information will be updated.
+ * If the user does not exist in our system, a new user will be created.
+ * @param user
+ * @return true
+ */
+ public static boolean updateAUser(User user){
+ return UserDBMgr.updateUser(user);
+ }
+}
+
+class PathParser{
+ private PathPieces paths;
+ public PathParser(String url){
+ paths = new PathPieces(url);
+ }
+ public boolean isUserAdminReq(){
+ if( paths == null ) return false;
+ String uaprefix = paths.getPart(UserAdminActions.USERADMIN_IDX);
+ if( uaprefix != null ){
+ // FIXME: following tests are not comprehensive. Need a better way to know whether the URL is protected.
+ if( uaprefix.compareTo(UserAdminActions.USERADMIN_PREFIX)==0 ||
+ uaprefix.compareTo(UserAdminActions.USERADMIN_CERTBASED_PREFIX)==0){
+ return true;
+ }else{
+ return false;
+ }
+ }else
+ return false;
+ }
+ public UserAdminReq getUserAdminReq(){
+ if( isUserAdminReq() ){
+ return new UserAdminReq(paths.getSubParts(UserAdminActions.USERADMIN_IDX + 1));
+ }else
+ return null;
+ }
+}
+
+/**
+ * Represents a user admin request.
+ */
+class UserAdminReq {
+ private PathPieces pieces;
+ public UserAdminReq(PathPieces pieces){
+ this.pieces = pieces;
+ }
+ /**
+ * Check whether the client wants to get information of all users.
+ */
+ public boolean isGetInfoAllUser(){
+ if( pieces.size() == 0 ) return false;
+ String userid = pieces.getPart(0);
+ return UserAdminActions.isGetAllUser(userid);
+ }
+
+ /**
+ * Check whether the client wants to get information of all users.
+ */
+ public boolean isGetInfoAllUserAndLayout(){
+ if( pieces.size() == 0 ) return false;
+ String userid = pieces.getPart(0);
+ return UserAdminActions.isGetAllUserAndLayout(userid);
+ }
+
+ /**
+ * Check whether the client wants to get information of a single user.
+ */
+ public boolean isGetInfoAUser(){
+ if( pieces.size() == 0 ) return false;
+ String userid = pieces.getPart(0);
+ return UserAdminActions.isGetAUser(userid);
+ }
+ public String getUserId(){
+ if( pieces.size() == 0 ) return null;
+ String userid = pieces.getPart(0);
+ return userid;
+ }
+}
+
+/**
+ * Represents a user admin action
+ */
+class UserAdminActions{
+ public static String USERADMIN_METHOD_GET = "get";
+ public static String USERADMIN_METHOD_POST = "post";
+ public static String USERADMIN_METHOD_DELETE = "delete";
+ public static String USERADMIN_METHOD_PUT = "put";
+
+ public static int USERADMIN_IDX = 0;
+ public static String USERADMIN_PREFIX = "users";
+ public static String USERADMIN_CERTBASED_PREFIX = "cert-protected-users";
+ public static String USERADMIN_GETALLUSER_PREFIX = "_all_";
+ public static String USERADMIN_GETALLUSERANDLAYOUT_PREFIX = "_all_user_layout_";
+
+ public static boolean isGetAllUserAndLayout(String userid){
+ if( userid == null ) return false;
+ if( userid.compareTo(USERADMIN_GETALLUSERANDLAYOUT_PREFIX) == 0 )
+ return true;
+ return false;
+ }
+
+ public static boolean isGetAllUser(String userid){
+ if( userid == null ) return false;
+ if( userid.compareTo(USERADMIN_GETALLUSER_PREFIX) == 0 )
+ return true;
+ return false;
+ }
+
+ public static boolean isGetAUser(String userid){
+ if( userid == null ) return false;
+ if( userid.compareTo(USERADMIN_GETALLUSER_PREFIX) != 0 )
+ return true;
+ return false;
+ }
+ public static boolean isGetMethod(String method){
+ return method.compareToIgnoreCase(USERADMIN_METHOD_GET)==0;
+ }
+ public static boolean isPostMethod(String method){
+ return method.compareToIgnoreCase(USERADMIN_METHOD_POST)==0;
+ }
+ public static boolean isPutMethod(String method){
+ return method.compareToIgnoreCase(USERADMIN_METHOD_PUT)==0;
+ }
+ public static boolean isDeleteMethod(String method){
+ return method.compareToIgnoreCase(USERADMIN_METHOD_DELETE)==0;
+ }
+}
+
+/** This class extract the user information from the request. */
+class UserExtractor{
+ /** These variables represents the keys for various input fields. */
+ private static final String keyScreenname = "screenname";
+ private static final String keyPassword = "password";
+ private static final String keyLastname = "lastname";
+ private static final String keyFirstname = "firstname";
+ //private static final String keyAge = "age";
+ private static final String keyDobYear = "dobyear";
+ private static final String keyDobMonth = "dobmonth";
+ private static final String keyDobDay = "dobday";
+ private static final String keyLanguage = "language";
+ private static final String keyTimeZone = "timezone";
+ private static final String keyEmail = "email";
+ private static final String keyGender = "gender";
+ private static final String keyPostcode = "zipcode";
+ private static final String keyCountry = "country";
+
+ //input with following key indicates this is an OpenID signup
+ //Note: for security reason, we must check whether the claimed id has been authenticated.
+ private static final String keyOpenIdFlag = "openid";
+
+ /* validator for user-input information. */
+ //private static final UserValidator uv = new UserValidator();
+
+ public static User extract(HttpServletRequest request)
+ throws Exception{
+ if( UserAdminActions.isPostMethod(request.getMethod()) ){
+ /* get values for various input fields */
+ String screenname = request.getParameter(keyScreenname);
+ String password = request.getParameter(keyPassword);
+ String lastname = request.getParameter(keyLastname);
+ String firstname = request.getParameter(keyFirstname);
+ String dobyear = request.getParameter(keyDobYear);
+ String dobmonth = request.getParameter(keyDobMonth);
+ String dobday = request.getParameter(keyDobDay);
+ String language = request.getParameter(keyLanguage);
+ String timezone = request.getParameter(keyTimeZone);
+ String email = request.getParameter(keyEmail);
+ String gender = request.getParameter(keyGender);
+ String postcode = request.getParameter(keyPostcode);
+ String openid = request.getParameter(keyOpenIdFlag);
+ String country = request.getParameter(keyCountry);
+
+ //String age = request.getParameter(keyAge);
+ Calendar calendar = Calendar.getInstance();
+ calendar.clear();
+ calendar.set(Integer.parseInt(dobyear),
+ Integer.parseInt(dobmonth),
+ Integer.parseInt(dobday));
+ Date dob = calendar.getTime();
+
+ User user = new User( screenname, firstname, lastname, dob, language,
+ timezone, email, gender, postcode, openid, password, country );
+ return user;
+ }else if( UserAdminActions.isPutMethod(request.getMethod()) ){
+ ServletInputStream input = request.getInputStream();
+ Map<String, String> params = new HashMap<String,String>();
+ String charset = request.getCharacterEncoding();
+ if( charset == null ){
+ String ct = request.getContentType();
+ int index = ct.indexOf(";");
+ if( index != -1 ){
+ charset = ct.substring(index+1);
+ charset = charset.trim();
+ }
+ }
+ if( charset != null ){
+ BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset));
+ int code, code2;
+ boolean isHighSurrogate = false, propstage = true;
+ StringBuilder prop = new StringBuilder(), value = new StringBuilder();
+ while( (code = reader.read()) != -1 ){
+ if( Character.isHighSurrogate((char)code) ){
+ }else{
+ if( code == '&' ){
+ propstage = true;
+ params.put( URLDecoder.decode(prop.toString()), URLDecoder.decode(value.toString()) );
+ prop.delete(0, prop.length());
+ }else if( code == '=' ){
+ propstage = false;
+ value.delete(0, value.length());
+ }else if( propstage ){
+ prop.append((char)code);
+ }else if( !propstage ){
+ value.append((char)code);
+ }
+ }
+ }
+ if( propstage == false )
+ params.put( URLDecoder.decode(prop.toString()), URLDecoder.decode(value.toString()) );
+
+ String screenname = params.get(keyScreenname);
+ String password = params.get(keyPassword);
+ String lastname = params.get(keyLastname);
+ String firstname = params.get(keyFirstname);
+ String dobyear = params.get(keyDobYear);
+ String dobmonth = params.get(keyDobMonth);
+ String dobday = params.get(keyDobDay);
+ String language = params.get(keyLanguage);
+ String timezone = params.get(keyTimeZone);
+ String email = params.get(keyEmail);
+ String gender = params.get(keyGender);
+ String postcode = params.get(keyPostcode);
+ String openid = params.get(keyOpenIdFlag);
+ String country = params.get(keyCountry);
+
+ System.out.println("DOB year:"+dobyear+"month:"+dobmonth+"day:"+dobday);
+ //String age = params.getParameter(keyAge);
+ Calendar calendar = Calendar.getInstance();
+ calendar.clear();
+ calendar.set(Integer.parseInt(dobyear),
+ Integer.parseInt(dobmonth),
+ Integer.parseInt(dobday));
+ Date dob = calendar.getTime();
+
+ User user = new User( screenname, firstname, lastname, dob, language,
+ timezone, email, gender, postcode, openid, password, country );
+ return user;
+ }else{
+ //TODO
+ return null;
+ }
+ }else{
+ return null;
+ }
+ }
+}
+
+class SecurityChecker{
+ public static String sessionAdminKey = "admin";
+ public boolean isLegal(HttpServletRequest request, HttpServletResponse response){
+ return isLegal(request, response, null);
+ }
+ public boolean isLegal(HttpServletRequest request, HttpServletResponse response,
+ UserAdminReq uareq){
+ if(uareq.isGetInfoAllUser() || uareq.isGetInfoAllUserAndLayout()){
+ System.out.println("GET ALL INFO");
+ return isAdmin(request, response);
+ }else if ( uareq. isGetInfoAUser() ){
+ String claimedid = uareq.getUserId();
+ if( claimedid == null ) return false;
+ String method = request.getMethod();
+ if( UserAdminActions.isPostMethod(method) ){
+ return isLegalPost(request, response, claimedid);
+ }else if( UserAdminActions.isPutMethod(method) ){
+ return isLegalPut(request, response, claimedid);
+ }else if( UserAdminActions.isDeleteMethod(method) ){
+ return isLegalDelete(request, response, claimedid);
+ }else if( UserAdminActions.isGetMethod(method) ){
+ System.out.println("IN GET A INFO");
+ return isLegalGet(request, response, claimedid);
+ }else
+ return false;
+ }else
+ return false;
+ }
+ protected boolean isAdmin(HttpServletRequest request, HttpServletResponse response){
+ HttpSession session = request.getSession();
+ Object obj = session.getAttribute(sessionAdminKey);
+ System.out.println("Is Admin "+obj);
+ if( obj != null ){
+ return true;
+ }else
+ return false;
+ }
+ private boolean isLoginAndSame(HttpServletRequest request, HttpServletResponse response,
+ String claimedid){
+
+ System.out.println("IS LOGIN AND SAME");
+ if( claimedid == null ) return false;
+ HttpSession session = request.getSession();
+ // Object obj = session.getAttribute(SignIn.sessionUserId);
+ Object obj = ServletSessionMgr.getUserInSession(session);
+ System.out.println("SESSION obj" + obj);
+ if( obj == null ){
+ return false;
+ }else{
+ String uid = (String)obj; //the user signed in
+ if( claimedid.compareTo(uid) == 0 )
+ return true;
+ return false;
+ }
+ }
+ private boolean isLegalPost(HttpServletRequest request, HttpServletResponse response,
+ String claimedid){
+ return isAdmin(request, response);
+ }
+ private boolean isLegalPut(HttpServletRequest request, HttpServletResponse response,
+ String claimedid){
+ if( isAdmin(request, response) )
+ return true;
+ return isLoginAndSame(request, response, claimedid);
+ }
+ private boolean isLegalDelete(HttpServletRequest request, HttpServletResponse response,
+ String claimedid){
+ return isAdmin(request, response);
+ }
+ private boolean isLegalGet(HttpServletRequest request, HttpServletResponse response,
+ String claimedid){
+ if( isAdmin(request, response) )
+ return true;
+ return isLoginAndSame(request, response, claimedid);
+ }
+}
+
+class DummySecurityChecker extends SecurityChecker {
+ @Override
+ protected boolean isAdmin (HttpServletRequest request, HttpServletResponse response) {
+ System.out.println("DummySecurityChecker is used");
+ return true;
+ }
+}
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminLogout.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminLogout.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminLogout.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminLogout.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,57 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+/** Handles logout. */
+public class UserAdminLogout extends HttpServlet{
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ logout(request, response);
+ }
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ logout(request, response);
+ }
+ private void logout(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ HttpSession session = request.getSession();
+ if( session != null ){
+ session.invalidate();
+ }
+ responseGen(response);
+ }
+ private void responseGen(HttpServletResponse response){
+ try{
+ response.setContentType("application/json");
+ String output = "{succ: 'logout succeeded'}";
+ PrintWriter out = response.getWriter();
+ out.write(output);
+ }catch(Exception e){
+ System.out.println("[ERROR]:In function responseGen:" + e);
+ }
+ }
+}
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminPasswdChange.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminPasswdChange.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminPasswdChange.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminPasswdChange.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,77 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import cgl.shindig.usermanage.*;
+
+/**
+ * This class handles signin of user administrator.
+ */
+public class UserAdminPasswdChange extends HttpServlet{
+
+ private static final String keyOldPassword = "oldpassword";
+ private static final String keyNewPassword = "newpassword";
+
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+
+ String screenname = null;
+ HttpSession session = request.getSession();
+ if (session != null) {
+ screenname = (String)session.getAttribute(SecurityChecker.sessionAdminKey);
+ }
+
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ if (screenname == null) {
+ out.write("{error:'Your may not have logged in.'}");
+ return;
+ }
+
+ String oldpassword = request.getParameter(keyOldPassword);
+ String newpassword = request.getParameter(keyNewPassword);
+
+ AdminUser adminUser = new AdminUser(screenname, oldpassword);
+ AdminUser adminUserInDb = UserDBMgr.getAdminUserBySN(screenname);
+ if (adminUser.equals(adminUserInDb)) {
+ adminUser.setPassword(newpassword);
+ UserDBMgr.setAdminUserBySN(adminUser);
+ out.write("{succ:'Password was changed successfully'}");
+ } else {
+ out.write("{error:'Your type invalid old password.'}");
+ }
+ }
+
+ /* only POST request is accepted */
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ PrintWriter out = response.getWriter();
+ out.write("{error:'You should use HTTP POST to sign in.'}");
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminSignIn.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminSignIn.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminSignIn.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/UserAdminSignIn.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,68 @@
+package cgl.shindig.usermanage.servlet;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import cgl.shindig.usermanage.*;
+
+/** This class handles signin of user administrator. */
+public class UserAdminSignIn extends HttpServlet{
+ public static final String sessionUserId = "userId";
+
+ /** These two variables represents the keys for user name and password input field. */
+ private static final String keyScreenname = "screenname";
+ private static final String keyPassword = "password";
+
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ String screenname = request.getParameter(keyScreenname);
+ String password = request.getParameter(keyPassword);
+ PrintWriter out = response.getWriter();
+
+ AdminUser adminUser = new AdminUser(screenname, password);
+ AdminUser adminUserInDb = UserDBMgr.getAdminUserBySN(screenname);
+ if (adminUser.equals(adminUserInDb)) {
+ // if( screenname != null && screenname.compareTo("admin") == 0 &&
+ // password != null && password.compareTo("admin") == 0 ){
+ response.setContentType("application/json");
+ out.write("{succ:'login successfully'}");
+ HttpSession session = request.getSession();
+ session.setAttribute(SecurityChecker.sessionAdminKey, screenname);
+ } else {
+ response.setContentType("application/json");
+ out.write("{error:'login failed'}");
+ }
+ }
+
+ /* only POST request is accepted */
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws javax.servlet.ServletException, java.io.IOException{
+ PrintWriter out = response.getWriter();
+ out.write("{error:'You should use HTTP POST to sign in.'}");
+ }
+}
+
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/defaultLayout.json
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/defaultLayout.json?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/defaultLayout.json (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/servlet/defaultLayout.json Fri Apr 1 00:29:22 2011
@@ -0,0 +1,246 @@
+{
+ "layouts":[{
+ "layouttype":"js-tab-layout",
+ "activetabidx":0,
+ "properties":{
+ "sync":"auto",
+ "theme":"default_theme"
+ },
+ "layoutdata":[{
+ "tabname":"My Gadgets",
+ "tabid":"_tab_0",
+ "column":3,
+ "ratios":"33,34,33",
+ "content":[{
+ "columnname":"undefined",
+ "columnid":"_tab_0_col_0",
+ "content":[{
+ "gadgetname":"RSS Feeds",
+ "gadgetspecsrc":"${gadget.repo.base}/rssreader.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_0_col_0_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ },
+ {
+ "gadgetname":"Embedded Calendar",
+ "gadgetspecsrc":"${gadget.repo.base}/EmbeddedCalendar.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_0_col_0_gadget_1",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_0_col_1",
+ "content":[{
+ "gadgetname":"Calendar",
+ "gadgetspecsrc":"http://gcalgadget.googlecode.com/svn/trunk/gcalgadget.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_0_col_1_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ },
+ {
+ "gadgetname":"Customized RSS Feeds",
+ "gadgetspecsrc":"${gadget.repo.base}/customized-rss-feeds.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_0_col_1_gadget_1",
+ "userpref":{
+ "selectedTab":"0"
+ },
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_0_col_2",
+ "content":[{
+ "gadgetname":"Task list",
+ "gadgetspecsrc":"${gadget.repo.base}/tasklist-080313-05.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_0_col_2_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "tabname":"Social Gadgets",
+ "tabid":"_tab_1",
+ "column":3,
+ "ratios":"33,34,33",
+ "content":[{
+ "columnname":"undefined",
+ "columnid":"_tab_1_col_0",
+ "content":[{
+ "gadgetname":"Twitter",
+ "gadgetspecsrc":"${gadget.repo.base}/twitter.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_1_col_0_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_1_col_1",
+ "content":[{
+ "gadgetname":"Picasa",
+ "gadgetspecsrc":"${gadget.repo.base}/picasa.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_1_col_1_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ },
+ {
+ "gadgetname":"Youtube",
+ "gadgetspecsrc":"${gadget.repo.base}/youtubesearch.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_1_col_1_gadget_1",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_1_col_2",
+ "content":[{
+ "gadgetname":"Facebook",
+ "gadgetspecsrc":"${gadget.repo.base}/facebook.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_1_col_2_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "tabname":"Friend Connect",
+ "tabid":"_tab_6",
+ "column":3,
+ "ratios":"33,34,33",
+ "content":[{
+ "columnname":"undefined",
+ "columnid":"_tab_6_col_0",
+ "content":[{
+ "gadgetname":"Discussion Board",
+ "gadgetspecsrc":"${gadget.repo.base}/DiscussionBoard.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_6_col_0_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ },
+ {
+ "gadgetname":"Activities",
+ "gadgetspecsrc":"${gadget.repo.base}/activity-fc.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_6_col_0_gadget_1",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_6_col_1",
+ "content":[{
+ "gadgetname":"QA",
+ "gadgetspecsrc":"${gadget.repo.base}/QA.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_6_col_1_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ },
+ {
+ "gadgetname":"Poll",
+ "gadgetspecsrc":"${gadget.repo.base}/poll-fc.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_6_col_1_gadget_1",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_6_col_2",
+ "content":[{
+ "gadgetname":"NewsLetter Subscription",
+ "gadgetspecsrc":"${gadget.repo.base}/newsletter-fc.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_6_col_2_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ },
+ {
+ "gadgetname":"CTS Event",
+ "gadgetspecsrc":"${gadget.repo.base}/event-fc.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_6_col_2_gadget_1",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "tabname":"More Gadgets",
+ "tabid":"_tab_7",
+ "column":3,
+ "ratios":"33,34,33",
+ "content":[{
+ "columnname":"undefined",
+ "columnid":"_tab_7_col_0",
+ "content":[{
+ "gadgetname":"Remember the Milk",
+ "gadgetspecsrc":"http://www.rememberthemilk.com/services/modules/googleig/rtm.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_7_col_0_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_7_col_1",
+ "content":[{
+ "gadgetname":"Wunderground",
+ "gadgetspecsrc":"http://www.wunderground.com/google/stationmap.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_7_col_1_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ },
+ {
+ "columnname":"undefined",
+ "columnid":"_tab_7_col_2",
+ "content":[{
+ "gadgetname":"Scientific Calculator",
+ "gadgetspecsrc":"http://www.trinimon.de/gadget/JCalculator.xml",
+ "gadgetrendersrc":"undefined",
+ "gadgetid":"_tab_7_col_2_gadget_0",
+ "userpref":{},
+ "status":"normal"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
Added: incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/util/ResourceLoader.java
URL: http://svn.apache.org/viewvc/incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/util/ResourceLoader.java?rev=1087520&view=auto
==============================================================================
--- incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/util/ResourceLoader.java (added)
+++ incubator/rave/donations/ogce-gadget-container/ishindig-webapp/src/main/java/cgl/shindig/usermanage/util/ResourceLoader.java Fri Apr 1 00:29:22 2011
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package cgl.shindig.usermanage.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.io.IOUtils;
+
+/**
+ * Handles loading contents from resource and file system files.
+ */
+public class ResourceLoader {
+
+ /**
+ * Opens a given path as either a resource or a file, depending on the path
+ * name.
+ *
+ * If path starts with res://, we interpret it as a resource.
+ * Otherwise we attempt to load it as a file.
+ * @param path
+ * @return The opened input stream
+ */
+ public static InputStream open(String path) throws IOException {
+ if (path.startsWith("res://")) {
+ return openResource(path.substring(6));
+ }
+ File file = new File(path);
+ return new FileInputStream(file);
+ }
+
+ /**
+ * @param resource
+ * @return An input stream for the given named resource
+ * @throws FileNotFoundException
+ */
+ public static InputStream openResource(String resource) throws IOException {
+ ClassLoader cl = ResourceLoader.class.getClassLoader();
+ InputStream is = cl.getResourceAsStream(resource.trim());
+ if (is == null) {
+ throw new FileNotFoundException("Can not locate resource: " + resource);
+ }
+ return is;
+ }
+
+ /**
+ * Reads the contents of a resource as a string.
+ *
+ * @param resource
+ * @return Contents of the resource.
+ * @throws IOException
+ */
+ public static String getContent(String resource) throws IOException {
+ return IOUtils.toString(openResource(resource), "UTF-8");
+ }
+
+ /**
+ * @param file
+ * @return The contents of the file (assumed to be UTF-8).
+ * @throws IOException
+ */
+ public static String getContent(File file) throws IOException {
+ return IOUtils.toString(new FileInputStream(file), "UTF-8");
+ }
+}