code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
public class ControllerBuilder {
private static final Logger LOG = Logger.getLogger(ControllerBuilder.class);
private static final ControllerBuilder instance = new ControllerBuilder();
public static void buildSite(HashMap<String, Site> sites, File tmpLocation) {
instance.buildSite(sites, tmpLocation, true);
}
public void buildSite(HashMap<String, Site> sites, File tmpLocation, boolean ok) {
File siteFile = new File(tmpLocation, "TCSiteController.java");
StringBuffer str = addClassStart(sites);
str.append("}\n");
FileOutputStream fos;
try {
fos = new FileOutputStream(siteFile);
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
LOG.warn("Error writing class to " + siteFile.getAbsolutePath() + "(" + e.getMessage() + ")");
}
}
private StringBuffer addClassStart(HashMap<String, Site> sites) {
Site defaultSite = sites.get("xxDefaultxx");
StringBuffer str = new StringBuffer("import javax.servlet.http.*;\n");
str.append("import javax.servlet.*;\n");
str.append("import java.util.*;\n");
str.append("import org.apache.log4j.Logger;\n");
str.append("public class TCSiteController extends uk.co.taylorconsulting.web.controller.WebHelper implements uk.co.taylorconsulting.web.controller.WebFramework {\n");
str.append("\tprivate static final Logger LOG = Logger.getLogger(TCSiteController.class);\n");
str.append("\tprivate static final ").append("TCSiteController instance = new ").append("TCSiteController").append("();\n");
str.append("\tpublic ").append("TCSiteController(){}\n");
str.append("\tpublic static TCSiteController getInstance() {\n");
str.append("\t\treturn instance;\n");
str.append("\t}\n");
str.append("\tprivate enum Actions {system_quicklink");
for (Site s : sites.values()) {
str.append(",");
str.append(s.getName().toLowerCase());
}
str.append(";\n");
str.append("\t}\n");
str.append("\tpublic void process(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
str.append("\t\ttry {\n");
str.append("\t\t\tString req = request.getServletPath().toLowerCase();\n");
str.append("\t\t\treq = req.substring(1);\n");
str.append("\t\t\treq = req.substring(0,req.indexOf(\"").append(defaultSite.getExt().toLowerCase()).append("\")-1);\n");
str.append("\t\t\tLOG.debug(\"action=\"+req);\n");
str.append("\t\t\tActions dispatcher = Actions.valueOf(req);\n");
str.append("\t\t\tswitch (dispatcher) {\n");
Site defSite = null;
for (Site s : sites.values()) {
if (s.getName().equals("xxDefaultxx")) {
defSite = s;
}
str.append("\t\t\t\tcase ").append(s.getName().toLowerCase()).append(": {\n");
str.append("\t\t\t\t\t((Site").append(s.getName()).append(")getCache(\"Site").append(s.getName()).append("\")).process(request, response, servletContext);\n");
str.append("\t\t\t\t\treturn;\n");
str.append("\t\t\t\t}\n");
}
str.append("\t\t\t\tcase system_quicklink: {\n");
str.append("\t\t\t\t\t((SystemQuickLink)getCache(\"SystemQuickLink\")).process(request, response, servletContext);\n");
str.append("\t\t\t\t\treturn;\n");
str.append("\t\t\t\t}\n");
str.append("\t\t\t}\n");
str.append("\t\t} catch (Throwable t) {}\n");
if (defSite != null) {
str.append("\t\t((Site").append(defSite.getName()).append(")getCache(\"Site").append(defSite.getName()).append("\")).process(request, response, servletContext);\n");
} else {
str.append("\t\tLOG.warn(\"Cannot process request. Action not defined for path: \"+request.getServletPath());\n");
}
str.append("\t}\n");
return str;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.security.SecurityProcessor;
import uk.co.taylorconsulting.annoweb.web.builder.data.ActionHolder;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
public class SecurityHandlerBuilder extends SiteBuilder {
private static final Logger LOG = Logger.getLogger(SecurityHandlerBuilder.class);
private static final SecurityHandlerBuilder instance = new SecurityHandlerBuilder();
public static void buildSite(HashMap<String, Site> sites, File tmpLocation) {
instance.buildSite(sites, tmpLocation, true);
}
public void buildSite(HashMap<String, Site> sites, File tmpLocation, boolean ok) {
File siteFile = new File(tmpLocation, "SecurityHandler.java");
StringBuffer str = addClassStart(sites);
str.append("}\n");
FileOutputStream fos;
try {
fos = new FileOutputStream(siteFile);
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
LOG.warn("Error writing class to " + siteFile.getAbsolutePath() + "(" + e.getMessage() + ")");
}
}
private StringBuffer addClassStart(HashMap<String, Site> sites) {
Site s = sites.get("xxDefaultxx");
StringBuffer str = new StringBuffer("import javax.servlet.http.*;\n");
str.append("import javax.servlet.*;\n");
str.append("import java.util.*;\n");
str.append("import org.apache.log4j.Logger;\n");
str.append("public class SecurityHandler extends uk.co.taylorconsulting.web.controller.WebHelper {\n");
str.append("\tprivate static final Logger LOG = Logger.getLogger(SecurityHandler.class);\n");
str.append("\tprivate static final ").append("SecurityHandler instance = new ").append("SecurityHandler").append("();\n");
str.append("\tprivate ").append("SecurityHandler(){}\n");
str.append("\tpublic static SecurityHandler getInstance() {\n");
str.append("\t\treturn instance;\n");
str.append("\t}\n");
str.append("\tpublic static boolean checkSecurity(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, String... roles) {\n");
str.append("\t\treturn instance.checkSecurity(request, response, servletContext, true, roles);\n");
str.append("\t}\n");
str.append("\tpublic boolean checkSecurity(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, boolean ok, String... roles) {\n");
HashMap<String, HashMap<String, Class<? extends SecurityProcessor>>> security = s.getGlobals().getSecurity();
str.append("\t\tString context = request.getServletPath().toLowerCase();\n");
str.append("\t\tif (context.lastIndexOf(\"\\\\\") > 1) {\n");
str.append("\t\t\tcontext = context.substring(0,context.indexOf(\"\\\\\"));\n");
str.append("\t\t} else {\n");
str.append("\t\t\tcontext=null;\n");
str.append("\t\t}\n");
str.append("\t\tString realm=request.getServerName();\n");
boolean first = true;
boolean moreThanOne = false;
for (String realm : security.keySet()) {
if (!realm.equalsIgnoreCase("all")) {
HashMap<String, Class<? extends SecurityProcessor>> contexts = security.get(realm);
if (first) {
first = false;
str.append("\t\tif (realm.equalsIgnoreCase(\"");
} else {
str.append("\t\t} else if (realm.equalsIgnoreCase(\"");
}
str.append(realm).append("\")) {\n");
moreThanOne = addContexts(str, contexts, moreThanOne);
str.append("\t\t}\n");
}
}
if (security.containsKey("all")) {
HashMap<String, Class<? extends SecurityProcessor>> contexts = security.get("all");
if (!first) {
str.append("\t\t} else {\n");
}
moreThanOne = addContexts(str, contexts, moreThanOne);
if (!first) {
str.append("\t\t}\n");
}
}
if (moreThanOne) {
str.append("\t\treturn false;\n");
}
str.append("\t}\n");
str.append("\tpublic void login(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
ActionHolder login = s.getGlobals().getLogin();
ActionHolder notAuthed = s.getGlobals().getNotAuthed();
if (login != null) {
addForward(str, null, login.getMethod().getDeclaringClass(), login.getMethod().getName(), false, "\t\t", s, null);
}
str.append("\t}\n");
str.append("\tpublic void notAuthed(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
if (notAuthed != null) {
addForward(str, null, notAuthed.getMethod().getClass(), notAuthed.getMethod().getName(), false, "\t\t", s, null);
}
str.append("\t}\n");
return str;
}
private boolean addContexts(StringBuffer str, HashMap<String, Class<? extends SecurityProcessor>> contexts, boolean moreThanOne) {
boolean first2 = true;
for (String context : contexts.keySet()) {
if (context.equals("")) {
continue;
}
if (first2) {
first2 = false;
str.append("\t\t\tif (context.equalsIgnoreCase(\"");
} else {
str.append("\t\t\t} else if (context.equalsIgnoreCase(\"");
}
str.append(context).append("\")) {\n");
addContext(str, contexts, context);
}
if (!first2) {
str.append("\t\t\t}\n");
moreThanOne = true;
}
if (contexts.containsKey("")) {
addContext(str, contexts, "");
}
return moreThanOne;
}
private void addContext(StringBuffer str, HashMap<String, Class<? extends SecurityProcessor>> contexts, String context) {
str.append("\t\t\t\tuk.co.taylorconsulting.annotation.security.SecurityProcessor sec = (").append(contexts.get(context).getCanonicalName()).append(")getCache(\"").append(contexts.get(context).getCanonicalName()).append("\");\n");
str.append("\t\t\t\tfor (String role:roles) {\n");
str.append("\t\t\t\t\tuk.co.taylorconsulting.annotation.security.SecurityOptions resp = sec.isRoleValid(role,request);\n");
str.append("\t\t\t\t\tswitch(resp) {\n");
str.append("\t\t\t\t\t\tcase login: {\n");
str.append("\t\t\t\t\t\t\tlogin(request, response, servletContext);\n");
str.append("\t\t\t\t\t\t\treturn false;\n");
str.append("\t\t\t\t\t\t}\n");
str.append("\t\t\t\t\t\tcase notAuthorised: {\n");
str.append("\t\t\t\t\t\t\tnotAuthed(request, response, servletContext);\n");
str.append("\t\t\t\t\t\t\treturn false;\n");
str.append("\t\t\t\t\t\t}\n");
str.append("\t\t\t\t\t}\n");
str.append("\t\t\t\t}\n");
str.append("\t\t\t\treturn true;\n");
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder.data;
import java.util.HashMap;
import uk.co.taylorconsulting.annoweb.annotation.injection.DefaultCacheValue;
import uk.co.taylorconsulting.annoweb.annotation.injection.DefaultValue;
import uk.co.taylorconsulting.annoweb.annotation.injection.Inject;
public class FormData {
private Class<?> clazz;
private HashMap<String, DefaultCacheValue> defaultCacheValues = new HashMap<String, DefaultCacheValue>();
private HashMap<String, DefaultValue> defaultValues = new HashMap<String, DefaultValue>();
private HashMap<String, Inject> injects = new HashMap<String, Inject>();
public FormData(Class<?> clazz) {
this.clazz = clazz;
}
public Class<?> getClazz() {
return clazz;
}
public void addDefaultCache(String key, DefaultCacheValue defCache) {
this.defaultCacheValues.put(key, defCache);
}
public void addDefaultValue(String key, DefaultValue defValue) {
this.defaultValues.put(key, defValue);
}
public void addInjects(String key, Inject inject) {
this.injects.put(key, inject);
}
public HashMap<String, DefaultCacheValue> getDefaultCacheValues() {
return defaultCacheValues;
}
public HashMap<String, DefaultValue> getDefaultValues() {
return defaultValues;
}
public HashMap<String, Inject> getInjects() {
return injects;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder.data;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import uk.co.taylorconsulting.annoweb.annotation.exception.CatchException;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Validator;
import uk.co.taylorconsulting.annoweb.annotation.security.SecurityHandler;
import uk.co.taylorconsulting.annoweb.annotation.security.SecurityProcessor;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalDefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalForward;
import uk.co.taylorconsulting.annoweb.annotation.web.QuickLink;
public class Globals {
private HashMap<Class<? extends Throwable>, Method> exceptionHandlers = new HashMap<Class<? extends Throwable>, Method>();
public HashMap<String, FormData> forms = new HashMap<String, FormData>();
private HashMap<String, HashMap<String, Class<? extends SecurityProcessor>>> security = new HashMap<String, HashMap<String, Class<? extends SecurityProcessor>>>();
private GlobalDefaultForward defaultForward;
private HashMap<String, GlobalForward> forwards = new HashMap<String, GlobalForward>();
private HashMap<String, Method> validators = new HashMap<String, Method>();
private HashMap<Method, ActionHolder> allActions = new HashMap<Method, ActionHolder>();
private ActionHolder login;
private ActionHolder notAuthed;
private HashMap<String, ActionHolder> quickLinks = new HashMap<String, ActionHolder>();
public ActionHolder getLogin() {
return login;
}
public void setLogin(ActionHolder login) {
if (this.login == null) {
this.login = login;
}
}
public ActionHolder getNotAuthed() {
return notAuthed;
}
public void setNotAuthed(ActionHolder notAuthed) {
if (this.notAuthed == null) {
this.notAuthed = notAuthed;
}
}
public void addAction(Method m, ActionHolder ah) {
allActions.put(m, ah);
}
public ActionHolder getAction(Method m) {
return allActions.get(m);
}
public void addExceptionHandler(Method method, CatchException exceptionHandler) {
if (!exceptionHandlers.containsKey(exceptionHandler.value())) {
exceptionHandlers.put(exceptionHandler.value(), method);
}
}
public Method getExceptionHandler(Class<? extends Throwable> exception) {
if (exceptionHandlers.containsKey(exception)) {
return exceptionHandlers.get(exception);
}
return exceptionHandlers.get(Throwable.class);
}
public void addForm(Class<?> clazz) {
if (!forms.containsKey(clazz.getCanonicalName())) {
forms.put(clazz.getCanonicalName(), new FormData(clazz));
}
}
public FormData getForm(String name) {
return forms.get(name);
}
public Collection<FormData> getForms() {
return forms.values();
}
public void addSecurityHandler(SecurityHandler a, Class<? extends SecurityProcessor> thisClass) {
HashMap<String, Class<? extends SecurityProcessor>> realm = security.get(a.realm());
if (realm == null) {
realm = new HashMap<String, Class<? extends SecurityProcessor>>();
security.put(a.realm(), realm);
}
if (!realm.containsKey(a.context())) {
realm.put(a.context(), thisClass);
}
}
public void setDefaultForward(GlobalDefaultForward defaultForward) {
this.defaultForward = defaultForward;
}
public void addForward(GlobalForward gf) {
if (!forwards.containsKey(gf.name())) {
forwards.put(gf.name(), gf);
}
}
public GlobalForward getForward(String name) {
return forwards.get(name);
}
public Collection<GlobalForward> getForwards() {
return forwards.values();
}
public void addValidator(Validator a, Method m) {
validators.put(a.value(), m);
}
public GlobalDefaultForward getDefaultForward() {
return defaultForward;
}
public HashMap<Class<? extends Throwable>, Method> getExceptionHandlers() {
return exceptionHandlers;
}
public HashMap<String, HashMap<String, Class<? extends SecurityProcessor>>> getSecurity() {
return security;
}
public void addQuickLink(ActionHolder ah, QuickLink annotation) {
if (!quickLinks.containsKey(annotation.link())) {
ah.setQuickLinks(annotation);
quickLinks.put(annotation.link(), ah);
}
}
public HashMap<String, ActionHolder> getQuickLinks() {
return quickLinks;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder.data;
import java.lang.reflect.Method;
public class SiteHolder {
private Site site;
private Method method;
private Class<?> clazz;
private ActionHolder ah;
public SiteHolder(Site site, Method method, Class<?> clazz, ActionHolder ah) {
this.site = site;
this.method = method;
this.clazz = clazz;
this.ah = ah;
}
public Site getSite() {
return site;
}
public Method getMethod() {
return method;
}
public Class<?> getClazz() {
return clazz;
}
public ActionHolder getAh() {
return ah;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder.data;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.action.Action;
import uk.co.taylorconsulting.annoweb.annotation.security.Role;
import uk.co.taylorconsulting.annoweb.annotation.web.DefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forward;
import uk.co.taylorconsulting.annoweb.annotation.web.Web;
public class Site {
private String name;
private String contextClass;
private String ext;
private Globals globals;
private HashMap<Class<?>, ArrayList<Role>> roles = new HashMap<Class<?>, ArrayList<Role>>();
private HashMap<Class<?>, DefaultForward> defaultForwards = new HashMap<Class<?>, DefaultForward>();
private HashMap<Class<?>, ArrayList<Forward>> classForwards = new HashMap<Class<?>, ArrayList<Forward>>();
private String dispatch;
private HashMap<String, ActionHolder> actions = new HashMap<String, ActionHolder>();
private Method defaultAction;
private static final Logger LOG = Logger.getLogger(Site.class);
public Site(String name, String contextClass) {
this.name = name.toLowerCase();
this.contextClass = contextClass;
}
public Site(String name, String contextClass, String ext) {
this.name = name.toLowerCase();
this.contextClass = contextClass;
this.ext = ext;
}
public void setName(String name) {
this.name = name.toLowerCase();
}
public void setContextClass(String contextClass) {
this.contextClass = contextClass;
}
public void setExt(String ext) {
this.ext = ext;
}
public void setGlobals(Globals globals) {
this.globals = globals;
}
public void addRole(Role role, Class<?> thisClass) {
ArrayList<Role> roleList = roles.get(thisClass);
if (roleList == null) {
roleList = new ArrayList<Role>();
roles.put(thisClass, roleList);
}
roleList.add(role);
}
public void addDefaultForward(DefaultForward defaultForward, Class<?> thisClass) {
if (!defaultForwards.containsKey(thisClass)) {
defaultForwards.put(thisClass, defaultForward);
}
}
public void addForward(Forward forward, Class<?> thisClass) {
ArrayList<Forward> forwards = classForwards.get(thisClass);
if (forwards == null) {
forwards = new ArrayList<Forward>();
classForwards.put(thisClass, forwards);
}
forwards.add(forward);
}
public void setWeb(Web a) {
if (dispatch == null || dispatch.equalsIgnoreCase("dispatch")) {
dispatch = a.dispatch();
}
name = a.view();
}
public void merge(Site tmp) {
if (dispatch == null || dispatch.equalsIgnoreCase("dispatch")) {
dispatch = tmp.dispatch;
}
for (Class<?> c : tmp.roles.keySet()) {
if (roles.containsKey(c)) {
roles.get(c).addAll(tmp.roles.get(c));
} else {
roles.put(c, tmp.roles.get(c));
}
}
for (Class<?> c : tmp.defaultForwards.keySet()) {
if (!defaultForwards.containsKey(c)) {
defaultForwards.put(c, tmp.defaultForwards.get(c));
}
}
for (Class<?> c : tmp.classForwards.keySet()) {
if (classForwards.containsKey(c)) {
classForwards.get(c).addAll(tmp.classForwards.get(c));
} else {
classForwards.put(c, tmp.classForwards.get(c));
}
}
if (defaultAction == null) {
defaultAction = tmp.defaultAction;
}
for (String s : tmp.actions.keySet()) {
if (!actions.containsKey(s)) {
ActionHolder ah = tmp.actions.get(s);
ah.setSite(this);
actions.put(s, ah);
}
}
}
public String getName() {
return name;
}
public ActionHolder addAction(Action action, Method method) {
if (!actions.containsKey(action.dispatch() + ":" + action.value())) {
ActionHolder ah = new ActionHolder(action, method, this);
actions.put(action.dispatch() + ":" + action.value(), ah);
globals.addAction(method, ah);
return ah;
}
return null;
}
public void setDefaultAction(Method defaultAction) {
if (this.defaultAction == null) {
this.defaultAction = defaultAction;
}
}
public void addActionRole(Action action, Role role) {
ActionHolder ah = actions.get(action.dispatch() + ":" + action.value());
if (ah != null) {
ah.addRole(role);
}
}
public void addActionDefaultForward(DefaultForward forward, Action action) {
ActionHolder ah = actions.get(action.dispatch() + ":" + action.value());
if (ah != null) {
ah.setDefaultForward(forward);
}
}
public void addActionForward(Forward forward, Action action) {
ActionHolder ah = actions.get(action.dispatch() + ":" + action.value());
if (ah != null) {
ah.addForward(forward);
}
}
public void debug() {
if (LOG.isDebugEnabled()) {
StringBuffer str = new StringBuffer("Site -- ").append(name).append(" --\n");
str.append("context class: ").append(contextClass).append("\n");
str.append("ext:").append(ext).append("\n");
str.append("Roles:\n");
for (Class<?> c : roles.keySet()) {
ArrayList<Role> rs = roles.get(c);
for (Role r : rs) {
str.append(r.value()).append(", realm=").append(r.realm()).append("\n");
}
}
str.append("dispatch=").append(dispatch).append("\n");
str.append("Default Forwards:\n");
for (Class<?> c : defaultForwards.keySet()) {
str.append(c.getCanonicalName()).append(":").append(defaultForwards.get(c).value()).append("\n");
}
str.append("Class Forwards:\n");
for (Class<?> c : classForwards.keySet()) {
str.append(c.getCanonicalName()).append("\n");
for (Forward f : classForwards.get(c)) {
str.append(" ").append(f.name()).append(", path=").append(f.path()).append(", web=").append(f.web().getCanonicalName()).append(", method=").append(f.method()).append(", redirect=").append(f.redirect()).append("\n");
}
}
if (defaultAction == null) {
str.append("defaultAction = null\n");
} else {
str.append("defaultAction =" + defaultAction.getDeclaringClass().getCanonicalName()).append(":").append(defaultAction.getName()).append("\n");
}
str.append("Actions:");
for (String a : actions.keySet()) {
ActionHolder ah = actions.get(a);
str.append(ah.toString());
}
LOG.debug(str.toString());
}
}
public HashMap<String, ActionHolder> getActions() {
return actions;
}
public Method getDefaultAction() {
return defaultAction;
}
public Globals getGlobals() {
return globals;
}
public HashMap<Class<?>, ArrayList<Role>> getRoles() {
return roles;
}
public HashMap<Class<?>, DefaultForward> getDefaultForwards() {
return defaultForwards;
}
public HashMap<Class<?>, ArrayList<Forward>> getClassForwards() {
return classForwards;
}
public String getDispatch() {
return dispatch;
}
public ArrayList<Forward> getForward(Class<?> clazz) {
ArrayList<Forward> retVal = classForwards.get(clazz);
if (retVal == null) {
retVal = new ArrayList<Forward>();
}
return retVal;
}
public String getExt() {
return ext;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder.data;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import uk.co.taylorconsulting.annoweb.annotation.action.Action;
import uk.co.taylorconsulting.annoweb.annotation.security.Role;
import uk.co.taylorconsulting.annoweb.annotation.web.DefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forward;
import uk.co.taylorconsulting.annoweb.annotation.web.QuickLink;
public class ActionHolder {
private Action action;
private Method method;
private ArrayList<Role> roles = new ArrayList<Role>();
private DefaultForward defaultForward;
private HashMap<String, Forward> forwards = new HashMap<String, Forward>();
private Site site;
private QuickLink quickLinks;
public ActionHolder(Action action, Method method, Site site) {
this.action = action;
this.method = method;
this.site = site;
}
public Action getAction() {
return action;
}
public Method getMethod() {
return method;
}
public void addRole(Role role) {
roles.add(role);
}
public void setDefaultForward(DefaultForward forward) {
this.defaultForward = forward;
}
public void addForward(Forward forward) {
if (!forwards.containsKey(forward.name())) {
forwards.put(forward.name(), forward);
}
}
public String toString() {
StringBuffer str = new StringBuffer();
str.append(" action:").append(action.value()).append("\n");
str.append(" method:").append(method.getDeclaringClass().getCanonicalName()).append(":").append(method.getName()).append("\n");
str.append(" Roles:\n");
for (Role r : roles) {
str.append(" ").append(r.value()).append(", realm=").append(r.realm()).append("\n");
}
str.append(" Default Forward:\n");
if (defaultForward == null) {
str.append("none\n");
} else {
str.append(defaultForward.value()).append("\n");
}
str.append(" Forwards:\n");
for (Forward f : forwards.values()) {
str.append(" ").append(f.name()).append(", path=").append(f.path()).append(", web=").append(f.web().getCanonicalName()).append(", method=").append(f.method()).append(", redirect=").append(f.redirect()).append("\n");
}
return str.toString();
}
public Forward getForward(String name) {
return forwards.get(name);
}
public Collection<Forward> getForwards() {
return forwards.values();
}
public DefaultForward getDefaultForward() {
return defaultForward;
}
public Site getSite() {
return site;
}
public void setSite(Site site) {
this.site = site;
}
public ArrayList<Role> getRoles() {
return roles;
}
public QuickLink getQuickLinks() {
return quickLinks;
}
public void setQuickLinks(QuickLink quickLinks) {
this.quickLinks = quickLinks;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.math.BigDecimal;
import org.apache.commons.fileupload.FileItem;
public enum MethodTypeEnum {
String(String.class, "getString", "null"), primativeByte(byte.class, "getPByte", "-1"), Byte(Byte.class, "getByte", "null"), primativeShort(short.class, "getPShort", "-1"), Short(Short.class, "getShort", "null"), primativeInt(
int.class, "getInt", "-1"), Integer(Integer.class, "getInteger", "null"), primativeLong(long.class, "getPLong", "-1"), Long(Long.class, "getLong", "null"), primativeFloat(float.class, "getPFloat", "-1.0"), Float(Float.class,
"getFloat", "null"), primativeDouble(double.class, "getPDouble", "-1.0"), Double(Double.class, "getDouble", "null"), primativeBoolean(boolean.class, "getPBoolean", "false"), Boolean(Boolean.class, "getBoolean", "null"), BigDecimal(
BigDecimal.class, "getBigDecimal", "null"), primativeChar(char.class, "getPChar", "' '"), Char(Character.class, "getCharacter", "null"), StringA(String[].class, "getStringA", "null"), primativeByteA(byte[].class, "getPByteA",
"-1"), ByteA(Byte[].class, "getByteA", "null"), primativeShortA(short[].class, "getPShortA", "-1"), ShortA(Short[].class, "getShortA", "null"), primativeIntA(int[].class, "getIntA", "-1"), IntegerA(Integer[].class,
"getIntegerA", "null"), primativeLongA(long[].class, "getPLongA", "-1"), LongA(Long[].class, "getLongA", "null"), primativeFloatA(float[].class, "getPFloatA", "-1.0"), FloatA(Float[].class, "getFloatA", "null"), primativeDoubleA(
double[].class, "getPDoubleA", "-1.0"), DoubleA(Double[].class, "getDoubleA", "null"), primativeBooleanA(boolean[].class, "getPBooleanA", "false"), BooleanA(Boolean[].class, "getBooleanA", "null"), primativeCharA(char[].class,
"getPCharA", "'\u0000'"), CharA(Character[].class, "getCharacterA", "null"), BigDecimalA(BigDecimal[].class, "getBigDecimalA", "null"), FileItem(FileItem.class, "getFileItem", "null"), FileItemA(FileItem[].class,
"getFileItemA", "null");
private Class<?> clazz;
private String method;
private String defaultValue;
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
private MethodTypeEnum(Class<?> clazz, String method, String defaultValue) {
this.method = method;
this.clazz = clazz;
this.defaultValue = defaultValue;
}
public static MethodTypeEnum getByClass(Class<?> clazz) {
for (MethodTypeEnum o : MethodTypeEnum.values()) {
if (o.getClazz() == clazz) {
return o;
}
}
return null;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.web.controller.WebFramework;
import com.sun.tools.javac.Main;
public class Compiler {
private static final Logger LOG = Logger.getLogger(Compiler.class);
protected String removeDot(String clazzName) {
while (clazzName.indexOf(".") > 0) {
clazzName = clazzName.replace(".", "_");
}
return clazzName;
}
protected void makeDir(File tmp) {
if (tmp.getParentFile() == null)
return;
while (!tmp.getParentFile().exists()) {
makeDir(tmp.getParentFile());
}
if (!tmp.exists()) {
tmp.mkdir();
}
}
protected WebFramework compile(File path) {
try {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
LOG.debug("Loading libraries");
String[] p = getParams(path);
LOG.debug("Compiling with parameters :" + toString(p));
String[] p2 = new String[p.length + path.listFiles().length];
System.arraycopy(p, 0, p2, 0, p.length);
int i = p.length;
for (File f : path.listFiles()) {
p2[i++] = f.getAbsolutePath();
}
Main.compile(p2, pw);
Class<?> c = Class.forName("TCSiteController");
return (WebFramework) c.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
private String toString(String[] p) {
StringBuffer str = new StringBuffer();
boolean first = true;
for (String s : p) {
if (first) {
first = false;
} else {
str.append(",");
}
str.append(s);
}
return str.toString();
}
private String[] getParams(File path) {
ArrayList<String> params = new ArrayList<String>();
params.add("-cp");
StringBuffer cp = new StringBuffer(".").append(System.getProperty("path.separator")).append(path.getParentFile().getAbsolutePath()).append(File.separator).append("WEB-INF").append(File.separator).append("classes");
addParentLibs(path, cp);
addWebLibs(path, cp);
addServerLibs(path, cp);
params.add(cp.toString());
params.add("-d");
params.add(path.getParentFile().getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "classes");
String[] p = new String[params.size()];
params.toArray(p);
return p;
}
private void addServerLibs(File path, StringBuffer cp) {
path = path.getParentFile();
while (path != null && path.exists()) {
File lib = null;
File common = null;
File serverLib = null;
try {
lib = new File(path, "lib");
} catch (Exception e) {
lib = null;
}
try {
common = new File(path, "common");
} catch (Exception e) {
common = null;
}
try {
serverLib = new File(path, "server");
serverLib = new File(serverLib, "lib");
} catch (Exception e) {
serverLib = null;
}
if (lib != null && lib.exists()) {
addLibs(lib, cp);
}
if (common != null && common.exists()) {
addLibs(new File(common, "endorsed"), cp);
addLibs(new File(common, "i18n"), cp);
addLibs(new File(common, "lib"), cp);
}
path = path.getParentFile();
}
}
private void addLibs(File dir, StringBuffer cp) {
if (dir.exists()) {
for (File child : dir.listFiles()) {
addJarToClasspath(cp, child);
}
}
}
private void addWebLibs(File path, StringBuffer cp) {
File lib = new File(new File(path.getParentFile(), "WEB-INF"), "lib");
if (lib.exists()) {
for (File child : lib.listFiles()) {
addJarToClasspath(cp, child);
}
}
}
private void addParentLibs(File path, StringBuffer cp) {
File lib = new File(path.getParentFile(), "lib");
if (lib.exists()) {
for (File child : lib.listFiles()) {
addJarToClasspath(cp, child);
}
}
}
private void addJarToClasspath(StringBuffer cp, File child) {
if (child.getName().endsWith(".jar")) {
cp.append(System.getProperty("path.separator"));
cp.append(child.getAbsolutePath());
}
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.action.Action;
import uk.co.taylorconsulting.annoweb.annotation.action.Default;
import uk.co.taylorconsulting.annoweb.annotation.action.Init;
import uk.co.taylorconsulting.annoweb.annotation.exception.CatchException;
import uk.co.taylorconsulting.annoweb.annotation.exception.CatchExceptions;
import uk.co.taylorconsulting.annoweb.annotation.form.Form;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Validator;
import uk.co.taylorconsulting.annoweb.annotation.security.Login;
import uk.co.taylorconsulting.annoweb.annotation.security.NotAuthorised;
import uk.co.taylorconsulting.annoweb.annotation.security.Role;
import uk.co.taylorconsulting.annoweb.annotation.security.Roles;
import uk.co.taylorconsulting.annoweb.annotation.security.SecurityHandler;
import uk.co.taylorconsulting.annoweb.annotation.security.SecurityProcessor;
import uk.co.taylorconsulting.annoweb.annotation.web.DefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forwards;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalDefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalForward;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalForwards;
import uk.co.taylorconsulting.annoweb.annotation.web.QuickLink;
import uk.co.taylorconsulting.annoweb.annotation.web.Web;
import uk.co.taylorconsulting.annoweb.web.builder.data.ActionHolder;
import uk.co.taylorconsulting.annoweb.web.builder.data.FormData;
import uk.co.taylorconsulting.annoweb.web.builder.data.Globals;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
import uk.co.taylorconsulting.annoweb.web.builder.data.SiteHolder;
import uk.co.taylorconsulting.annoweb.web.controller.WebFramework;
public class WebBuilder {
private static Logger LOG = Logger.getLogger(WebBuilder.class);
public void process(String classpath, String ext, HashMap<String, Site> sites) {
String[] bits = classpath.split(System.getProperty("path.separator"));
if (sites.size() == 0) {
sites.put("xxDefaultxx", new Site("xxDefaultxx", null, ext));
}
Globals globals = new Globals();
for (Site s : sites.values()) {
s.setGlobals(globals);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Building Web app with Classpath = " + classpath);
}
for (String s : bits) {
processPath(sites, s, globals);
}
}
private void processPath(HashMap<String, Site> sites, String path, Globals globals) {
try {
File f = new File(path);
if (f.exists()) {
if (f.isDirectory()) {
processDir(f, sites, globals);
} else if (f.isFile()) {
processFile(f, sites, globals);
}
}
} catch (java.lang.Exception e) {
LOG.warn("Error building site", e);
}
}
private void processDir(File dir, HashMap<String, Site> sites, Globals globals) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing dir: " + dir.getAbsolutePath());
}
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
processDir(f, sites, globals);
}
processFile(f, sites, globals);
}
}
private void processFile(File file, HashMap<String, Site> sites, Globals globals) {
String name = file.getName().toLowerCase();
if (LOG.isDebugEnabled()) {
LOG.debug("Processing file: " + file.getAbsoluteFile().toString());
}
if (name.endsWith(".class")) {
processClass(file, sites, globals);
}
}
private void processClass(File file, HashMap<String, Site> sites, Globals globals) {
Class<?> clazz = getCanonacleName(file);
Site tmp = new Site("tmp", null);
tmp.setGlobals(globals);
if (LOG.isDebugEnabled()) {
LOG.debug("Processing class: " + clazz.getCanonicalName());
}
Site classSite = null;
for (Annotation a : clazz.getAnnotations()) {
classSite = processClassAnnotation(clazz, a, sites, globals, classSite, tmp);
}
if (classSite == null) {
Site defaultSite = sites.get("xxDefaultxx");
defaultSite.merge(tmp);
classSite = defaultSite;
} else {
if (sites.containsKey(classSite.getName())) {
tmp = sites.get(classSite.getName());
tmp.merge(classSite);
classSite = tmp;
} else {
sites.put(classSite.getName(), classSite);
}
}
tmp = new Site("tmp", null);
tmp.setGlobals(globals);
for (Method m : clazz.getMethods()) {
Site methodSite = null;
Action action = m.getAnnotation(Action.class);
if (action != null) {
ActionHolder ah = tmp.addAction((Action) action, m);
for (Annotation a : m.getAnnotations()) {
methodSite = processMethodAnnotation(clazz, m, action, a, sites, globals, methodSite, tmp);
}
if (methodSite == null) {
classSite.merge(tmp);
} else {
sites.put(methodSite.getName(), methodSite);
}
if (m.getAnnotation(Login.class) != null) {
globals.setLogin(ah);
}
if (m.getAnnotation(NotAuthorised.class) != null) {
globals.setNotAuthed(ah);
}
if (m.getAnnotation(QuickLink.class) != null) {
globals.addQuickLink(ah, m.getAnnotation(QuickLink.class));
}
} else if (m.getAnnotation(CatchException.class) != null) {
CatchException ce = m.getAnnotation(CatchException.class);
globals.addExceptionHandler(m, ce);
} else if (m.getAnnotation(CatchExceptions.class) != null) {
CatchExceptions ces = m.getAnnotation(CatchExceptions.class);
for (CatchException ce : ces.value()) {
globals.addExceptionHandler(m, ce);
}
}
}
}
private Site processMethodAnnotation(Class<?> clazz, Method m, Action action, Annotation a, HashMap<String, Site> sites, Globals globals, Site methodSite, Site tmp) {
Site site = getSite(methodSite, tmp);
if (a instanceof Action) {} else if (a instanceof Default) {
site.setDefaultAction(m);
} else if (a instanceof CatchException) {
globals.addExceptionHandler(m, (CatchException) a);
} else if (a instanceof CatchExceptions) {
for (CatchException ca : ((CatchExceptions) a).value()) {
globals.addExceptionHandler(m, (CatchException) ca);
}
} else if (a instanceof Validator) {
globals.addValidator((Validator) a, m);
} else if (a instanceof Role) {
site.addActionRole(action, (Role) a);
} else if (a instanceof Roles) {
for (Role r : ((Roles) a).value()) {
site.addActionRole(action, r);
}
} else if (a instanceof DefaultForward) {
site.addActionDefaultForward((DefaultForward) a, action);
} else if (a instanceof Forward) {
site.addActionForward((Forward) a, action);
} else if (a instanceof Forwards) {
for (Forward f : ((Forwards) a).value()) {
site.addActionForward(f, action);
}
} else if (a instanceof Web) {
if (site == tmp) {
site.setWeb((Web) a);
methodSite = site;
}
}
return methodSite;
}
@SuppressWarnings("unchecked")
private Site processClassAnnotation(final Class<?> clazz, Annotation annotation, HashMap<String, Site> sites, Globals globals, Site classSite, Site tmp) {
Site site = getSite(classSite, tmp);
if (annotation instanceof Init) {
try {
if (clazz.getConstructor((Class<?>[]) null) != null) {
Thread t = new Thread() {
public void run() {
try {
clazz.newInstance();
} catch (Exception e) {
LOG.warn("Error while instantiating web init class " + clazz.getCanonicalName(), e);
}
}
};
t.start();
}
} catch (Exception e) {
LOG.warn("Error while instantiating web init class " + clazz.getCanonicalName(), e);
}
} else if (annotation instanceof Form) {
globals.addForm(clazz);
} else if (annotation instanceof Role) {
site.addRole((Role) annotation, clazz);
} else if (annotation instanceof Roles) {
for (Role r : ((Roles) annotation).value()) {
site.addRole(r, clazz);
}
} else if (annotation instanceof SecurityHandler) {
if (SecurityProcessor.class.isAssignableFrom(clazz)) {
Class<? extends SecurityProcessor> sp = (Class<? extends SecurityProcessor>) clazz;
globals.addSecurityHandler((SecurityHandler) annotation, sp);
}
} else if (annotation instanceof DefaultForward) {
site.addDefaultForward((DefaultForward) annotation, clazz);
} else if (annotation instanceof Forward) {
site.addForward((Forward) annotation, clazz);
} else if (annotation instanceof Forwards) {
for (Forward f : ((Forwards) annotation).value()) {
site.addForward(f, clazz);
}
} else if (annotation instanceof GlobalDefaultForward) {
globals.setDefaultForward((GlobalDefaultForward) annotation);
} else if (annotation instanceof GlobalForward) {
globals.addForward((GlobalForward) annotation);
} else if (annotation instanceof GlobalForwards) {
for (GlobalForward gf : ((GlobalForwards) annotation).value()) {
globals.addForward(gf);
}
} else if (annotation instanceof Web) {
if (site == tmp) {
site.setWeb((Web) annotation);
classSite = site;
}
}
return classSite;
}
private Site getSite(Site classSite, Site tmp) {
if (classSite == null)
return tmp;
return classSite;
}
private Class<?> getCanonacleName(File clazz) {
String clazzName = clazz.getName();
if (clazzName.indexOf(".") > 0) {
clazzName = clazzName.substring(0, clazzName.indexOf("."));
}
clazz = clazz.getParentFile();
while (clazz != null) {
try {
return Class.forName(clazzName);
} catch (Exception e) {}
clazzName = clazz.getName() + "." + clazzName;
clazz = clazz.getParentFile();
}
return null;
}
public WebFramework build(HashMap<String, Site> sites, String classpath) {
String[] bits = classpath.split(System.getProperty("path.separator"));
File tmpLocation = new File(new File(bits[0]), "tmp");
HashMap<String, SiteHolder> methods = new HashMap<String, SiteHolder>();
Globals globals = null;
for (Site s : sites.values()) {
for (ActionHolder ah : s.getActions().values()) {
Method m = ah.getMethod();
methods.put(m.getDeclaringClass().getCanonicalName() + ":" + m.getName(), new SiteHolder(s, m, m.getDeclaringClass(), ah));
}
}
mkdir(tmpLocation);
for (Site s : sites.values()) {
if (globals == null) {
globals = s.getGlobals();
}
SiteBuilder.buildSite(s, tmpLocation, methods);
}
for (FormData fd : globals.getForms()) {
FormBuilder.buildFormHelper(fd, tmpLocation, globals);
}
QuicklinkBuilder.buildSite(sites, tmpLocation);
ControllerBuilder.buildSite(sites, tmpLocation);
GlobalDataBuilder.buildSite(sites, tmpLocation);
SecurityHandlerBuilder.buildSite(sites, tmpLocation);
Compiler c = new Compiler();
return c.compile(tmpLocation);
}
private void mkdir(File tmpLocation) {
if (!tmpLocation.exists()) {
mkdir(tmpLocation.getParentFile());
tmpLocation.mkdir();
}
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Required;
import uk.co.taylorconsulting.annoweb.annotation.web.DefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forwards;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalForward;
import uk.co.taylorconsulting.annoweb.web.builder.data.ActionHolder;
import uk.co.taylorconsulting.annoweb.web.builder.data.Globals;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
public class GlobalDataBuilder extends SiteBuilder {
private static final Logger LOG = Logger.getLogger(GlobalDataBuilder.class);
private static final GlobalDataBuilder instance = new GlobalDataBuilder();
public static void buildSite(HashMap<String, Site> sites, File tmpLocation) {
instance.buildSite(sites, tmpLocation, true);
}
public void buildSite(HashMap<String, Site> sites, File tmpLocation, boolean ok) {
File siteFile = new File(tmpLocation, "GlobalDataHandler.java");
StringBuffer str = addClassStart(sites);
str.append("}\n");
FileOutputStream fos;
try {
fos = new FileOutputStream(siteFile);
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
LOG.warn("Error writing class to " + siteFile.getAbsolutePath() + "(" + e.getMessage() + ")");
}
}
private StringBuffer addClassStart(HashMap<String, Site> sites) {
StringBuffer str = new StringBuffer("import javax.servlet.http.*;\n");
str.append("import javax.servlet.*;\n");
str.append("import java.util.*;\n");
str.append("import org.apache.log4j.Logger;\n");
str.append("public class GlobalDataHandler extends uk.co.taylorconsulting.web.controller.WebHelper {\n");
str.append("\tprivate static final Logger LOG = Logger.getLogger(GlobalDataHandler.class);\n");
str.append("\tprivate static final ").append("GlobalDataHandler instance = new ").append("GlobalDataHandler").append("();\n");
str.append("\tprivate ").append("GlobalDataHandler(){}\n");
str.append("\tpublic static GlobalDataHandler getInstance() {\n");
str.append("\t\treturn instance;\n");
str.append("\t}\n");
boolean first = true;
str.append("\tpublic static boolean globalForward(String forwardName,HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) throws Throwable {\n");
str.append("\t\treturn instance.globalForward(forwardName, request, response, servletContext, true);\n");
str.append("\t}\n");
str.append("\tpublic boolean globalForward(String forwardName,HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, boolean ok) throws Throwable {\n");
first = true;
Site s = sites.get("xxDefaultxx");
Globals globals = s.getGlobals();
for (GlobalForward f : globals.getForwards()) {
if (first) {
str.append("\t\tif(");
first = false;
} else {
str.append("\t\t} else if(");
}
str.append("\"").append(f.name()).append("\".equals(forwardName)) {\n");
addForward(str, f.path(), f.web(), f.method(), f.redirect(), "\t\t\t", s, "true");
}
str.append("\t\t}\n");
str.append("\t\treturn false;\n");
str.append("\t}\n");
str.append("\tpublic static void handleException(Throwable t,HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
str.append("\t\tinstance.handleException(t,request, response, servletContext,0, true);\n");
str.append("\t}\n");
str.append("\tpublic static void handleException(Throwable t,HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, int tries) {\n");
str.append("\t\tinstance.handleException(t,request, response, servletContext,tries, true);\n");
str.append("\t}\n");
str.append("\tpublic void handleException(Throwable t,HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, int tries, boolean ok) {\n");
str.append("\t\trequest.setAttribute(\"exception\",t);\n");
str.append("\t\ttry {\n");
str.append("\t\t\tresponse.reset();\n");
first = true;
for (Class<? extends Throwable> clazz : processHandlers(globals.getExceptionHandlers())) {
if (first) {
first = false;
str.append("\t\tif(");
} else {
str.append("\t\t} else if(");
}
str.append("t instanceof ").append(clazz.getCanonicalName()).append(") {\n");
Method m = globals.getExceptionHandler(clazz);
str.append("\t\t\t").append(m.getDeclaringClass().getCanonicalName()).append(" actionClass = (").append(m.getDeclaringClass().getCanonicalName()).append(")getCache(\"").append(m.getDeclaringClass().getCanonicalName()).append(
"\");\n");
if (m.getReturnType() == String.class) {
str.append("\t\t\tString retValue = actionClass.");
} else {
str.append("\t\t\tactionClass.");
}
str.append(m.getName()).append("(").append(buildMethodSigniture(m, m.getAnnotation(Required.class), false, s.getGlobals())).append(");\n");
ActionHolder ah = new ActionHolder(null, null, s);
if (m.getAnnotation(Forward.class) != null) {
Forward f = m.getAnnotation(Forward.class);
ah.addForward(f);
}
if (m.getAnnotation(Forwards.class) != null) {
Forwards fs = m.getAnnotation(Forwards.class);
for (Forward f : fs.value()) {
ah.addForward(f);
}
}
if (m.getAnnotation(DefaultForward.class) != null) {
ah.setDefaultForward(m.getAnnotation(DefaultForward.class));
}
if (m.getReturnType() == String.class) {
// test value to forward
boolean firstP = true;
if (m.getAnnotation(Forward.class) != null) {
if (firstP) {
str.append("\t\t\t");
firstP = false;
} else {
str.append("\t\t\t} else ");
}
Forward f = m.getAnnotation(Forward.class);
addForward(str, f.path(), f.web(), f.method(), f.redirect(), "\t\t\t\t", s, null);
}
if (m.getAnnotation(Forwards.class) != null) {
Forwards fs = m.getAnnotation(Forwards.class);
for (Forward f : fs.value()) {
if (firstP) {
str.append("\t\t\t");
firstP = false;
} else {
str.append("\t\t\t} else ");
}
addForward(str, f.path(), f.web(), f.method(), f.redirect(), "\t\t\t\t", s, null);
}
}
if (firstP) {
str.append("\t\t\t");
firstP = false;
} else {
str.append("\t\t\t} else ");
}
str.append("if (!GlobalDataHandler.globalForward(retValue, request, response, servletContext)) {\n");
// do default forwards
addDefaultForward(s, str, ah, "\t\t\t\t");
} else {
// send to default forward
addDefaultForward(s, str, ah, "\t\t\t");
}
}
str.append("\t\t}\n");
str.append("\t\t} catch (Throwable t2) {t2.printStackTrace();}\n");
str.append("\t}\n");
return str;
}
private ArrayList<Class<? extends Throwable>> processHandlers(HashMap<Class<? extends Throwable>, Method> exceptionHandlers) {
ArrayList<Class<? extends Throwable>> allHandlers = new ArrayList<Class<? extends Throwable>>();
ArrayList<Class<? extends Throwable>> toBeDone = new ArrayList<Class<? extends Throwable>>();
toBeDone.addAll(exceptionHandlers.keySet());
while (toBeDone.size() > 0) {
Class<? extends Throwable> throwable = toBeDone.remove(0);
boolean found = false;
for (Class<? extends Throwable> test : toBeDone) {
if (throwable.isAssignableFrom(test)) {
found = true;
break;
}
}
if (found) {
toBeDone.add(throwable);
} else {
allHandlers.add(throwable);
}
}
return allHandlers;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.cache.CacheStore;
import uk.co.taylorconsulting.annoweb.annotation.form.Clean;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Param;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Required;
import uk.co.taylorconsulting.annoweb.annotation.injection.DefaultCacheValue;
import uk.co.taylorconsulting.annoweb.annotation.injection.DefaultValue;
import uk.co.taylorconsulting.annoweb.annotation.injection.Inject;
import uk.co.taylorconsulting.annoweb.web.builder.data.FormData;
import uk.co.taylorconsulting.annoweb.web.builder.data.Globals;
public class FormBuilder extends SiteBuilder {
private static final Logger LOG = Logger.getLogger(SiteBuilder.class);
private static final FormBuilder instance = new FormBuilder();
public static String createHelper(Class<?> c) {
return instance.createFormHelper(c);
}
private String createFormHelper(Class<?> c) {
String clazzName = "Form" + convertName(c.getName());
return clazzName;
}
public static void buildFormHelper(FormData fd, File tmpLocation, Globals globals) {
instance.buildFormHelper(fd, tmpLocation, globals, true);
}
public void buildFormHelper(FormData fd, File tmpLocation, Globals globals, boolean ok) {
Class<?> c = fd.getClazz();
String clazzName = createFormHelper(c);
File output = new File(tmpLocation, clazzName + ".java");
if (!output.exists()) {
StringBuffer str = new StringBuffer("import javax.servlet.http.*;\n");
str.append("import javax.servlet.*;\n");
str.append("import java.util.*;\n");
str.append("public class ").append(clazzName).append(" extends uk.co.taylorconsulting.web.controller.WebHelper {\n");
str.append("\tprivate static final ").append(clazzName).append(" instance = new ").append(clazzName).append("();\n");
str.append("\tprivate ").append(clazzName).append("(){}\n");
str.append("\tpublic static ").append(c.getCanonicalName()).append(" getForm(HttpServletRequest request, String name, boolean clean, String id) throws uk.co.taylorconsulting.web.builder.ParameterRequiredException{\n");
str.append("\t\tif (name==null || name.trim().equals(\"\")) {\n");
str.append("\t\t\tname=\"\";\n");
str.append("\t\t} else {\n");
str.append("\t\t\tname= name+\".\";\n");
str.append("\t\t}\n");
str.append("\t\treturn instance.getForm(request, name, clean, id, true);\n");
str.append("\t}\n");
str.append("\tpublic ").append(c.getCanonicalName()).append(" getForm(HttpServletRequest request, String name, boolean clean, String id, boolean ok) throws uk.co.taylorconsulting.web.builder.ParameterRequiredException{\n");
Method cleanMethod = null;
for (Method m : c.getMethods()) {
if (m.getAnnotation(Clean.class) != null) {
if (cleanMethod == null) {
cleanMethod = m;
}
}
}
str.append("\t\t").append(c.getCanonicalName()).append(" form = null;\n");
boolean first = true;
ArrayList<String> names = new ArrayList<String>();
for (String key : fd.getInjects().keySet()) {
Inject i = fd.getInjects().get(key);
// if (i.id() != null) {
// key = i.id();
// }
if (!names.contains(key)) {
names.add(key);
if (first) {
str.append("\t\tif (");
first = false;
} else {
str.append("\t\t} else if (");
}
str.append("\"").append(key).append("\".equals(id)) {\n");
switch (i.cache().store()) {
case REQUEST: {
str.append("\t\t\tform = (").append(c.getCanonicalName()).append(")request.getAttribute(id);\n");
str.append("\t\t\tif (form == null) {\n");
str.append("\t\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t\t\trequest.setAttribute(id,form);\n");
str.append("\t\t\t}\n");
break;
}
case SESSION: {
str.append("\t\t\tform = (").append(c.getCanonicalName()).append(")request.getSession().getAttribute(id);\n");
str.append("\t\t\tif (form == null) {\n");
str.append("\t\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t\t\trequest.getSession().setAttribute(id,form);\n");
str.append("\t\t\t}\n");
break;
}
case APPLICATION: {
str.append("\t\t\tform = (").append(c.getCanonicalName()).append(")uk.co.taylorconsulting.web.controller.CacheManager.getItemFromCache(request, uk.co.taylorconsulting.annotation.cache.CacheStore.").append(
i.cache().store().toString()).append(",\"").append(i.cache().cacheId()).append("\",\"").append(i.cache().id()).append("\");\n");
str.append("\t\t\tif (form == null) {\n");
str.append("\t\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t\t\tuk.co.taylorconsulting.web.controller.CacheManager.addToCache(request, uk.co.taylorconsulting.annotation.cache.CacheStore.").append(i.cache().store().toString()).append(",\"").append(
i.cache().cacheId()).append("\",\"").append(i.cache().id()).append("\",form);\n");
str.append("\t\t\t}\n");
break;
}
case NONE: {
str.append("\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
break;
}
}
}
}
for (String key : fd.getDefaultCacheValues().keySet()) {
DefaultCacheValue dcv = fd.getDefaultCacheValues().get(key);
if (dcv.id() != null) {
key = dcv.id();
}
if (!names.contains(key)) {
names.add(key);
if (first) {
str.append("\t\tif (");
first = false;
} else {
str.append("\t\t} else if (");
}
str.append("\"").append(key).append("\".equals(id)) {\n");
switch (dcv.cache().store()) {
case REQUEST: {
str.append("\t\t\tform = (").append(c.getCanonicalName()).append(")request.getAttribute(id);\n");
str.append("\t\t\tif (form == null) {\n");
str.append("\t\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t\t\trequest.setAttribute(id,form);\n");
str.append("\t\t\t}\n");
break;
}
case SESSION: {
str.append("\t\t\tform = (").append(c.getCanonicalName()).append(")request.getSession().getAttribute(id);\n");
str.append("\t\t\tif (form == null) {\n");
str.append("\t\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t\t\trequest.getSession().setAttribute(id,form);\n");
str.append("\t\t\t}\n");
break;
}
case APPLICATION: {
str.append("\t\t\tform = (").append(c.getCanonicalName()).append(")uk.co.taylorconsulting.web.controller.CacheManager.getItemFromCache(request, uk.co.taylorconsulting.annotation.cache.CacheStore.").append(
dcv.cache().store().toString()).append(",\"").append(dcv.cache().cacheId()).append("\",\"").append(dcv.cache().id()).append("\");\n");
str.append("\t\t\tif (form == null) {\n");
str.append("\t\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t\t\tuk.co.taylorconsulting.web.controller.CacheManager.addToCache(request, uk.co.taylorconsulting.annotation.cache.CacheStore.").append(dcv.cache().store().toString()).append(",\"").append(
dcv.cache().cacheId()).append("\",\"").append(dcv.cache().id()).append("\",form);\n");
str.append("\t\t\t}\n");
break;
}
case NONE: {
str.append("\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
break;
}
}
}
}
if (!first) {
str.append("\t\t} else {\n");
str.append("\t\t\tform = new ").append(c.getCanonicalName()).append("();\n");
str.append("\t\t}\n");
} else {
str.append("\t\tform = new ").append(c.getCanonicalName()).append("();\n");
}
for (Method m : c.getMethods()) {
first = true;
names.clear();
if (m.getName().toLowerCase().startsWith("set") && m.getParameterTypes().length == 1) {
// setter method
Class<?> clazz = m.getParameterTypes()[0];
MethodTypeEnum method = MethodTypeEnum.getByClass(clazz);
if (method != null) {
str.append("\t\t").append(clazz.getCanonicalName()).append(" tmp").append(m.getName()).append("=").append(buildMethodSigniture(m, m.getAnnotation(Required.class), true, globals)).append(";\n");
str.append("\t\tif (").append(" tmp").append(m.getName()).append("==").append(method.getDefaultValue()).append(") {\n");
String var = m.getName().toLowerCase().charAt(3) + m.getName().substring(4);
for (String key : fd.getInjects().keySet()) {
Inject i = fd.getInjects().get(key);
// if (i.id() != null) {
// key = i.id();
// }
if (!names.contains(key)) {
names.add(key);
for (Param p : i.defaultParameters()) {
if (p.name().equals(var)) {
if (first) {
str.append("\t\t\tif (");
first = false;
} else {
str.append("\t\t\t} else if (");
}
str.append("\"").append(key).append("\".equals(id)) {\n");
str.append("\t\t\t\ttmp").append(m.getName()).append("=").append(method.getMethod()).append("(\"").append(p.value()).append("\");\n");
break;
}
}
}
}
DefaultValue dv = m.getAnnotation(DefaultValue.class);
DefaultCacheValue dcv = m.getAnnotation(DefaultCacheValue.class);
if (dcv != null && dcv.cache().store() != CacheStore.NONE) {
if (!first) {
str.append("\t\t\t} else {\n");
}
switch (dcv.cache().store()) {
case REQUEST: {
str.append("\t\t\t\ttmp").append(m.getName()).append(" = (").append(clazz.getCanonicalName()).append(")request.getAttribute(\"").append(dcv.id()).append("\");\n");
break;
}
case SESSION: {
str.append("\t\\tt\ttmp").append(m.getName()).append(" = (").append(clazz.getCanonicalName()).append(")request.getSession().getAttribute(\"").append(dcv.id()).append("\");\n");
break;
}
case APPLICATION: {
if (clazz.isPrimitive()) {
String prim = clazz.getCanonicalName();
prim = prim.toUpperCase().charAt(0) + prim.substring(1);
str.append("\t\t\t\ttmp").append(m.getName()).append(" = (").append(c.getCanonicalName()).append(")uk.co.taylorconsulting.web.controller.CacheManager.get").append(prim).append(
"FromCache(request, uk.co.taylorconsulting.annotation.cache.CacheStore.").append(dcv.cache().store().toString()).append(",\"").append(dcv.cache().cacheId()).append("\",\"").append(
dcv.cache().id()).append("\");\n");
} else {
str.append("\t\t\t\ttmp").append(m.getName()).append(" = (").append(c.getCanonicalName()).append(
")uk.co.taylorconsulting.web.controller.CacheManager.getItemFromCache(request, uk.co.taylorconsulting.annotation.cache.CacheStore.").append(dcv.cache().store().toString()).append(",\"")
.append(dcv.cache().cacheId()).append("\",\"").append(dcv.cache().id()).append("\");\n");
}
break;
}
}
}
if (dv != null) {
if (dcv != null) {
str.append("\t\t\t\tif (").append(" tmp").append(m.getName()).append("==").append(method.getDefaultValue()).append(") {\n");
str.append("\t\t\t\t}\n");
} else {
if (!first) {
str.append("\t\t\t} else {\n");
}
}
str.append("\t\t\t\t\ttmp").append(m.getName()).append(" = (").append(clazz.getCanonicalName()).append(")").append(method.getMethod()).append("(\"").append(dv.value()).append("\");\n");
if (dcv != null) {
str.append("\t\t\t\t}\n");
}
}
if (!first || dv != null || (dcv != null && dcv.cache().store() != CacheStore.NONE)) {
str.append("\t\t\t}\n");
}
str.append("\t\t}\n");
str.append("\t\tform.").append(m.getName()).append("(tmp").append(m.getName()).append(");\n");
}
}
}
str.append("\t\treturn form;\n");
str.append("\t}\n");
str.append("}\n");
FileOutputStream fos;
try {
fos = new FileOutputStream(output);
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
LOG.warn("Error writing class to " + output.getAbsolutePath() + "(" + e.getMessage() + ")");
}
}
}
private String convertName(String name) {
return name.replace('.', '_');
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
public class ParameterRequiredException extends Throwable {
/**
*
*/
private static final long serialVersionUID = 309426935472852723L;
private String key;
private String bundle;
public ParameterRequiredException(String message, String key, String bundle) {
super(message);
this.key = key;
this.bundle = bundle;
}
public String getKey() {
return key;
}
public String getBundle() {
return bundle;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.action.Parameter;
import uk.co.taylorconsulting.annoweb.annotation.form.Clean;
import uk.co.taylorconsulting.annoweb.annotation.form.Form;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Required;
import uk.co.taylorconsulting.annoweb.annotation.injection.DefaultCacheValue;
import uk.co.taylorconsulting.annoweb.annotation.injection.DefaultValue;
import uk.co.taylorconsulting.annoweb.annotation.injection.Inject;
import uk.co.taylorconsulting.annoweb.annotation.injection.Injectable;
import uk.co.taylorconsulting.annoweb.annotation.injection.MultipleInjection;
import uk.co.taylorconsulting.annoweb.annotation.security.Role;
import uk.co.taylorconsulting.annoweb.annotation.web.DefaultForward;
import uk.co.taylorconsulting.annoweb.annotation.web.Forward;
import uk.co.taylorconsulting.annoweb.annotation.web.GlobalForward;
import uk.co.taylorconsulting.annoweb.web.builder.data.ActionHolder;
import uk.co.taylorconsulting.annoweb.web.builder.data.FormData;
import uk.co.taylorconsulting.annoweb.web.builder.data.Globals;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
import uk.co.taylorconsulting.annoweb.web.builder.data.SiteHolder;
import uk.co.taylorconsulting.annoweb.web.resources.Messages;
public class SiteBuilder {
private static final Logger LOG = Logger.getLogger(SiteBuilder.class);
private static final SiteBuilder instance = new SiteBuilder();
public static void buildSite(Site s, File tmpLocation, HashMap<String, SiteHolder> methods) {
instance.buildSite(s, tmpLocation, methods, true);
}
public void buildSite(Site s, File tmpLocation, HashMap<String, SiteHolder> methods, boolean ok) {
File siteFile = new File(tmpLocation, "Site" + removeSpace(s.getName()) + ".java");
StringBuffer str = addClassStart(s);
addMethods(s, str, methods);
str.append("}\n");
FileOutputStream fos;
try {
fos = new FileOutputStream(siteFile);
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
LOG.warn("Error writing class to " + siteFile.getAbsolutePath() + "(" + e.getMessage() + ")");
}
}
private void addMethods(Site s, StringBuffer str, HashMap<String, SiteHolder> methods) {
ArrayList<String> compMethods = new ArrayList<String>();
for (ActionHolder ah : s.getActions().values()) {
if (!compMethods.contains(ah.getMethod().getClass().getCanonicalName() + ":" + ah.getMethod().getName())) {
compMethods.add(ah.getMethod().getClass().getCanonicalName() + ":" + ah.getMethod().getName());
str.append("\tpublic void process").append(ah.getMethod().getName()).append("(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
str.append("\t\t").append(ah.getMethod().getDeclaringClass().getCanonicalName()).append(" actionClass= (").append(ah.getMethod().getDeclaringClass().getCanonicalName()).append(")getCache(\"").append(
ah.getMethod().getDeclaringClass().getCanonicalName()).append("\");\n");
str.append("\t\tif(actionClass != null) {\n");
str.append("\t\t\ttry {\n");
Method m = ah.getMethod();
Class<?> clazz = m.getDeclaringClass();
if ((s.getRoles().get(clazz) != null && s.getRoles().get(clazz).size() > 0) || ah.getRoles().size() > 0) {
str.append("\t\t\t\tif (SecurityHandler.checkSecurity(request, response, servletContext, ");
ArrayList<String> roles = new ArrayList<String>();
boolean first = true;
first = addRoles(str, roles, first, s.getRoles().get(clazz));
addRoles(str, roles, first, ah.getRoles());
str.append(")) {\n");
}
if (ah.getMethod().getReturnType() == String.class) {
str.append("\t\t\t\tString retValue = actionClass.");
} else {
str.append("\t\t\t\tactionClass.");
}
str.append(ah.getMethod().getName()).append("(").append(buildMethodSigniture(ah.getMethod(), ah.getMethod().getAnnotation(Required.class), false, s.getGlobals())).append(");\n");
if (ah.getMethod().getReturnType() == String.class) {
// test value to forward
boolean first = true;
for (Forward f : ah.getForwards()) {
if (first) {
first = false;
str.append("\t\t\t\t");
} else {
str.append("\t\t\t\t} else ");
}
str.append("if (\"").append(f.name()).append("\".equals(retValue)) {\n");
addForward(str, f.path(), f.web(), f.method(), f.redirect(), "\t\t\t\t\t", s, null);
}
ArrayList<Forward> sForwards = s.getForward(ah.getMethod().getDeclaringClass());
if (sForwards != null) {
for (Forward f : sForwards) {
if (first) {
first = false;
str.append("\t\t\t\t");
} else {
str.append("\t\t\t\t} else ");
}
str.append("if (\"").append(f.name()).append("\".equals(retValue)) {\n");
addForward(str, f.path(), f.web(), f.method(), f.redirect(), "\t\t\t\t\t", s, null);
}
}
if (first) {
str.append("\t\t\t\t");
first = false;
} else {
str.append("\t\t\t\t} else ");
}
str.append("if (!GlobalDataHandler.globalForward(retValue, request, response, servletContext)) {\n");
// do default forwards
addDefaultForward(s, str, ah, "\t\t\t\t\t");
str.append("\t\t\t\t}\n");
} else {
// send to default forward
addDefaultForward(s, str, ah, "\t\t\t\t");
}
if (s.getRoles().size() > 0 || ah.getRoles().size() > 0) {
str.append("\t\t\t\t}\n");
}
str.append("\t\t\t} catch (Throwable t) {\n");
str.append("\t\t\t\tGlobalDataHandler.handleException(t, request, response, servletContext);\n");
str.append("\t\t\t}\n");
str.append("\t\t}\n");
str.append("\t}\n");
}
}
}
private boolean addRoles(StringBuffer str, ArrayList<String> roles, boolean first, ArrayList<Role> rT) {
if (rT != null && rT.size() > 0) {
for (Role r : rT) {
if (!roles.contains(r.value())) {
roles.add(r.value());
if (first) {
first = false;
} else {
str.append(",");
}
str.append("\"").append(r.value()).append("\"");
}
}
}
return first;
}
protected void addDefaultForward(Site s, StringBuffer str, ActionHolder ah, String indent) {
String defF = ah.getDefaultForward() == null ? null : ah.getDefaultForward().value();
if (defF == null) {
if (ah.getMethod() != null) {
DefaultForward df = s.getDefaultForwards().get(ah.getMethod().getDeclaringClass());
if (df != null) {
defF = df.value();
}
}
}
Forward f = null;
if (defF == null) {
if (s.getGlobals().getDefaultForward() != null) {
defF = s.getGlobals().getDefaultForward().value();
}
} else {
f = ah.getForward(defF);
if (f == null) {
if (ah.getMethod() != null) {
for (Forward fTmp : s.getForward(ah.getMethod().getDeclaringClass())) {
if (fTmp.name().equals(defF)) {
f = fTmp;
break;
}
}
}
}
}
if (f != null) {
addForward(str, f.path(), f.web(), f.method(), f.redirect(), indent, s, null);
} else {
GlobalForward gf = s.getGlobals().getForward(defF);
if (gf != null) {
addForward(str, gf.path(), gf.web(), gf.method(), gf.redirect(), indent, s, null);
} else {
LOG.warn("Cannot find forward called \"" + defF + "\"");
}
}
}
protected void addForward(StringBuffer str, String path, Class<?> web, String method, boolean redirect, String indent, Site s, String retVal) {
if (redirect && path != null && (!path.equals(""))) {
str.append(indent).append("response.sendRedirect(\"").append(path).append("\");\n");
} else {
if (web != null && web != Forward.class && web != GlobalForward.class) {
Method forwardMethod = null;
for (Method m : web.getMethods()) {
if (m.getName().equals(method)) {
forwardMethod = m;
break;
}
}
if (forwardMethod != null) {
ActionHolder ah = s.getGlobals().getAction(forwardMethod);
if (ah != null) {
if (ah.getSite() == s) {
str.append(indent).append("process").append(ah.getMethod().getName()).append("(request, response, servletContext);\n");
} else {
str.append(indent).append("((Site").append(ah.getSite().getName()).append(")getCache(\"Site").append(ah.getSite().getName()).append("\")).process").append(ah.getMethod().getName()).append(
"(request, response, servletContext);\n");
}
}
}
} else {
str.append(indent).append("RequestDispatcher rd = servletContext.getRequestDispatcher(\"").append(path).append("\");\n");
str.append(indent).append("rd.forward(request,response);\n");
}
}
addReturn(str, indent, retVal);
}
private void addReturn(StringBuffer str, String indent, String retVal) {
if (retVal == null) {
str.append(indent).append("return;\n");
} else {
str.append(indent).append("return ").append(retVal).append(";\n");
}
}
protected String buildMethodSigniture(Method method, Required required, boolean addName, Globals globals) {
StringBuffer str = new StringBuffer();
int paramPos = -1;
boolean firstParam = true;
Annotation[][] allAnnotations = method.getParameterAnnotations();
String defaultName = null;
if (method.getName().toLowerCase().startsWith("set")) {
defaultName = method.getName().substring(3);
defaultName = defaultName.substring(0, 1).toLowerCase() + defaultName.substring(1);
}
for (Class<?> c : method.getParameterTypes()) {
paramPos++;
firstParam = addParam(method, str, firstParam, paramPos, allAnnotations, c, required, defaultName, addName, globals);
}
return str.toString();
}
private boolean addParam(Method m, StringBuffer str, boolean firstParam, int paramPos, Annotation[][] allAnnotations, Class<?> c, Required required, String defaultName, boolean addName, Globals globals) {
if (firstParam) {
firstParam = false;
} else {
str.append(",");
}
if (c == HttpServletRequest.class) {
str.append("request");
} else if (c == HttpServletResponse.class) {
str.append("response");
} else if (c == Messages.class) {
str.append("messages");
} else if (isException(c)) {
if (required == null) {
str.append("getException(\"exception\", request,false, null,null,").append(c.getCanonicalName()).append(".class)");
} else {
str.append("getException(\"exception\", request,false, ").append(required.key()).append("\",\"").append(required.bundle()).append("\",").append(c.getCanonicalName()).append(".class)");
}
} else {
String paramName = null;
boolean clean = false;
MethodTypeEnum method = MethodTypeEnum.getByClass(c);
DefaultCacheValue defCache = null;
DefaultValue defValue = null;
Inject inject = null;
for (Annotation annotation : allAnnotations[paramPos]) {
if (annotation instanceof Parameter) {
paramName = ((Parameter) annotation).value();
} else if (annotation instanceof Clean) {
clean = true;
} else if (annotation instanceof DefaultCacheValue) {
defCache = (DefaultCacheValue) annotation;
} else if (annotation instanceof DefaultValue) {
defValue = (DefaultValue) annotation;
} else if (annotation instanceof Inject) {
inject = (Inject) annotation;
}
}
if (paramName == null) {
paramName = defaultName;
}
if (method == null) {
if (c.getAnnotation(Form.class) != null || defCache != null || defValue != null || inject != null || c.getAnnotation(MultipleInjection.class) != null || c.getAnnotation(Injectable.class) != null) {
processForm(m, str, c, paramName, clean, defCache, defValue, inject, globals);
} else {
str.append("null");
}
} else {
if (paramName == null && defCache == null && defValue == null) {
str.append("null");
} else {
str.append(method.getMethod());
if (addName) {
str.append("(name+\"");
} else {
str.append("(\"");
}
str.append(paramName).append("\",request,");
if (required == null) {
str.append("false,null,null");
} else {
str.append("true,\"").append(required.key()).append("\",\"").append(required.bundle()).append("\"");
}
if (defCache != null) {
str.append("getCache").append(method.toString()).append("\"").append(defCache.cache().cacheId()).append("\", \"").append(defCache.cache().id()).append("\",\"").append(defCache.value()).append("\",").append(
c.getClass().getCanonicalName()).append(".class, request)");
} else if (defValue != null) {
str.append("getDefault").append(method.toString()).append("(\"").append(defValue.value()).append("\",").append(c.getClass().getCanonicalName()).append(".class, request)");
}
str.append(")");
}
}
}
return firstParam;
}
private boolean isException(Class<?> c) {
if (Throwable.class.isAssignableFrom(c)) {
return true;
}
return false;
}
private boolean processForm(Method m, StringBuffer str, Class<?> c, String name, boolean clean, DefaultCacheValue defCache, DefaultValue defValue, Inject inject, Globals globals) {
String helper = FormBuilder.createHelper(c);
FormData fd = globals.getForm(c.getCanonicalName());
if (fd == null) {
globals.addForm(c);
fd = globals.getForm(c.getCanonicalName());
}
if (defCache != null) {
fd.addDefaultCache(m.getDeclaringClass().getCanonicalName() + ":" + m.getName(), defCache);
}
if (defValue != null) {
fd.addDefaultValue(m.getDeclaringClass().getCanonicalName() + ":" + m.getName(), defValue);
}
if (inject != null) {
fd.addInjects(m.getDeclaringClass().getCanonicalName() + ":" + m.getName(), inject);
}
boolean done = false;
str.append(helper).append(".getForm(request,");
if (name == null) {
str.append("null, ");
} else {
str.append("\"").append(name).append("\", ").append(clean);
}
str.append(clean);
String id = null;
if (inject != null) {
id = m.getDeclaringClass().getCanonicalName() + ":" + m.getName();
} else if (defCache != null) {
id = defCache.id();
} else if (defValue != null) {
id = defValue.id();
}
if (id == null || id.equals("")) {
id = m.getDeclaringClass().getCanonicalName() + ":" + m.getName();
}
str.append(",\"").append(id).append("\")");
done = true;
return done;
}
private StringBuffer addClassStart(Site s) {
StringBuffer str = new StringBuffer("import javax.servlet.http.*;\n");
str.append("import javax.servlet.*;\n");
str.append("import java.util.*;\n");
str.append("import org.apache.log4j.Logger;\n");
str.append("public class ").append("Site" + removeSpace(s.getName())).append(" extends uk.co.taylorconsulting.web.controller.WebHelper implements uk.co.taylorconsulting.web.controller.WebFramework {\n");
ActionHolder defaultAction = null;
Method defaultMethod = s.getDefaultAction();
str.append("\tprivate static final Logger LOG = Logger.getLogger(Site").append(removeSpace(s.getName())).append(".class);\n");
str.append("\tprivate static final ").append("Site" + removeSpace(s.getName())).append(" instance = new ").append("Site" + removeSpace(s.getName())).append("();\n");
str.append("\tpublic ").append("Site" + removeSpace(s.getName())).append("(){}\n");
str.append("\tpublic static ").append("Site" + removeSpace(s.getName())).append(" getInstance() {\n");
str.append("\t\treturn instance;\n");
str.append("\t}\n");
if (s.getActions().size() == 0) {
str.append("\tpublic void process(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
str.append("\t\tLOG.warn(\"Cannot process request. Action not defined for path: \"+request.getServletPath());\n");
} else {
str.append("\tprivate enum Actions {\n");
str.append("\t\t");
boolean first = true;
for (ActionHolder ah : s.getActions().values()) {
if (first) {
first = false;
} else {
str.append(",");
}
str.append(ah.getAction().dispatch()).append("_").append(ah.getAction().value());
}
str.append(";\n");
str.append("\t}\n");
str.append("\tpublic void process(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
first = true;
ArrayList<String> dispatches = new ArrayList<String>();
first = true;
for (ActionHolder ah : s.getActions().values()) {
if (!dispatches.contains(ah.getAction().dispatch())) {
dispatches.add(ah.getAction().dispatch());
if (first) {
first = false;
str.append("\t\ttry {\n");
str.append("\t\tLOG.debug(\"dispatcher=\"+request.getParameter(\"").append(ah.getAction().dispatch()).append("\"));\n");
str.append("\t\tActions dispatcher = Actions.valueOf(\"").append(ah.getAction().dispatch()).append("_\"+request.getParameter(\"").append(ah.getAction().dispatch()).append("\"));\n");
} else {
str.append("\t\tif (dispatcher == null) {\n");
str.append("\t\tLOG.debug(\"dispatcher=\"+request.getParameter(\"").append(ah.getAction().dispatch()).append("\"));\n");
str.append("\t\t\tdispatcher = Actions.valueOf(\"").append(ah.getAction().dispatch()).append("_\"+request.getParameter(\"").append(ah.getAction().dispatch()).append("\");\n");
str.append("\t\t}\n");
}
}
}
if (s.getActions().size() == 1) {
ActionHolder ah = s.getActions().values().iterator().next();
if (ah == null) {
LOG.warn("no actions defined for site " + s.getName());
}
if (ah.getMethod() == defaultMethod) {
str.append("\t\t} catch (Throwable t){t.printStackTrace();}\n");
str.append("\t\tprocess").append(ah.getMethod().getName()).append("(request, response, servletContext);\n");
} else {
str.append("\t\tif (dispatcher == Action.").append(ah.getAction().dispatch()).append("_").append(ah.getAction().value()).append(") {\n");
str.append("\t\t\tprocess").append(ah.getMethod().getName()).append("(request, response, servletContext);\n");
str.append("\t\t}\n");
str.append("\t\t} catch (Throwable t){t.printStackTrace();}\n");
}
} else {
str.append("\t\tswitch(dispatcher) {\n");
for (ActionHolder ah : s.getActions().values()) {
if (ah.getMethod() == defaultMethod || ah.getAction().value().equals("xxdefaultxx")) {
if (defaultAction == null) {
defaultAction = ah;
}
} else {
addMethodCall(str, ah, false);
}
}
str.append("\t\t}\n");
str.append("\t\t} catch (Throwable t){t.printStackTrace();}\n");
if (defaultAction != null) {
addMethodCall(str, defaultAction, true);
} else {
str.append("\t\tLOG.warn(\"Cannot process request. Action not defined for path: \"+request.getServletPath());\n");
}
}
}
str.append("\t}\n");
return str;
}
private void addMethodCall(StringBuffer str, ActionHolder ah, boolean other) {
if (!other) {
str.append("\t\t\tcase ").append(ah.getAction().dispatch()).append("_").append(ah.getAction().value()).append(": {\n");
}
str.append("\t\t\t\tprocess").append(ah.getMethod().getName()).append("(request, response, servletContext);\n");
if (!other) {
str.append("\t\t\t\treturn;\n");
str.append("\t\t\t}\n");
}
}
private String removeSpace(String name) {
name = name.trim();
int i = name.indexOf(' ');
while (i > 0) {
name = name.substring(0, i).trim() + name.substring(i + 1).trim();
i = name.indexOf(' ');
}
return name;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.builder;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.annotation.web.LinkParameter;
import uk.co.taylorconsulting.annoweb.web.builder.data.ActionHolder;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
public class QuicklinkBuilder extends SiteBuilder {
private static final Logger LOG = Logger.getLogger(QuicklinkBuilder.class);
private static final QuicklinkBuilder instance = new QuicklinkBuilder();
public static void buildSite(HashMap<String, Site> sites, File tmpLocation) {
instance.buildSite(sites, tmpLocation, true);
}
public void buildSite(HashMap<String, Site> sites, File tmpLocation, boolean ok) {
File siteFile = new File(tmpLocation, "SystemQuickLink.java");
StringBuffer str = addClassStart(sites);
str.append("}\n");
FileOutputStream fos;
try {
fos = new FileOutputStream(siteFile);
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
LOG.warn("Error writing class to " + siteFile.getAbsolutePath() + "(" + e.getMessage() + ")");
}
}
private StringBuffer addClassStart(HashMap<String, Site> sites) {
Site defaultSite = sites.get("xxDefaultxx");
StringBuffer str = new StringBuffer("import javax.servlet.http.*;\n");
str.append("import javax.servlet.*;\n");
str.append("import java.util.*;\n");
str.append("import org.apache.log4j.Logger;\n");
str.append("public class SystemQuickLink extends uk.co.taylorconsulting.web.controller.WebHelper implements uk.co.taylorconsulting.web.controller.WebFramework {\n");
str.append("\tprivate static final Logger LOG = Logger.getLogger(SystemQuickLink.class);\n");
str.append("\tprivate static final ").append("SystemQuickLink instance = new ").append("SystemQuickLink").append("();\n");
str.append("\tpublic ").append("SystemQuickLink(){}\n");
str.append("\tpublic static SystemQuickLink getInstance() {\n");
str.append("\t\treturn instance;\n");
str.append("\t}\n");
str.append("\tprivate enum Actions {\n");
str.append("\t\t");
boolean first = true;
for (String key : defaultSite.getGlobals().getQuickLinks().keySet()) {
if (first) {
first = false;
} else {
str.append(",");
}
str.append(key);
}
str.append(";\n");
str.append("\t}\n");
str.append("\tpublic void process(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {\n");
first = true;
str.append("\t\tString hash = request.getParameter(\"hash\");\n");
str.append("\t\ttry {\n");
str.append("\t\t\tString[] tokens = hash.split(\":\");\n");
str.append("\t\t\tif (tokens.length < 2 || (!tokens[0].equalsIgnoreCase(\"ql\"))) {\n");
str.append("\t\t\t\tLOG.warn(\"invalid quicklink recieved: \"+hash);\n");
str.append("\t\t\t\treturn;\n");
str.append("\t\t\t}\n");
str.append("\t\t\tActions dispatcher = Actions.valueOf(tokens[1]);\n");
str.append("\t\t\tswitch (dispatcher) {\n");
for (String key : defaultSite.getGlobals().getQuickLinks().keySet()) {
ActionHolder ah = defaultSite.getGlobals().getQuickLinks().get(key);
str.append("\t\t\t\tcase ").append(key).append(": {\n");
int i = 2;
for (LinkParameter lp : ah.getQuickLinks().parameters()) {
str.append("\t\t\t\t\trequest.setAttribute(\"").append(lp.name()).append("\",tokens[").append(i++).append("]);\n");
str.append("\t\t\t\t\t");
switch (lp.store()) {
case SESSION: {
str.append("request.getSession().setAttribute(\"");
break;
}
case REQUEST: {
str.append("request.setAttribute(\"");
}
}
str.append(lp.name()).append("\",");
MethodTypeEnum method = MethodTypeEnum.getByClass(lp.type());
str.append(method.getMethod());
str.append("(\"").append(lp.name()).append("\", request, false, null, null));\n");
}
addForward(str, null, ah.getMethod().getDeclaringClass(), ah.getMethod().getName(), false, "\t\t\t\t\t", defaultSite, null);
str.append("\t\t\t\t}\n");
}
str.append("\t\t\t}\n");
str.append("\t\t} catch (Throwable t) {LOG.warn(\"Error finding quicklink:\"+hash);}\n");
str.append("\t}\n");
return str;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.controller;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.web.builder.WebBuilder;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;
public class WebController extends HttpServlet {
private WebFramework framework;
private ServletConfig config;
private static final long serialVersionUID = 9068648708242215669L;
private static Logger LOG = Logger.getLogger(WebController.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
while (framework == null) {
try {
synchronized (this) {
wait(100);
}
} catch (Exception e) {}
}
String path = request.getServletPath().toUpperCase();
if (LOG.isDebugEnabled()) {
LOG.debug("Processing path:" + path);
}
framework.process(request, response, request.getSession().getServletContext());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
while (framework == null) {
try {
synchronized (this) {
wait(100);
}
} catch (Exception e) {}
}
setParametersToAttributes(request);
framework.process(request, response, request.getSession().getServletContext());
}
@SuppressWarnings("unchecked")
private void setParametersToAttributes(HttpServletRequest request) {
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> files = null;
try {
files = servletFileUpload.parseRequest(request);
for (FileItem fi : files) {
if (fi.isFormField()) {
request.setAttribute(fi.getFieldName(), fi.getString());
} else {
request.setAttribute(fi.getFieldName(), fi);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void init() throws ServletException {}
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
Thread t = new Thread(new Runnable() {
public void run() {
process();
}
});
t.start();
}
private void process() {
HashMap<String, Site> sites = new HashMap<String, Site>();
String ext = processConfig(sites);
String classpath = config.getServletContext().getRealPath("/");
build(classpath, ext, sites);
output(sites);
}
private void output(HashMap<String, Site> sites) {
for (Site s : sites.values()) {
s.debug();
}
}
private String processConfig(HashMap<String, Site> sites) {
String ext = "do";
for (Enumeration<?> namesEnum = config.getInitParameterNames(); namesEnum.hasMoreElements();) {
String name = (String) namesEnum.nextElement();
if (name.equalsIgnoreCase("extension")) {
ext = config.getInitParameter(name);
} else {
// Must be a context name
sites.put(name, new Site(name, config.getInitParameter(name)));
}
}
for (Site s : sites.values()) {
s.setExt(ext);
}
return ext;
}
private void build(String classpath, String ext, HashMap<String, Site> sites) {
long time = System.currentTimeMillis();
WebBuilder wb = new WebBuilder();
wb.process(classpath, ext, sites);
framework = wb.build(sites, classpath);
wb = null;
LOG.info("Site build took " + (System.currentTimeMillis() - time) + " millis seconds.");
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.controller;
import java.math.BigDecimal;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import uk.co.taylorconsulting.annoweb.web.builder.ParameterRequiredException;
public abstract class WebHelper extends CacheHelper {
private static HashMap<String, Object> cache = new HashMap<String, Object>();
private static final Logger LOG = Logger.getLogger(WebHelper.class);
protected String getDispatch(HttpServletRequest request, String dispatch) {
String retValue = request.getParameter(dispatch);
if (retValue == null) {
try {
retValue = (String) request.getAttribute(dispatch);
} catch (Exception e) {}
}
return retValue;
}
protected Throwable getException(String value) {
return null;
}
protected Throwable getException(String name, HttpServletRequest request, boolean required, String key, String bundle, Class<? extends Throwable> base, Exception defaultValue) throws ParameterRequiredException {
try {
Throwable t = getException(name, request, required, key, bundle, base);
if (t == null)
t = defaultValue;
return t;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Throwable getException(String name, HttpServletRequest request, boolean required, String key, String bundle, Class<? extends Throwable> base) throws ParameterRequiredException {
Object o = null;
o = getObject(name, request, required, key, bundle);
if (o != null) {
if (!(o instanceof Throwable)) {
o = null;
}
}
if (o != null) {
if (!base.isAssignableFrom(o.getClass())) {
o = null;
}
}
return (Throwable) o;
}
protected String getString(String value) {
return value;
}
protected String getString(String name, HttpServletRequest request, boolean required, String key, String bundle, String defaultValue) throws ParameterRequiredException {
try {
String s = getString(name, request, required, key, bundle);
if (s == null)
s = defaultValue;
return s;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected String getString(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
return (String) getObject(name, request, required, key, bundle);
} catch (Exception e) {}
return null;
}
protected byte getPByte(String value) {
try {
return Byte.parseByte(value);
} catch (Exception e) {}
return -1;
}
protected byte getPByte(String name, HttpServletRequest request, boolean required, String key, String bundle, byte defaultValue) throws ParameterRequiredException {
try {
byte b = getPByte(name, request, required, key, bundle);
return b;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected byte getPByte(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Byte.parseByte((String) o);
} else if (o instanceof Byte) {
return ((Byte) o);
}
} catch (Exception e) {}
return -1;
}
protected Byte getByte(String value) {
try {
return Byte.parseByte(value);
} catch (Exception e) {}
return null;
}
protected Byte getByte(String name, HttpServletRequest request, boolean required, String key, String bundle, Byte defaultValue) throws ParameterRequiredException {
try {
Byte b = getByte(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Byte getByte(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Byte) {
return (Byte) o;
} else if (o instanceof String) {
try {
return Byte.parseByte((String) getObject(name, request, required, key, bundle));
} catch (Exception e2) {}
}
} catch (Exception e) {}
return null;
}
protected short getPShort(String value) {
try {
return Short.parseShort(value);
} catch (Exception e) {}
return -1;
}
protected short getPShort(String name, HttpServletRequest request, boolean required, String key, String bundle, short defaultValue) throws ParameterRequiredException {
try {
short s = getByte(name, request, required, key, bundle);
return s;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected short getPShort(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Short.parseShort((String) o);
} else if (o instanceof Short) {
return ((Short) o);
}
} catch (Exception e) {}
return -1;
}
protected Short getShort(String value) {
try {
return Short.parseShort(value);
} catch (Exception e) {}
return null;
}
protected Short getShort(String name, HttpServletRequest request, boolean required, String key, String bundle, Short defaultValue) throws ParameterRequiredException {
try {
Short s = getShort(name, request, required, key, bundle);
if (s == null)
s = defaultValue;
return s;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Short getShort(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Short) {
return (Short) o;
} else if (o instanceof String) {
try {
return Short.parseShort((String) getObject(name, request, required, key, bundle));
} catch (Exception e2) {}
}
} catch (Exception e) {}
return null;
}
protected int getInt(String value) {
try {
return Integer.parseInt(value);
} catch (Exception e) {}
return -1;
}
protected int getInt(String name, HttpServletRequest request, boolean required, String key, String bundle, int defaultValue) throws ParameterRequiredException {
try {
int i = getInt(name, request, required, key, bundle);
return i;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected int getInt(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Integer.parseInt((String) o);
} else if (o instanceof Integer) {
return ((Integer) o);
}
} catch (Exception e) {}
return -1;
}
protected Integer getInteger(String value) {
try {
return Integer.parseInt(value);
} catch (Exception e) {}
return null;
}
protected Integer getInteger(String name, HttpServletRequest request, boolean required, String key, String bundle, Integer defaultValue) throws ParameterRequiredException {
try {
Integer i = getInteger(name, request, required, key, bundle);
if (i == null)
i = defaultValue;
return i;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Integer getInteger(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Integer) {
return (Integer) o;
} else if (o instanceof String) {
return Integer.parseInt((String) o);
}
} catch (Exception e) {}
return null;
}
protected BigDecimal getBigDecimal(String value) {
try {
return BigDecimal.valueOf(Long.parseLong(value));
} catch (Exception e) {}
return null;
}
protected BigDecimal getBigDecimal(String name, HttpServletRequest request, boolean required, String key, String bundle, BigDecimal defaultValue) throws ParameterRequiredException {
try {
BigDecimal b = getBigDecimal(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected BigDecimal getBigDecimal(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof BigDecimal) {
return (BigDecimal) o;
} else if (o instanceof String) {
return BigDecimal.valueOf(Double.parseDouble((String) o));
}
} catch (Exception e) {}
return null;
}
protected long getPLong(String value) {
try {
return Long.parseLong(value);
} catch (Exception e) {}
return -1;
}
protected long getPLong(String name, HttpServletRequest request, boolean required, String key, String bundle, long defaultValue) throws ParameterRequiredException {
try {
long b = getPLong(name, request, required, key, bundle);
return b;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected long getPLong(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Long.parseLong((String) o);
} else if (o instanceof Long) {
return ((Long) o);
}
} catch (Exception e) {}
return -1;
}
protected Long getLong(String value) {
try {
return Long.parseLong(value);
} catch (Exception e) {}
return null;
}
protected Long getLong(String name, HttpServletRequest request, boolean required, String key, String bundle, Long defaultValue) throws ParameterRequiredException {
try {
Long l = getLong(name, request, required, key, bundle);
if (l == null)
l = defaultValue;
return l;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Long getLong(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Long) {
return (Long) o;
} else if (o instanceof String) {
return Long.parseLong((String) o);
}
} catch (Exception e) {}
return null;
}
protected float getPFloat(String value) {
try {
return Float.parseFloat(value);
} catch (Exception e) {}
return -1.0f;
}
protected float getPFloat(String name, HttpServletRequest request, boolean required, String key, String bundle, float defaultValue) throws ParameterRequiredException {
try {
float f = getPFloat(name, request, required, key, bundle);
return f;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected float getPFloat(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Float.parseFloat((String) o);
} else if (o instanceof Float) {
return ((Float) o);
}
} catch (Exception e) {}
return -1;
}
protected Float getFloat(String value) {
try {
return Float.parseFloat(value);
} catch (Exception e) {}
return null;
}
protected Float getFloat(String name, HttpServletRequest request, boolean required, String key, String bundle, Float defaultValue) throws ParameterRequiredException {
try {
Float f = getFloat(name, request, required, key, bundle);
if (f == null)
f = defaultValue;
return f;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Float getFloat(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Float) {
return (Float) o;
} else if (o instanceof Float) {
return Float.parseFloat((String) o);
}
} catch (Exception e) {}
return null;
}
protected double getPDouble(String value) {
try {
return Double.parseDouble(value);
} catch (Exception e) {}
return -1.0;
}
protected double getPDouble(String name, HttpServletRequest request, boolean required, String key, String bundle, double defaultValue) throws ParameterRequiredException {
try {
Double d = getDouble(name, request, required, key, bundle);
if (d == null)
d = defaultValue;
return d;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected double getPDouble(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Double.parseDouble((String) o);
} else if (o instanceof Double) {
return ((Double) o);
}
} catch (Exception e) {}
return -1;
}
protected Double getDouble(String value) {
try {
return Double.parseDouble(value);
} catch (Exception e) {}
return null;
}
protected Double getDouble(String name, HttpServletRequest request, boolean required, String key, String bundle, Double defaultValue) throws ParameterRequiredException {
try {
Double d = getDouble(name, request, required, key, bundle);
if (d == null)
d = defaultValue;
return d;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Double getDouble(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Double) {
return (Double) o;
} else if (o instanceof String) {
return Double.parseDouble((String) o);
}
} catch (Exception e) {}
return null;
}
protected boolean getPBoolean(String value) {
try {
return Boolean.parseBoolean(value);
} catch (Exception e) {}
return false;
}
protected boolean getPBoolean(String name, HttpServletRequest request, boolean required, String key, String bundle, boolean defaultValue) throws ParameterRequiredException {
try {
boolean b = getBoolean(name, request, required, key, bundle);
return b;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected boolean getPBoolean(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return Boolean.parseBoolean((String) o);
} else if (o instanceof Boolean) {
return ((Boolean) o);
}
} catch (Exception e) {}
return Boolean.FALSE;
}
protected Boolean getBoolean(String value) {
try {
return Boolean.parseBoolean(value);
} catch (Exception e) {}
return null;
}
protected Boolean getBoolean(String name, HttpServletRequest request, boolean required, String key, String bundle, Boolean defaultValue) throws ParameterRequiredException {
try {
Boolean b = getBoolean(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Boolean getBoolean(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Boolean) {
return (Boolean) o;
} else if (o instanceof String) {
return Boolean.parseBoolean((String) o);
}
} catch (Exception e) {}
return null;
}
protected char getPChar(String value) {
try {
return value.charAt(0);
} catch (Exception e) {}
return Character.MIN_VALUE;
}
protected char getPChar(String name, HttpServletRequest request, boolean required, String key, String bundle, char defaultValue) throws ParameterRequiredException {
try {
char c = getPChar(name, request, required, key, bundle);
return c;
} catch (ParameterRequiredException pre) {
return defaultValue;
}
}
protected char getPChar(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object o = getObject(name, request, required, key, bundle);
if (o instanceof String) {
return ((String) o).charAt(0);
} else if (o instanceof Character) {
return ((Character) o);
}
} catch (Exception e) {}
return ' ';
}
protected Character getCharacter(String value) {
try {
return value.charAt(0);
} catch (Exception e) {}
return null;
}
protected Character getCharacter(String name, HttpServletRequest request, boolean required, String key, String bundle, Character defaultValue) throws ParameterRequiredException {
try {
Character c = getCharacter(name, request, required, key, bundle);
if (c == null)
c = defaultValue;
return c;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Character getCharacter(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object o = getObject(name, request, required, key, bundle);
try {
if (o instanceof Character) {
return (Character) o;
} else if (o instanceof String) {
return Character.valueOf(((String) o).charAt(0));
}
} catch (Exception e) {}
return null;
}
protected Object getObject(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object s = request.getParameter(name);
if (s == null) {
s = request.getAttribute(name);
if (s == null) {
s = request.getSession().getAttribute(name);
}
}
if (s == null) {
if (required)
throw new ParameterRequiredException("missing parameter " + name, key, bundle);
}
return s;
}
protected String[] getStringA(String value) {
try {
return value.split(",");
} catch (Exception e) {}
return null;
}
protected String[] getStringA(String name, HttpServletRequest request, boolean required, String key, String bundle, String[] defaultValue) throws ParameterRequiredException {
try {
String[] s = getStringA(name, request, required, key, bundle);
if (s == null)
s = defaultValue;
return s;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected String[] getStringA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
return (String[]) o;
}
} catch (Exception e) {}
return new String[0];
}
protected byte[] getPByteA(String value) {
try {
String[] ops = value.split(",");
byte[] retValue = new byte[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPByte(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected byte[] getPByteA(String name, HttpServletRequest request, boolean required, String key, String bundle, byte[] defaultValue) throws ParameterRequiredException {
try {
byte[] b = getPByteA(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected byte[] getPByteA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
byte[] retValue = new byte[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Byte.parseByte(s);
}
return retValue;
} else if (o instanceof Byte[]) {
byte[] retValue = new byte[o.length];
int i = 0;
for (Byte b : (Byte[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new byte[0];
}
protected Byte[] getByteA(String value) {
try {
String[] ops = value.split(",");
Byte[] retValue = new Byte[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getByte(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Byte[] getByteA(String name, HttpServletRequest request, boolean required, String key, String bundle, Byte[] defaultValue) throws ParameterRequiredException {
try {
Byte[] b = getByteA(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Byte[] getByteA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Byte[] retValue = new Byte[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Byte.parseByte(s);
}
return retValue;
} else if (o instanceof Byte[]) {
return (Byte[]) o;
}
} catch (Exception e) {}
return new Byte[0];
}
protected short[] getPShortA(String value) {
try {
String[] ops = value.split(",");
short[] retValue = new short[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPShort(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected short[] getShortA(String name, HttpServletRequest request, boolean required, String key, String bundle, short[] defaultValue) throws ParameterRequiredException {
try {
short[] s = getPShortA(name, request, required, key, bundle);
if (s == null)
s = defaultValue;
return s;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected short[] getPShortA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
short[] retValue = new short[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Short.parseShort(s);
}
return retValue;
} else if (o instanceof Short[]) {
short[] retValue = new short[o.length];
int i = 0;
for (Short b : (Short[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new short[0];
}
protected Short[] getShortA(String value) {
try {
String[] ops = value.split(",");
Short[] retValue = new Short[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getShort(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Short[] getShortA(String name, HttpServletRequest request, boolean required, String key, String bundle, Short[] defaultValue) throws ParameterRequiredException {
try {
Short[] s = getShortA(name, request, required, key, bundle);
if (s == null)
s = defaultValue;
return s;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Short[] getShortA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Short[] retValue = new Short[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Short.parseShort(s);
}
return retValue;
} else if (o instanceof Byte[]) {
return (Short[]) o;
}
} catch (Exception e) {}
return new Short[0];
}
protected int[] getIntA(String value) {
try {
String[] ops = value.split(",");
int[] retValue = new int[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getInt(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected int[] getIntA(String name, HttpServletRequest request, boolean required, String key, String bundle, int[] defaultValue) throws ParameterRequiredException {
try {
int[] i = getIntA(name, request, required, key, bundle);
if (i == null)
i = defaultValue;
return i;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected int[] getIntA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
int[] retValue = new int[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Integer.parseInt(s);
}
return retValue;
} else if (o instanceof Integer[]) {
int[] retValue = new int[o.length];
int i = 0;
for (Integer b : (Integer[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new int[0];
}
protected Integer[] getIntegerA(String value) {
try {
String[] ops = value.split(",");
Integer[] retValue = new Integer[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getInteger(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Integer[] getIntegerA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Integer[] retValue = new Integer[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Integer.parseInt(s);
}
return retValue;
} else if (o instanceof Integer[]) {
return (Integer[]) o;
}
} catch (Exception e) {}
return new Integer[0];
}
protected FileItem getFileItem(String value) {
return null;
}
protected FileItem getFileItem(String name, HttpServletRequest request, boolean required, String key, String bundle, FileItem defaultValue) throws ParameterRequiredException {
try {
FileItem f = getFileItem(name, request, required, key, bundle);
if (f == null)
f = defaultValue;
return f;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected FileItem getFileItem(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
FileItem retValue = null;
try {
retValue = (FileItem) getObject(name, request, required, key, bundle);
} catch (Exception e) {}
return retValue;
}
protected FileItem[] getFileItemAA(String value) {
return null;
}
protected FileItem[] getFileItemA(String name, HttpServletRequest request, boolean required, String key, String bundle, FileItem[] defaultValue) throws ParameterRequiredException {
try {
FileItem[] f = getFileItemA(name, request, required, key, bundle);
if (f == null)
f = defaultValue;
return f;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected FileItem[] getFileItemA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
FileItem[] retValue = null;
try {
retValue = (FileItem[]) getObjectA(name, request, required, key, bundle);
} catch (Exception e) {
retValue = new FileItem[0];
}
return retValue;
}
protected BigDecimal[] getBigDecimalA(String value) {
try {
String[] ops = value.split(",");
BigDecimal[] retValue = new BigDecimal[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getBigDecimal(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected BigDecimal[] getBigDecimalA(String name, HttpServletRequest request, boolean required, String key, String bundle, BigDecimal[] defaultValue) throws ParameterRequiredException {
try {
BigDecimal[] b = getBigDecimalA(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected BigDecimal[] getBigDecimalA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
BigDecimal[] retValue = new BigDecimal[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = BigDecimal.valueOf(Double.parseDouble(s));
}
return retValue;
} else if (o instanceof BigDecimal[]) {
return (BigDecimal[]) o;
}
} catch (Exception e) {}
return new BigDecimal[0];
}
protected long[] getPLongA(String value) {
try {
String[] ops = value.split(",");
long[] retValue = new long[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPLong(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected long[] getPLongA(String name, HttpServletRequest request, boolean required, String key, String bundle, long[] defaultValue) throws ParameterRequiredException {
try {
long[] l = getPLongA(name, request, required, key, bundle);
if (l == null)
l = defaultValue;
return l;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected long[] getPLongA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
long[] retValue = new long[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Long.parseLong(s);
}
return retValue;
} else if (o instanceof Long[]) {
long[] retValue = new long[o.length];
int i = 0;
for (Long b : (Long[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new long[0];
}
protected Long[] getLongA(String value) {
try {
String[] ops = value.split(",");
Long[] retValue = new Long[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getLong(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Long[] getLongA(String name, HttpServletRequest request, boolean required, String key, String bundle, Long[] defaultValue) throws ParameterRequiredException {
try {
Long[] l = getLongA(name, request, required, key, bundle);
if (l == null)
l = defaultValue;
return l;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Long[] getLongA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Long[] retValue = new Long[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Long.parseLong(s);
}
return retValue;
} else if (o instanceof Long[]) {
return (Long[]) o;
}
} catch (Exception e) {}
return new Long[0];
}
protected float[] getPFloatA(String value) {
try {
String[] ops = value.split(",");
float[] retValue = new float[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPFloat(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected float[] getPLfloatA(String name, HttpServletRequest request, boolean required, String key, String bundle, float[] defaultValue) throws ParameterRequiredException {
try {
float[] f = getPFloatA(name, request, required, key, bundle);
if (f == null)
f = defaultValue;
return f;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected float[] getPFloatA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
float[] retValue = new float[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Float.parseFloat(s);
}
return retValue;
} else if (o instanceof Float[]) {
float[] retValue = new float[o.length];
int i = 0;
for (Float b : (Float[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new float[0];
}
protected Float[] getFloatA(String value) {
try {
String[] ops = value.split(",");
Float[] retValue = new Float[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getFloat(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Float[] getPfloatA(String name, HttpServletRequest request, boolean required, String key, String bundle, Float[] defaultValue) throws ParameterRequiredException {
try {
Float[] f = getFloatA(name, request, required, key, bundle);
if (f == null)
f = defaultValue;
return f;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Float[] getFloatA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Float[] retValue = new Float[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Float.parseFloat(s);
}
return retValue;
} else if (o instanceof Float[]) {
return (Float[]) o;
}
} catch (Exception e) {}
return new Float[0];
}
protected double[] getPDoubleA(String value) {
try {
String[] ops = value.split(",");
double[] retValue = new double[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPDouble(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected double[] getPDoubleA(String name, HttpServletRequest request, boolean required, String key, String bundle, double[] defaultValue) throws ParameterRequiredException {
try {
double[] d = getPDoubleA(name, request, required, key, bundle);
if (d == null)
d = defaultValue;
return d;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected double[] getPDoubleA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
double[] retValue = new double[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Double.parseDouble(s);
}
return retValue;
} else if (o instanceof Double[]) {
double[] retValue = new double[o.length];
int i = 0;
for (Double b : (Double[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new double[0];
}
protected Double[] getDoubleA(String value) {
try {
String[] ops = value.split(",");
Double[] retValue = new Double[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getDouble(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Double[] getDoubleA(String name, HttpServletRequest request, boolean required, String key, String bundle, Double[] defaultValue) throws ParameterRequiredException {
try {
Double[] d = getDoubleA(name, request, required, key, bundle);
if (d == null)
d = defaultValue;
return d;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Double[] getDoubleA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Double[] retValue = new Double[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Double.parseDouble(s);
}
return retValue;
} else if (o instanceof Double[]) {
return (Double[]) o;
}
} catch (Exception e) {}
return new Double[0];
}
protected boolean[] getPBooleanA(String value) {
try {
String[] ops = value.split(",");
boolean[] retValue = new boolean[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPBoolean(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected boolean[] getPBooleanA(String name, HttpServletRequest request, boolean required, String key, String bundle, boolean[] defaultValue) throws ParameterRequiredException {
try {
boolean[] b = getPBooleanA(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected boolean[] getPBooleanA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
boolean[] retValue = new boolean[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Boolean.parseBoolean(s);
}
return retValue;
} else if (o instanceof Boolean[]) {
boolean[] retValue = new boolean[o.length];
int i = 0;
for (Boolean b : (Boolean[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new boolean[0];
}
protected Boolean[] getBooleanA(String value) {
try {
String[] ops = value.split(",");
Boolean[] retValue = new Boolean[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getBoolean(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Boolean[] getBooleanA(String name, HttpServletRequest request, boolean required, String key, String bundle, Boolean[] defaultValue) throws ParameterRequiredException {
try {
Boolean[] b = getBooleanA(name, request, required, key, bundle);
if (b == null)
b = defaultValue;
return b;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Boolean[] getBooleanA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Boolean[] retValue = new Boolean[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = Boolean.parseBoolean(s);
}
return retValue;
} else if (o instanceof Boolean[]) {
return (Boolean[]) o;
}
} catch (Exception e) {}
return null;
}
protected char[] getPCharA(String value) {
try {
String[] ops = value.split(",");
char[] retValue = new char[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getPChar(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected char[] getPCharA(String name, HttpServletRequest request, boolean required, String key, String bundle, char[] defaultValue) throws ParameterRequiredException {
try {
char[] c = getPCharA(name, request, required, key, bundle);
if (c == null)
c = defaultValue;
return c;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected char[] getPCharA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
char[] retValue = new char[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = s.charAt(0);
}
return retValue;
} else if (o instanceof Character[]) {
char[] retValue = new char[o.length];
int i = 0;
for (Character b : (Character[]) o) {
retValue[i++] = b;
}
return retValue;
}
} catch (Exception e) {}
return new char[0];
}
protected Character[] getCharacterA(String value) {
try {
String[] ops = value.split(",");
Character[] retValue = new Character[ops.length];
for (int i = 0; i < ops.length; i++) {
retValue[i] = getCharacter(ops[i]);
}
return retValue;
} catch (Exception e) {}
return null;
}
protected Character[] getCharacterA(String name, HttpServletRequest request, boolean required, String key, String bundle, Character[] defaultValue) throws ParameterRequiredException {
try {
Character[] c = getCharacterA(name, request, required, key, bundle);
if (c == null)
c = defaultValue;
return c;
} catch (ParameterRequiredException pre) {
if (defaultValue == null)
throw pre;
return defaultValue;
}
}
protected Character[] getCharacterA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
try {
Object[] o = getObjectA(name, request, required, key, bundle);
if (o instanceof String[]) {
Character[] retValue = new Character[o.length];
int i = 0;
for (String s : (String[]) o) {
retValue[i++] = s.charAt(0);
}
return retValue;
} else if (o instanceof Character[]) {
return (Character[]) o;
}
} catch (Exception e) {}
return new Character[0];
}
protected Object[] getObjectA(String name, HttpServletRequest request, boolean required, String key, String bundle) throws ParameterRequiredException {
Object[] s = request.getParameterValues(name);
if (s == null || s.length < 1) {
s = (Object[]) request.getAttribute(name);
if (s == null) {
s = (Object[]) request.getSession().getAttribute(name);
}
}
if (s == null) {
if (required)
throw new ParameterRequiredException("missing parameter " + name, key, bundle);
}
return s;
}
public Object getCache(String key) {
Object o = cache.get(key);
if (o == null) {
try {
o = Class.forName(key).newInstance();
cache.put(key, o);
} catch (Exception e) {
LOG.warn("Error creating class from key " + key + ":" + e.getLocalizedMessage());
}
}
return o;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.controller;
import javax.servlet.http.HttpServletRequest;
import uk.co.taylorconsulting.annoweb.annotation.cache.CacheImplementation;
import uk.co.taylorconsulting.annoweb.annotation.cache.CacheStore;
public class CacheManager {
public static CacheImplementation cacheManager;
public static void setCacheManager(CacheImplementation cm) {
cacheManager = cm;
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, boolean value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, byte value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, char value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, double value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, float value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, int value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, long value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, Object Value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, Value);
}
}
public static void addToCache(HttpServletRequest request, CacheStore store, String cacheId, String itemId, short value) {
if (cacheManager != null) {
cacheManager.addToCache(request, store, cacheId, itemId, value);
}
}
public static boolean getBooleanFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getBooleanFromCache(request, store, cacheid, itemId);
}
return false;
}
public static byte getByteFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getByteFromCache(request, store, cacheid, itemId);
}
return -1;
}
public static char getCharFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getCharFromCache(request, store, cacheid, itemId);
}
return Character.MIN_VALUE;
}
public static double getDoubleFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getDoubleFromCache(request, store, cacheid, itemId);
}
return -1.0;
}
public static float getFloatFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getFloatFromCache(request, store, cacheid, itemId);
}
return -1.0f;
}
public static int getIntFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getIntFromCache(request, store, cacheid, itemId);
}
return -1;
}
public static Object getItemFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getItemFromCache(request, store, cacheid, itemId);
}
return null;
}
public static long getLongFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getLongFromCache(request, store, cacheid, itemId);
}
return -1;
}
public static short getShortFromCache(HttpServletRequest request, CacheStore store, String cacheid, String itemId) {
if (cacheManager != null) {
return cacheManager.getShortFromCache(request, store, cacheid, itemId);
}
return -1;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.controller;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface WebFramework {
public void process(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext);
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.controller;
public abstract class CacheHelper {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.resources;
import java.util.ArrayList;
import java.util.Hashtable;
public class Messages {
private Hashtable<MessageTypeEnum, ArrayList<Message>> messages = new Hashtable<MessageTypeEnum, ArrayList<Message>>();
public void addMessage(Message m) {
ArrayList<Message> msgs = messages.get(m.getType());
if (msgs == null) {
msgs = new ArrayList<Message>();
messages.put(m.getType(), msgs);
}
msgs.add(m);
}
public ArrayList<Message> getMessages() {
ArrayList<Message> retVal = new ArrayList<Message>();
for (MessageTypeEnum type : messages.keySet()) {
retVal.addAll(getMessages(type));
}
return retVal;
}
public ArrayList<Message> getMessages(MessageTypeEnum type) {
return messages.get(type);
}
public ArrayList<Message> getMessages(MessageTypeEnum type, String keyStart) {
return filter(getMessages(type), keyStart);
}
public ArrayList<Message> getMessages(String keyStart) {
return filter(getMessages(), keyStart);
}
private ArrayList<Message> filter(ArrayList<Message> msgs, String keyStart) {
ArrayList<Message> retVal = new ArrayList<Message>();
for (Message m : msgs) {
if (m.getKey().startsWith(keyStart)) {
retVal.add(m);
}
}
return retVal;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.resources;
public enum MessageTypeEnum {
Error, Message, Warning;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.resources;
public class NormalMessage extends Message {
public NormalMessage(String key) {
super(key, MessageTypeEnum.Error, (Object[]) null);
}
public NormalMessage(String key, String bundle) {
super(key, bundle, MessageTypeEnum.Error, (Object[]) null);
}
public NormalMessage(String key, Object[] params) {
super(key, MessageTypeEnum.Message, params);
}
public NormalMessage(String key, String bundle, Object[] params) {
super(key, bundle, MessageTypeEnum.Message, params);
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.resources;
public class ErrorMessage extends Message {
public ErrorMessage(String key) {
super(key, MessageTypeEnum.Error, (Object[]) null);
}
public ErrorMessage(String key, String bundle) {
super(key, bundle, MessageTypeEnum.Error, (Object[]) null);
}
public ErrorMessage(String key, Object[] params) {
super(key, MessageTypeEnum.Error, params);
}
public ErrorMessage(String key, String bundle, Object[] params) {
super(key, bundle, MessageTypeEnum.Error, params);
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.web.resources;
import java.util.ArrayList;
public abstract class Message {
private String key;
private String bundle;
private MessageTypeEnum type;
private ArrayList<Object> parameters = new ArrayList<Object>();
public Message(String key, MessageTypeEnum type, Object... params) {
this(key, null, type, params);
}
public Message(String key, String bundle, MessageTypeEnum type, Object... params) {
this.key = key;
this.bundle = bundle;
this.type = type;
if (params != null) {
for (Object o : params) {
this.parameters.add(o);
}
}
}
public String getKey() {
return key;
}
public String getBundle() {
return bundle;
}
public ArrayList<Object> getParameters() {
return parameters;
}
public MessageTypeEnum getType() {
return type;
}
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Inherited
public @interface DefaultForward {
String value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface GlobalDefaultForward {
String value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Inherited
public @interface Forward {
String name();
String path() default "";
Class<?> web() default Forward.class;
String method() default "";
boolean redirect() default false;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface QuickLink {
String link();
LinkParameter[] parameters();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
public @interface LinkParameter {
int position();
String name();
Class<?> type() default String.class;
ParamStore store() default ParamStore.REQUEST;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface GlobalForward {
String name();
String path() default "";
Class<?> web() default GlobalForward.class;
String method() default "";
boolean redirect() default false;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
public enum ParamStore {
REQUEST, SESSION;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface Web {
String view();
String dispatch() default "dispatch";
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Inherited
public @interface Forwards {
Forward[] value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface GlobalForwards {
GlobalForward[] value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.exception;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Inherited
public @interface CatchExceptions {
CatchException[] value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.exception;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface CatchException {
Class<? extends Throwable> value() default Throwable.class;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import uk.co.taylorconsulting.annoweb.annotation.cache.CacheValue;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Inherited
public @interface DefaultCacheValue {
String value();
String id() default "";
CacheValue cache();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
@Inherited
public @interface MultipleValues {
DefaultCacheValue[] defaultCacheValues() default {};
DefaultValue[] defaultValues() default {};
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import uk.co.taylorconsulting.annoweb.annotation.cache.CacheValue;
import uk.co.taylorconsulting.annoweb.annotation.form.validation.Param;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.PARAMETER })
@Inherited
public @interface Inject {
String id() default "";
CacheValue cache();
Param[] defaultParameters() default {};
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import uk.co.taylorconsulting.annoweb.annotation.cache.CacheStore;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface Injectable {
String id();
CacheStore cache() default CacheStore.NONE;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface MultipleInjection {
Injectable[] value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Inherited
public @interface DefaultValue {
String id() default "";
String value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.form;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.PARAMETER, ElementType.METHOD })
@Inherited
public @interface Clean {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.form;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface Form {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.form.validation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface Validator {
String value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.form.validation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.PARAMETER })
@Inherited
public @interface Validate {
String validator();
String[] params();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.form.validation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.PARAMETER, ElementType.METHOD })
@Inherited
public @interface Required {
String key();
String bundle() default "";
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.form.validation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.PARAMETER })
@Inherited
public @interface Param {
String name();
String value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.action;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface Init {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.action;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface Action {
String value() default "xxdefaultxx";
String dispatch() default "dispatch";
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.action;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.PARAMETER, ElementType.FIELD })
public @interface Parameter {
String value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.action;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface Default {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Inherited
public @interface Roles {
Role[] value();
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE, ElementType.METHOD })
@Inherited
public @interface Role {
String value();
String realm() default "all";
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import javax.servlet.http.HttpServletRequest;
public interface Security {
public boolean hasRoles(HttpServletRequest request, String... roles);
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface Login {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
public enum SecurityOptions {
login, notAuthorised, securityOk;
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface NotAuthorised {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
@Inherited
public @interface SecurityHandler {
String realm() default "all";
String context() default "";
}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
@Inherited
public @interface LoginHandler {}
| Java |
/**
* Copyright (c) 2008, George Taylor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the copyright holder's organization nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.co.taylorconsulting.annoweb.annotation.security;
import javax.servlet.http.HttpServletRequest;
public interface SecurityProcessor {
public SecurityOptions isRoleValid(String role, HttpServletRequest request);
}
| Java |
package org.frasermccrossan.toneitdown;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Notify.applyProfile(context);
}
}
| Java |
package org.frasermccrossan.toneitdown;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
class ProfileDatabaseHelper {
private ProfileOpenHelper openHelper;
private SQLiteDatabase db;
ProfileDatabaseHelper(Context c) {
openHelper = new ProfileOpenHelper(c);
db = openHelper.getWritableDatabase();
}
public void close() {
db.close();
}
Cursor allProfiles() {
return db.query(ProfileOpenHelper.PROFILE_TABLE_NAME,
new String[] { "_id", ProfileOpenHelper.NAME, ProfileOpenHelper.VOLUME, ProfileOpenHelper.VIBRATE },
null,
null, null, null, "_id");
}
boolean isCurrent(long profileId) {
return getCurrentProfileId() == profileId;
}
// get a profile by ID
Profile getProfileById(long profileId) {
Cursor c = db.query(ProfileOpenHelper.PROFILE_TABLE_NAME,
new String[] { ProfileOpenHelper.NAME, ProfileOpenHelper.VOLUME, ProfileOpenHelper.VIBRATE },
String.format("%s = %d", "_id", profileId),
null, null, null, "1");
if (c.moveToFirst()) {
Profile rv = new Profile(profileId, c.getString(0), Integer.parseInt(c.getString(1)), Integer.parseInt(c.getString(2)));
c.close();
return rv;
}
else {
return null;
}
}
public long getPrimaryProfileId() {
Cursor c = db.query(ProfileOpenHelper.STATUS_TABLE_NAME,
new String[] { ProfileOpenHelper.CURRENT_PROFILE },
null, null, null, null, "1");
if (c.moveToFirst()) {
long rv = c.getLong(0);
c.close();
return rv;
}
else {
return ProfileOpenHelper.NULL_PROFILE;
}
}
public long getCurrentProfileId() {
Cursor c = db.query(ProfileOpenHelper.STATUS_TABLE_NAME,
new String[] { ProfileOpenHelper.CURRENT_PROFILE, ProfileOpenHelper.TIMED_PROFILE },
null, null, null, null, "1");
if (c.moveToFirst()) {
long current = c.getLong(0);
long timed = c.getInt(1);
c.close();
return (timed == ProfileOpenHelper.NULL_PROFILE) ? current : timed;
}
else {
return ProfileOpenHelper.NULL_PROFILE;
}
}
public Profile getCurrentProfile() {
long currentId = getCurrentProfileId();
return getProfileById(currentId);
}
public String getCurrentProfileName() {
Profile current = getCurrentProfile();
if (current != null) {
return current.name;
}
else {
return null;
}
}
public ProfileInfo getProfileInfo() {
Cursor c = db.query(ProfileOpenHelper.STATUS_TABLE_NAME,
new String[] { ProfileOpenHelper.CURRENT_PROFILE,
ProfileOpenHelper.TIMED_PROFILE,
ProfileOpenHelper.TIMED_EXPIRY },
null, null, null, null, "1");
if (c.moveToFirst()) {
ProfileInfo info = new ProfileInfo();
info.currentProfile = c.getInt(0);
info.timedProfile = c.getInt(1);
info.timedExpiry = c.getLong(2);
c.close();
return info;
}
else {
return null;
}
}
ArrayList<HourMinute> getHistory() {
Cursor c = db.query(ProfileOpenHelper.HISTORY_TABLE_NAME,
new String[] { ProfileOpenHelper.HOUR_OF_DAY, ProfileOpenHelper.MINUTE },
null, null, null, null,
ProfileOpenHelper.HOUR_OF_DAY + "," + ProfileOpenHelper.MINUTE,
null);
ArrayList<HourMinute> a = new ArrayList<HourMinute>(c.getCount());
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
HourMinute hm = new HourMinute(c.getInt(0), c.getInt(1));
a.add(hm);
}
c.close();
return a;
}
boolean setName(long id, CharSequence name) {
ContentValues cv = new ContentValues(1);
cv.put(ProfileOpenHelper.NAME, name.toString());
return (db.update(ProfileOpenHelper.PROFILE_TABLE_NAME, cv,
"_id = ?", new String[] { "" + id }) == 1);
}
boolean setVolume(long id, int volumePercentage) {
ContentValues cv = new ContentValues(1);
cv.put(ProfileOpenHelper.VOLUME, volumePercentage);
return (db.update(ProfileOpenHelper.PROFILE_TABLE_NAME, cv,
"_id = ?", new String[] { "" + id }) == 1);
}
boolean setVibrate(long id, boolean vibrate) {
ContentValues cv = new ContentValues(1);
cv.put(ProfileOpenHelper.VIBRATE, vibrate ? 1 : 0);
return (db.update(ProfileOpenHelper.PROFILE_TABLE_NAME, cv,
"_id = ?", new String[] { "" + id }) == 1);
}
boolean setProfile(long id) {
ContentValues cv = new ContentValues(2);
cv.put(ProfileOpenHelper.CURRENT_PROFILE, id);
cv.put(ProfileOpenHelper.TIMED_PROFILE, ProfileOpenHelper.NULL_PROFILE);
return (db.update(ProfileOpenHelper.STATUS_TABLE_NAME, cv,
null, null) == 1);
}
boolean setTimedProfile(long id, long expiry) {
if (getPrimaryProfileId() == ProfileOpenHelper.NULL_PROFILE) {
/* if we don't have a primary yet, just set it rather than
* trying to set a secondary without a primary
*/
return setProfile(id);
}
ContentValues cv = new ContentValues(2);
cv.put(ProfileOpenHelper.TIMED_PROFILE, id);
cv.put(ProfileOpenHelper.TIMED_EXPIRY, expiry);
return (db.update(ProfileOpenHelper.STATUS_TABLE_NAME, cv,
null, null) == 1);
}
boolean clearTimedProfile() {
return setTimedProfile(ProfileOpenHelper.NULL_PROFILE, 0);
}
// true if the given profile is either the current or the timed
boolean profileIsActive(long profileId) {
Cursor c = db.query(ProfileOpenHelper.STATUS_TABLE_NAME,
new String[] { ProfileOpenHelper.CURRENT_PROFILE, ProfileOpenHelper.TIMED_PROFILE },
null, null, null, null, "1");
if (c.moveToFirst()) {
long rvCurrent = c.getLong(0);
long rvTimed = c.getLong(1);
c.close();
return (profileId == rvCurrent) || (profileId == rvTimed);
}
return false;
}
boolean deleteProfile(long id) {
return (db.delete(ProfileOpenHelper.PROFILE_TABLE_NAME, "_id = ?",
new String[] { String.valueOf(id) }) == 1);
}
long createEmptyProfile() {
ContentValues cv = new ContentValues(3);
cv.put(ProfileOpenHelper.NAME, "");
cv.put(ProfileOpenHelper.VOLUME, 0);
cv.put(ProfileOpenHelper.VIBRATE, 0);
return db.insert(ProfileOpenHelper.PROFILE_TABLE_NAME, null, cv);
}
void recordSelectedTime(int hourOfDay, int minute) {
long now = System.currentTimeMillis();
ContentValues cv = new ContentValues(1);
cv.put(ProfileOpenHelper.LAST_USED, now);
int rows = db.update(ProfileOpenHelper.HISTORY_TABLE_NAME, cv,
String.format("%s = %d and %s = %d", ProfileOpenHelper.HOUR_OF_DAY, hourOfDay,
ProfileOpenHelper.MINUTE, minute),
null);
if (rows == 0) { // haven't used this time before
cv.put(ProfileOpenHelper.HOUR_OF_DAY, hourOfDay);
cv.put(ProfileOpenHelper.MINUTE, minute);
db.insert(ProfileOpenHelper.HISTORY_TABLE_NAME, null, cv);
// now purge older times
Cursor c = db.query(ProfileOpenHelper.HISTORY_TABLE_NAME,
new String[] { ProfileOpenHelper.LAST_USED },
null, null, null, null, ProfileOpenHelper.LAST_USED + " desc",
String.valueOf(ProfileOpenHelper.MAX_RECORDED_TIMES) + ",1");
if (c.moveToFirst()) {
long lastTime = c.getLong(0);
String prune = String.format("delete from %s where %s <= %d",
ProfileOpenHelper.HISTORY_TABLE_NAME, ProfileOpenHelper.LAST_USED,
lastTime);
db.execSQL(prune);
}
}
}
}
| Java |
package org.frasermccrossan.toneitdown;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
public class EditProfile extends Activity {
private ProfileDatabaseHelper pdh;
private Profile profile;
private final int CONFIRM_DIALOG = 1;
Button doneButton;
Button deleteButton;
private OnClickListener buttonListener = new OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
if (v == doneButton) {
if (pdh.profileIsActive(profile._id)) {
Notify.applyProfile(EditProfile.this);
}
EditProfile.this.finish();
}
else if (v == deleteButton) {
if (pdh.profileIsActive(profile._id)) {
Toast.makeText(EditProfile.this, R.string.cannot_delete_active, Toast.LENGTH_SHORT).show();
}
else {
showDialog(CONFIRM_DIALOG);
}
}
}
};
private TextWatcher nameWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
// don't care
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// don't care
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
pdh.setName(profile._id, s);
}
};
private OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// don't care
}
public void onStartTrackingTouch(SeekBar seekBar) {
// don't care
}
public void onStopTrackingTouch(SeekBar seekBar) {
pdh.setVolume(profile._id, seekBar.getProgress());
if (pdh.isCurrent(profile._id)) {
Profile curProfile = pdh.getProfileById(profile._id);
if (curProfile != null) {
curProfile.apply(EditProfile.this, true);
}
}
}
};
private OnCheckedChangeListener vibrateListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
pdh.setVibrate(profile._id, isChecked);
}
};
private void deleteProfile() {
pdh.deleteProfile(profile._id);
this.finish();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CONFIRM_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String message = String.format(getString(R.string.delete_confirm), profile.name);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteProfile();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
return builder.create();
}
return null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_profile);
pdh = new ProfileDatabaseHelper(this);
Intent intent = getIntent();
long profileId = intent.getLongExtra(PickProfile.profileNameTag, -1);
profile = pdh.getProfileById(profileId);
EditText profileNameField = (EditText)findViewById(R.id.profile_name);
profileNameField.setText(profile.name);
profileNameField.addTextChangedListener(nameWatcher);
SeekBar volumeBar = (SeekBar)findViewById(R.id.volume_bar);
volumeBar.setProgress(profile.volume);
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
volumeBar.setMax(am.getStreamMaxVolume(AudioManager.STREAM_RING));
volumeBar.setOnSeekBarChangeListener(volumeListener);
CheckBox vibrateCheckbox = (CheckBox)findViewById(R.id.vibrate_checkbox);
vibrateCheckbox.setChecked(profile.vibrate > 0);
vibrateCheckbox.setOnCheckedChangeListener(vibrateListener);
doneButton = (Button)findViewById(R.id.done);
doneButton.setOnClickListener(buttonListener);
deleteButton = (Button)findViewById(R.id.delete);
deleteButton.setOnClickListener(buttonListener);
super.onCreate(savedInstanceState);
}
@Override
public void onDestroy() {
pdh.close();
super.onDestroy();
}
}
| Java |
package org.frasermccrossan.toneitdown;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ProfileExpirer extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ProfileDatabaseHelper pdh = new ProfileDatabaseHelper(context);
pdh.clearTimedProfile();
Notify.applyProfile(context);
}
}
| Java |
package org.frasermccrossan.toneitdown;
import android.content.Context;
import android.media.AudioManager;
class Profile {
long _id;
String name;
int volume;
int vibrate;
Profile(String name, int volume, int vibrate) {
this.name = name;
this.volume = volume;
this.vibrate = vibrate;
}
Profile(long _id, String name, int volume, int vibrate) {
this._id = _id;
this.name = name;
this.volume = volume;
this.vibrate = vibrate;
}
void apply(Context c, boolean showUI) {
AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
setVibrate(am, AudioManager.VIBRATE_TYPE_RINGER);
setVibrate(am, AudioManager.VIBRATE_TYPE_NOTIFICATION);
setVolume(am, AudioManager.STREAM_RING, showUI ? AudioManager.FLAG_SHOW_UI : 0);
setVolume(am, AudioManager.STREAM_NOTIFICATION, 0);
}
private void setVolume(AudioManager am, int streamType, int flags) {
am.setStreamVolume(streamType, volume, flags);
}
private void setVibrate(AudioManager am, int vibrateType) {
am.setVibrateSetting(vibrateType, vibrate > 0 ? AudioManager.VIBRATE_SETTING_ON : AudioManager.VIBRATE_SETTING_OFF);
}
}
| Java |
package org.frasermccrossan.toneitdown;
import java.text.DateFormat;
import java.util.Calendar;
import android.content.Context;
public class HourMinute {
public int hourOfDay;
public int minute;
HourMinute(int h, int m) {
hourOfDay = h;
minute = m;
}
public String timeAsText(Context c) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0); // why not?
cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
cal.set(Calendar.MINUTE, minute);
DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(c);
return dateFormat.format(cal.getTimeInMillis());
}
}
| Java |
package org.frasermccrossan.toneitdown;
import java.text.DateFormat;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
class Notify {
private static final int NOTIFICATION_ID = 1;
// apply all profile settings described by the database, including
// alarms and notifications
static void applyProfile(Context context) {
ProfileDatabaseHelper dbh = new ProfileDatabaseHelper(context);
ProfileInfo info = dbh.getProfileInfo();
if (info != null) {
Profile currentProfile = dbh.getProfileById(info.currentProfile);
if (currentProfile == null) {
dbh.close();
return;
}
Profile timedProfile = dbh.getProfileById(info.timedProfile);
Profile activeProfile;
int icon;
String tickerText;
String contentText;
if (info.isTimed()) {
activeProfile = timedProfile;
icon = R.drawable.ic_stat_timed;
DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(context);
tickerText = String.format("%s (%s)", timedProfile.name, currentProfile.name);
contentText = String.format(context.getString(R.string.profile_will_revert), currentProfile.name,
dateFormat.format(info.timedExpiry));
}
else {
activeProfile = currentProfile;
icon = R.drawable.ic_stat_current;
tickerText = currentProfile.name;
contentText = "";
}
String contentTitle = String.format(context.getString(R.string.profile_is), activeProfile.name);
Notification.Builder nb = new Notification.Builder(context);
nb.setSmallIcon(icon);
nb.setTicker(tickerText);
nb.setOngoing(true);
nb.setContentTitle(contentTitle);
nb.setContentText(contentText);
nb.setOnlyAlertOnce(false);
nb.setWhen(System.currentTimeMillis());
Intent notificationIntent = new Intent(context, PickProfile.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
nb.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, nb.getNotification());
activeProfile.apply(context, false);
if (info.isTimed()) {
Intent intent = new Intent(context, ProfileExpirer.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 12345, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, info.timedExpiry, sender);
}
dbh.close();
}
}
}
| Java |
package org.frasermccrossan.toneitdown;
import java.util.Locale;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.media.AudioManager;
class ProfileOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "profiledb";
static final String PROFILE_TABLE_NAME = "profiles";
static final String NAME = "name";
static final String VOLUME = "volume";
static final String VIBRATE = "vibrate";
static final String STATUS_TABLE_NAME = "status";
static final String CURRENT_PROFILE = "current_profile";
static final String TIMED_PROFILE = "timed_profile";
static final String TIMED_EXPIRY = "timed_expiry";
static final long NULL_PROFILE = -1;
static final String HISTORY_TABLE_NAME = "history";
static final String HOUR_OF_DAY = "hour_of_day";
static final String MINUTE = "minute";
static final String LAST_USED = "last_used";
static final int MAX_RECORDED_TIMES = 5;
private Context c;
ProfileOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
c = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String s;
s = String.format("CREATE TABLE %s (_id integer primary key, %s TEXT, %s NUMBER, %s BOOLEAN);",
PROFILE_TABLE_NAME, NAME, VOLUME, VIBRATE);
db.execSQL(s);
// find the maximum stream volume and scale out initial entries
AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_RING);
final Profile[] default_profiles = {
new Profile(c.getString(R.string.normal), 75 * maxVolume /100, 0),
new Profile(c.getString(R.string.outdoor), maxVolume, 1),
new Profile(c.getString(R.string.quiet), 20 * maxVolume / 100, 1),
new Profile(c.getString(R.string.silent), 0, 1)
};
for (int i = 0; i < default_profiles.length; ++i) {
s = String.format(Locale.US, "insert into %s (name, volume, vibrate) values ('%s', %d, %d)",
PROFILE_TABLE_NAME,
default_profiles[i].name,
default_profiles[i].volume,
default_profiles[i].vibrate);
db.execSQL(s);
}
s = String.format("CREATE TABLE %s as select %d as %s, %d as %s;",
STATUS_TABLE_NAME, NULL_PROFILE, CURRENT_PROFILE, NULL_PROFILE, TIMED_PROFILE);
db.execSQL(s);
// for first-time users
onUpgrade(db, 1, DATABASE_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int v1, int v2) {
int v;
for (v = v1 + 1; v <= v2; ++v) {
upgradeTo(db, v);
}
}
private void upgradeTo(SQLiteDatabase db, int version) {
switch(version) {
case 2:
upgrade1to2(db);
break;
case 3:
upgrade2to3(db);
break;
}
}
private void upgrade1to2(SQLiteDatabase db) {
String s = String.format("alter table %s add column %s number", STATUS_TABLE_NAME, TIMED_EXPIRY);
db.execSQL(s);
}
private void upgrade2to3(SQLiteDatabase db) {
String s = String.format("create table %s (_id integer primary key, %s number, %s number, %s number)",
HISTORY_TABLE_NAME, HOUR_OF_DAY, MINUTE, LAST_USED);
db.execSQL(s);
}
}
| Java |
package org.frasermccrossan.toneitdown;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
public class PickProfile extends Activity {
private ProfileDatabaseHelper pdh;
private RadioGroup profile_list;
private ActionMode myActionMode = null;
Cursor allProfileCursor;
static final String profileNameTag = "profileName";
private long longClickedProfile;
private static final int TIME_DIALOG = 0;
private static final int HISTORY_DIALOG = 1;
Button newButton;
private OnClickListener profilesListener = new OnClickListener () {
public void onClick(View v) {
long profileId = (Long)v.getTag();
if (pdh.setProfile(profileId)) {
Notify.applyProfile(PickProfile.this);
PickProfile.this.finish();
}
}
};
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
if (v == newButton) {
long newProfileId = pdh.createEmptyProfile();
if (newProfileId != -1) {
startEdit(newProfileId);
}
}
}
};
private OnLongClickListener longListener = new OnLongClickListener() {
public boolean onLongClick(View v) {
if (myActionMode != null) {
return false;
}
longClickedProfile = (Long)((RadioButton) v).getTag();
// Start the CAB using the ActionMode.Callback defined above
myActionMode = PickProfile.this.startActionMode(myActionModeCallback);
return true;
}
};
private void startEdit(long profileId) {
Intent editIntent = new Intent(PickProfile.this, EditProfile.class);
editIntent.putExtra(profileNameTag, profileId);
startActivity(editIntent);
}
private ActionMode.Callback myActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.profile_context_menu, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
@SuppressWarnings("deprecation")
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_profile:
startEdit(longClickedProfile);
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.timed_profile:
// all we do here is set up a time picker dialog, the listener does the real work
showDialog(HISTORY_DIALOG);
mode.finish();
return true;
default:
return false;
}
}
// Called when the user exits the action mode
@Override
public void onDestroyActionMode(ActionMode mode) {
myActionMode = null;
}
};
private void setExpiryTime(int hourOfDay, int minute) {
Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0); // why not?
Calendar expireTime = (Calendar)now.clone();
expireTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
expireTime.set(Calendar.MINUTE, minute);
if (expireTime.before(now)) {
// make sure expiry time is in the future
expireTime.add(Calendar.HOUR_OF_DAY, 24);
}
pdh.setTimedProfile(longClickedProfile, expireTime.getTimeInMillis());
pdh.recordSelectedTime(hourOfDay, minute);
Notify.applyProfile(PickProfile.this);
PickProfile.this.finish();
}
private TimePickerDialog.OnTimeSetListener timeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setExpiryTime(hourOfDay, minute);
}
};
TimePickerDialog makeTimePicker() {
Calendar cal = Calendar.getInstance();
TimePickerDialog tp = new TimePickerDialog(this, timeSetListener,
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
DateFormat.is24HourFormat(PickProfile.this));
Profile profile = pdh.getProfileById(longClickedProfile);
String title = String.format(getString(R.string.profile_expiry_time), profile.name);
tp.setTitle(title);
return tp;
}
AlertDialog makeHistoryDialog(ArrayList<HourMinute> history) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Profile profile = pdh.getProfileById(longClickedProfile);
String title = String.format(getString(R.string.profile_expiry_time), profile.name);
builder.setTitle(title)
.setCancelable(true)
.setPositiveButton(getString(R.string.other_time), new DialogInterface.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(DialogInterface dialog, int id) {
showDialog(TIME_DIALOG);
}
})
.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
String[] hText = new String[history.size()];
int i;
for (i = 0; i < history.size(); ++i) {
hText[i] = history.get(i).timeAsText(PickProfile.this);
}
builder.setItems(hText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AlertDialog aDialog = (AlertDialog)(dialog);
@SuppressWarnings("unchecked")
ArrayList<HourMinute> hourMinArray = (ArrayList<HourMinute>)aDialog.getListView().getTag();
HourMinute hm = hourMinArray.get(id);
setExpiryTime(hm.hourOfDay, hm.minute);
}
});
AlertDialog dialog = builder.create();
// store the historylist in the listview so it can be used later
View listView = dialog.getListView();
listView.setTag(history);
return dialog;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG:
return makeTimePicker();
case HISTORY_DIALOG:
ArrayList<HourMinute> history = pdh.getHistory();
if (history.size() == 0) {
return makeTimePicker();
}
else {
return makeHistoryDialog(history);
}
}
return null;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pdh = new ProfileDatabaseHelper(this);
setContentView(R.layout.pick_profile);
Notify.applyProfile(this); // make sure notification is present
profile_list = (RadioGroup)findViewById(R.id.profile_list);
newButton = (Button)findViewById(R.id.new_button);
newButton.setOnClickListener(buttonListener);
}
@Override
public void onStart() {
super.onStart();
allProfileCursor = pdh.allProfiles();
int checkedId = -1;
long currentProfile = pdh.getCurrentProfileId();
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
for (allProfileCursor.moveToFirst(); !allProfileCursor.isAfterLast(); allProfileCursor.moveToNext()) {
//RadioButton rb = new RadioButton(this);
RadioButton rb = (RadioButton)inflater.inflate(R.layout.profile_radio_layout, null);
rb.setText(allProfileCursor.getString(1));
rb.setOnClickListener(profilesListener);
rb.setOnLongClickListener(longListener);
rb.setTag(new Long(allProfileCursor.getLong(0)));
profile_list.addView(rb, lp);
if (allProfileCursor.getLong(0) == currentProfile) {
checkedId = rb.getId();
}
}
profile_list.check(checkedId);
allProfileCursor.close();
}
@Override
protected void onStop() {
profile_list.removeAllViews();
super.onStop();
}
@Override
public void onDestroy() {
pdh.close();
super.onDestroy();
}
} | Java |
package org.frasermccrossan.toneitdown;
class ProfileInfo {
int currentProfile;
int timedProfile;
long timedExpiry;
public boolean isTimed() {
return (timedProfile != ProfileOpenHelper.NULL_PROFILE && timedExpiry > 0);
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.app;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
String SENDER_ID = "Your-Sender-ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Demo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
Context context;
String regid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
@Override
protected void onResume() {
super.onResume();
// Check device for Play Services APK.
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Stores the registration ID and the app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGcmPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Gets the current registration ID for application on GCM service, if there is one.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
// Send an upstream message.
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGcmPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.app;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* This {@code WakefulBroadcastReceiver} takes care of creating and managing a
* partial wake lock for your app. It passes off the work of processing the GCM
* message to an {@code IntentService}, while ensuring that the device does not
* go back to sleep in the transition. The {@code IntentService} calls
* {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to
* release the wake lock.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| Java |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed 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 com.google.android.gcm.demo.app;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {@code IntentService} does the actual handling of the GCM message.
* {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {@code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.server;
import java.io.IOException;
/**
* Exception thrown when GCM returned an error due to an invalid request.
* <p>
* This is equivalent to GCM posts that return an HTTP error different of 200.
*/
public final class InvalidRequestException extends IOException {
private final int status;
private final String description;
public InvalidRequestException(int status) {
this(status, null);
}
public InvalidRequestException(int status, String description) {
super(getMessage(status, description));
this.status = status;
this.description = description;
}
private static String getMessage(int status, String description) {
StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status);
if (description != null) {
base.append("(").append(description).append(")");
}
return base.toString();
}
/**
* Gets the HTTP Status Code.
*/
public int getHttpStatusCode() {
return status;
}
/**
* Gets the error description.
*/
public String getDescription() {
return description;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.server;
import java.io.Serializable;
/**
* Result of a GCM message request that returned HTTP status code 200.
*
* <p>
* If the message is successfully created, the {@link #getMessageId()} returns
* the message id and {@link #getErrorCodeName()} returns {@literal null};
* otherwise, {@link #getMessageId()} returns {@literal null} and
* {@link #getErrorCodeName()} returns the code of the error.
*
* <p>
* There are cases when a request is accept and the message successfully
* created, but GCM has a canonical registration id for that device. In this
* case, the server should update the registration id to avoid rejected requests
* in the future.
*
* <p>
* In a nutshell, the workflow to handle a result is:
* <pre>
* - Call {@link #getMessageId()}:
* - {@literal null} means error, call {@link #getErrorCodeName()}
* - non-{@literal null} means the message was created:
* - Call {@link #getCanonicalRegistrationId()}
* - if it returns {@literal null}, do nothing.
* - otherwise, update the server datastore with the new id.
* </pre>
*/
public final class Result implements Serializable {
private final String messageId;
private final String canonicalRegistrationId;
private final String errorCode;
public static final class Builder {
// optional parameters
private String messageId;
private String canonicalRegistrationId;
private String errorCode;
public Builder canonicalRegistrationId(String value) {
canonicalRegistrationId = value;
return this;
}
public Builder messageId(String value) {
messageId = value;
return this;
}
public Builder errorCode(String value) {
errorCode = value;
return this;
}
public Result build() {
return new Result(this);
}
}
private Result(Builder builder) {
canonicalRegistrationId = builder.canonicalRegistrationId;
messageId = builder.messageId;
errorCode = builder.errorCode;
}
/**
* Gets the message id, if any.
*/
public String getMessageId() {
return messageId;
}
/**
* Gets the canonical registration id, if any.
*/
public String getCanonicalRegistrationId() {
return canonicalRegistrationId;
}
/**
* Gets the error code, if any.
*/
public String getErrorCodeName() {
return errorCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (messageId != null) {
builder.append(" messageId=").append(messageId);
}
if (canonicalRegistrationId != null) {
builder.append(" canonicalRegistrationId=")
.append(canonicalRegistrationId);
}
if (errorCode != null) {
builder.append(" errorCode=").append(errorCode);
}
return builder.append(" ]").toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.server;
import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS;
import static com.google.android.gcm.server.Constants.JSON_ERROR;
import static com.google.android.gcm.server.Constants.JSON_FAILURE;
import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID;
import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID;
import static com.google.android.gcm.server.Constants.JSON_PAYLOAD;
import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS;
import static com.google.android.gcm.server.Constants.JSON_RESULTS;
import static com.google.android.gcm.server.Constants.JSON_SUCCESS;
import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY;
import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE;
import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN;
import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX;
import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID;
import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME;
import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE;
import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID;
import static com.google.android.gcm.server.Constants.TOKEN_ERROR;
import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID;
import com.google.android.gcm.server.Result.Builder;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper class to send messages to the GCM service using an API Key.
*/
public class Sender {
protected static final String UTF8 = "UTF-8";
/**
* Initial delay before first retry, without jitter.
*/
protected static final int BACKOFF_INITIAL_DELAY = 1000;
/**
* Maximum delay before a retry.
*/
protected static final int MAX_BACKOFF_DELAY = 1024000;
protected final Random random = new Random();
protected static final Logger logger =
Logger.getLogger(Sender.class.getName());
private final String key;
/**
* Default constructor.
*
* @param key API key obtained through the Google API Console.
*/
public Sender(String key) {
this.key = nonNull(key);
}
/**
* Sends a message to one device, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent, including the device's registration id.
* @param registrationId device where the message will be sent.
* @param retries number of retries in case of service unavailability errors.
*
* @return result of the request (see its javadoc for more details).
*
* @throws IllegalArgumentException if registrationId is {@literal null}.
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IOException if message could not be sent.
*/
public Result send(Message message, String registrationId, int retries)
throws IOException {
int attempt = 0;
Result result = null;
int backoff = BACKOFF_INITIAL_DELAY;
boolean tryAgain;
do {
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + registrationId);
}
result = sendNoRetry(message, registrationId);
tryAgain = result == null && attempt <= retries;
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (result == null) {
throw new IOException("Could not send message after " + attempt +
" attempts");
}
return result;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, String, int)} for more info.
*
* @return result of the post, or {@literal null} if the GCM service was
* unavailable or any network exception caused the request to fail.
*
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IllegalArgumentException if registrationId is {@literal null}.
*/
public Result sendNoRetry(Message message, String registrationId)
throws IOException {
StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
Boolean delayWhileIdle = message.isDelayWhileIdle();
if (delayWhileIdle != null) {
addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
}
Boolean dryRun = message.isDryRun();
if (dryRun != null) {
addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
}
String collapseKey = message.getCollapseKey();
if (collapseKey != null) {
addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
}
String restrictedPackageName = message.getRestrictedPackageName();
if (restrictedPackageName != null) {
addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
}
Integer timeToLive = message.getTimeToLive();
if (timeToLive != null) {
addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
}
for (Entry<String, String> entry : message.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
logger.warning("Ignoring payload entry thas has null: " + entry);
} else {
key = PARAM_PAYLOAD_PREFIX + key;
addParameter(body, key, URLEncoder.encode(value, UTF8));
}
}
String requestBody = body.toString();
logger.finest("Request body: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
if (status / 100 == 5) {
logger.fine("GCM service is unavailable (status " + status + ")");
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("Plain post error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
} else {
try {
responseBody = getAndClose(conn.getInputStream());
} catch (IOException e) {
logger.log(Level.WARNING, "Exception reading response: ", e);
// return null so it can retry
return null;
}
}
String[] lines = responseBody.split("\n");
if (lines.length == 0 || lines[0].equals("")) {
throw new IOException("Received empty response from GCM service.");
}
String firstLine = lines[0];
String[] responseParts = split(firstLine);
String token = responseParts[0];
String value = responseParts[1];
if (token.equals(TOKEN_MESSAGE_ID)) {
Builder builder = new Result.Builder().messageId(value);
// check for canonical registration id
if (lines.length > 1) {
String secondLine = lines[1];
responseParts = split(secondLine);
token = responseParts[0];
value = responseParts[1];
if (token.equals(TOKEN_CANONICAL_REG_ID)) {
builder.canonicalRegistrationId(value);
} else {
logger.warning("Invalid response from GCM: " + responseBody);
}
}
Result result = builder.build();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Message created succesfully (" + result + ")");
}
return result;
} else if (token.equals(TOKEN_ERROR)) {
return new Result.Builder().errorCode(value).build();
} else {
throw new IOException("Invalid response from GCM: " + responseBody);
}
}
/**
* Sends a message to many devices, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent.
* @param regIds registration id of the devices that will receive
* the message.
* @param retries number of retries in case of service unavailability errors.
*
* @return combined result of all requests made.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
* @throws IOException if message could not be sent.
*/
public MulticastResult send(Message message, List<String> regIds, int retries)
throws IOException {
int attempt = 0;
MulticastResult multicastResult;
int backoff = BACKOFF_INITIAL_DELAY;
// Map of results by registration id, it will be updated after each attempt
// to send the messages
Map<String, Result> results = new HashMap<String, Result>();
List<String> unsentRegIds = new ArrayList<String>(regIds);
boolean tryAgain;
List<Long> multicastIds = new ArrayList<Long>();
do {
multicastResult = null;
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + unsentRegIds);
}
try {
multicastResult = sendNoRetry(message, unsentRegIds);
} catch(IOException e) {
// no need for WARNING since exception might be already logged
logger.log(Level.FINEST, "IOException on attempt " + attempt, e);
}
if (multicastResult != null) {
long multicastId = multicastResult.getMulticastId();
logger.fine("multicast_id on attempt # " + attempt + ": " +
multicastId);
multicastIds.add(multicastId);
unsentRegIds = updateStatus(unsentRegIds, results, multicastResult);
tryAgain = !unsentRegIds.isEmpty() && attempt <= retries;
} else {
tryAgain = attempt <= retries;
}
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (multicastIds.isEmpty()) {
// all JSON posts failed due to GCM unavailability
throw new IOException("Could not post JSON requests to GCM after "
+ attempt + " attempts");
}
// calculate summary
int success = 0, failure = 0 , canonicalIds = 0;
for (Result result : results.values()) {
if (result.getMessageId() != null) {
success++;
if (result.getCanonicalRegistrationId() != null) {
canonicalIds++;
}
} else {
failure++;
}
}
// build a new object with the overall result
long multicastId = multicastIds.remove(0);
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId).retryMulticastIds(multicastIds);
// add results, in the same order as the input
for (String regId : regIds) {
Result result = results.get(regId);
builder.addResult(result);
}
return builder.build();
}
/**
* Updates the status of the messages sent to devices and the list of devices
* that should be retried.
*
* @param unsentRegIds list of devices that are still pending an update.
* @param allResults map of status that will be updated.
* @param multicastResult result of the last multicast sent.
*
* @return updated version of devices that should be retried.
*/
private List<String> updateStatus(List<String> unsentRegIds,
Map<String, Result> allResults, MulticastResult multicastResult) {
List<Result> results = multicastResult.getResults();
if (results.size() != unsentRegIds.size()) {
// should never happen, unless there is a flaw in the algorithm
throw new RuntimeException("Internal error: sizes do not match. " +
"currentResults: " + results + "; unsentRegIds: " + unsentRegIds);
}
List<String> newUnsentRegIds = new ArrayList<String>();
for (int i = 0; i < unsentRegIds.size(); i++) {
String regId = unsentRegIds.get(i);
Result result = results.get(i);
allResults.put(regId, result);
String error = result.getErrorCodeName();
if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE)
|| error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) {
newUnsentRegIds.add(regId);
}
}
return newUnsentRegIds;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, List, int)} for more info.
*
* @return multicast results if the message was sent successfully,
* {@literal null} if it failed but could be retried.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 status.
* @throws IOException if there was a JSON parsing error
*/
public MulticastResult sendNoRetry(Message message,
List<String> registrationIds) throws IOException {
if (nonNull(registrationIds).isEmpty()) {
throw new IllegalArgumentException("registrationIds cannot be empty");
}
Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE,
message.isDelayWhileIdle());
setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
Map<String, String> payload = message.getData();
if (!payload.isEmpty()) {
jsonRequest.put(JSON_PAYLOAD, payload);
}
String requestBody = JSONValue.toJSONString(jsonRequest);
logger.finest("JSON request: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("JSON error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
}
try {
responseBody = getAndClose(conn.getInputStream());
} catch(IOException e) {
logger.log(Level.WARNING, "IOException reading response", e);
return null;
}
logger.finest("JSON response: " + responseBody);
JSONParser parser = new JSONParser();
JSONObject jsonResponse;
try {
jsonResponse = (JSONObject) parser.parse(responseBody);
int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId);
@SuppressWarnings("unchecked")
List<Map<String, Object>> results =
(List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
if (results != null) {
for (Map<String, Object> jsonResult : results) {
String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
String canonicalRegId =
(String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
String error = (String) jsonResult.get(JSON_ERROR);
Result result = new Result.Builder()
.messageId(messageId)
.canonicalRegistrationId(canonicalRegId)
.errorCode(error)
.build();
builder.addResult(result);
}
}
MulticastResult multicastResult = builder.build();
return multicastResult;
} catch (ParseException e) {
throw newIoException(responseBody, e);
} catch (CustomParserException e) {
throw newIoException(responseBody, e);
}
}
private IOException newIoException(String responseBody, Exception e) {
// log exception, as IOException constructor that takes a message and cause
// is only available on Java 6
String msg = "Error parsing JSON response (" + responseBody + ")";
logger.log(Level.WARNING, msg, e);
return new IOException(msg + ":" + e);
}
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore error
logger.log(Level.FINEST, "IOException closing stream", e);
}
}
}
/**
* Sets a JSON field, but only if the value is not {@literal null}.
*/
private void setJsonField(Map<Object, Object> json, String field,
Object value) {
if (value != null) {
json.put(field, value);
}
}
private Number getNumber(Map<?, ?> json, String field) {
Object value = json.get(field);
if (value == null) {
throw new CustomParserException("Missing field: " + field);
}
if (!(value instanceof Number)) {
throw new CustomParserException("Field " + field +
" does not contain a number: " + value);
}
return (Number) value;
}
class CustomParserException extends RuntimeException {
CustomParserException(String message) {
super(message);
}
}
private String[] split(String line) throws IOException {
String[] split = line.split("=", 2);
if (split.length != 2) {
throw new IOException("Received invalid response line from GCM: " + line);
}
return split;
}
/**
* Make an HTTP post to a given URL.
*
* @return HTTP response.
*/
protected HttpURLConnection post(String url, String body)
throws IOException {
return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body);
}
/**
* Makes an HTTP POST request to a given endpoint.
*
* <p>
* <strong>Note: </strong> the returned connected should not be disconnected,
* otherwise it would kill persistent connections made using Keep-Alive.
*
* @param url endpoint to post the request.
* @param contentType type of request.
* @param body body of the request.
*
* @return the underlying connection.
*
* @throws IOException propagated from underlying methods.
*/
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
if (url == null || body == null) {
throw new IllegalArgumentException("arguments cannot be null");
}
if (!url.startsWith("https://")) {
logger.warning("URL does not use https: " + url);
}
logger.fine("Sending POST to " + url);
logger.finest("POST body: " + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
try {
out.write(bytes);
} finally {
close(out);
}
return conn;
}
/**
* Creates a map with just one key-value pair.
*/
protected static final Map<String, String> newKeyValues(String key,
String value) {
Map<String, String> keyValues = new HashMap<String, String>(1);
keyValues.put(nonNull(key), nonNull(value));
return keyValues;
}
/**
* Creates a {@link StringBuilder} to be used as the body of an HTTP POST.
*
* @param name initial parameter for the POST.
* @param value initial value for that parameter.
* @return StringBuilder to be used an HTTP POST body.
*/
protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Adds a new parameter to the HTTP POST body.
*
* @param body HTTP POST body.
* @param name parameter's name.
* @param value parameter's value.
*/
protected static void addParameter(StringBuilder body, String name,
String value) {
nonNull(body).append('&')
.append(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Gets an {@link HttpURLConnection} given an URL.
*/
protected HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
return conn;
}
/**
* Convenience method to convert an InputStream to a String.
* <p>
* If the stream ends in a newline character, it will be stripped.
* <p>
* If the stream is {@literal null}, returns an empty string.
*/
protected static String getString(InputStream stream) throws IOException {
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
// strip last newline
content.setLength(content.length() - 1);
}
return content.toString();
}
private static String getAndClose(InputStream stream) throws IOException {
try {
return getString(stream);
} finally {
if (stream != null) {
close(stream);
}
}
}
static <T> T nonNull(T argument) {
if (argument == null) {
throw new IllegalArgumentException("argument cannot be null");
}
return argument;
}
void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.server;
/**
* Constants used on GCM service communication.
*/
public final class Constants {
/**
* Endpoint for sending messages.
*/
public static final String GCM_SEND_ENDPOINT =
"https://android.googleapis.com/gcm/send";
/**
* HTTP parameter for registration id.
*/
public static final String PARAM_REGISTRATION_ID = "registration_id";
/**
* HTTP parameter for collapse key.
*/
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
/**
* HTTP parameter for delaying the message delivery if the device is idle.
*/
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
/**
* HTTP parameter for telling gcm to validate the message without actually sending it.
*/
public static final String PARAM_DRY_RUN = "dry_run";
/**
* HTTP parameter for package name that can be used to restrict message delivery by matching
* against the package name used to generate the registration id.
*/
public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name";
/**
* Prefix to HTTP parameter used to pass key-values in the message payload.
*/
public static final String PARAM_PAYLOAD_PREFIX = "data.";
/**
* Prefix to HTTP parameter used to set the message time-to-live.
*/
public static final String PARAM_TIME_TO_LIVE = "time_to_live";
/**
* Too many messages sent by the sender. Retry after a while.
*/
public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded";
/**
* Too many messages sent by the sender to a specific device.
* Retry after a while.
*/
public static final String ERROR_DEVICE_QUOTA_EXCEEDED =
"DeviceQuotaExceeded";
/**
* Missing registration_id.
* Sender should always add the registration_id to the request.
*/
public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration";
/**
* Bad registration_id. Sender should remove this registration_id.
*/
public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration";
/**
* The sender_id contained in the registration_id does not match the
* sender_id used to register with the GCM servers.
*/
public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId";
/**
* The user has uninstalled the application or turned off notifications.
* Sender should stop sending messages to this device and delete the
* registration_id. The client needs to re-register with the GCM servers to
* receive notifications again.
*/
public static final String ERROR_NOT_REGISTERED = "NotRegistered";
/**
* The payload of the message is too big, see the limitations.
* Reduce the size of the message.
*/
public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig";
/**
* Collapse key is required. Include collapse key in the request.
*/
public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey";
/**
* A particular message could not be sent because the GCM servers were not
* available. Used only on JSON requests, as in plain text requests
* unavailability is indicated by a 503 response.
*/
public static final String ERROR_UNAVAILABLE = "Unavailable";
/**
* A particular message could not be sent because the GCM servers encountered
* an error. Used only on JSON requests, as in plain text requests internal
* errors are indicated by a 500 response.
*/
public static final String ERROR_INTERNAL_SERVER_ERROR =
"InternalServerError";
/**
* Time to Live value passed is less than zero or more than maximum.
*/
public static final String ERROR_INVALID_TTL= "InvalidTtl";
/**
* Token returned by GCM when a message was successfully sent.
*/
public static final String TOKEN_MESSAGE_ID = "id";
/**
* Token returned by GCM when the requested registration id has a canonical
* value.
*/
public static final String TOKEN_CANONICAL_REG_ID = "registration_id";
/**
* Token returned by GCM when there was an error sending a message.
*/
public static final String TOKEN_ERROR = "Error";
/**
* JSON-only field representing the registration ids.
*/
public static final String JSON_REGISTRATION_IDS = "registration_ids";
/**
* JSON-only field representing the payload data.
*/
public static final String JSON_PAYLOAD = "data";
/**
* JSON-only field representing the number of successful messages.
*/
public static final String JSON_SUCCESS = "success";
/**
* JSON-only field representing the number of failed messages.
*/
public static final String JSON_FAILURE = "failure";
/**
* JSON-only field representing the number of messages with a canonical
* registration id.
*/
public static final String JSON_CANONICAL_IDS = "canonical_ids";
/**
* JSON-only field representing the id of the multicast request.
*/
public static final String JSON_MULTICAST_ID = "multicast_id";
/**
* JSON-only field representing the result of each individual request.
*/
public static final String JSON_RESULTS = "results";
/**
* JSON-only field representing the error field of an individual request.
*/
public static final String JSON_ERROR = "error";
/**
* JSON-only field sent by GCM when a message was successfully sent.
*/
public static final String JSON_MESSAGE_ID = "message_id";
private Constants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.server;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* GCM message.
*
* <p>
* Instances of this class are immutable and should be created using a
* {@link Builder}. Examples:
*
* <strong>Simplest message:</strong>
* <pre><code>
* Message message = new Message.Builder().build();
* </pre></code>
*
* <strong>Message with optional attributes:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .build();
* </pre></code>
*
* <strong>Message with optional attributes and payload data:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .addData("key1", "value1")
* .addData("key2", "value2")
* .build();
* </pre></code>
*/
public final class Message implements Serializable {
private final String collapseKey;
private final Boolean delayWhileIdle;
private final Integer timeToLive;
private final Map<String, String> data;
private final Boolean dryRun;
private final String restrictedPackageName;
public static final class Builder {
private final Map<String, String> data;
// optional parameters
private String collapseKey;
private Boolean delayWhileIdle;
private Integer timeToLive;
private Boolean dryRun;
private String restrictedPackageName;
public Builder() {
this.data = new LinkedHashMap<String, String>();
}
/**
* Sets the collapseKey property.
*/
public Builder collapseKey(String value) {
collapseKey = value;
return this;
}
/**
* Sets the delayWhileIdle property (default value is {@literal false}).
*/
public Builder delayWhileIdle(boolean value) {
delayWhileIdle = value;
return this;
}
/**
* Sets the time to live, in seconds.
*/
public Builder timeToLive(int value) {
timeToLive = value;
return this;
}
/**
* Adds a key/value pair to the payload data.
*/
public Builder addData(String key, String value) {
data.put(key, value);
return this;
}
/**
* Sets the dryRun property (default value is {@literal false}).
*/
public Builder dryRun(boolean value) {
dryRun = value;
return this;
}
/**
* Sets the restrictedPackageName property.
*/
public Builder restrictedPackageName(String value) {
restrictedPackageName = value;
return this;
}
public Message build() {
return new Message(this);
}
}
private Message(Builder builder) {
collapseKey = builder.collapseKey;
delayWhileIdle = builder.delayWhileIdle;
data = Collections.unmodifiableMap(builder.data);
timeToLive = builder.timeToLive;
dryRun = builder.dryRun;
restrictedPackageName = builder.restrictedPackageName;
}
/**
* Gets the collapse key.
*/
public String getCollapseKey() {
return collapseKey;
}
/**
* Gets the delayWhileIdle flag.
*/
public Boolean isDelayWhileIdle() {
return delayWhileIdle;
}
/**
* Gets the time to live (in seconds).
*/
public Integer getTimeToLive() {
return timeToLive;
}
/**
* Gets the dryRun flag.
*/
public Boolean isDryRun() {
return dryRun;
}
/**
* Gets the restricted package name.
*/
public String getRestrictedPackageName() {
return restrictedPackageName;
}
/**
* Gets the payload data, which is immutable.
*/
public Map<String, String> getData() {
return data;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Message(");
if (collapseKey != null) {
builder.append("collapseKey=").append(collapseKey).append(", ");
}
if (timeToLive != null) {
builder.append("timeToLive=").append(timeToLive).append(", ");
}
if (delayWhileIdle != null) {
builder.append("delayWhileIdle=").append(delayWhileIdle).append(", ");
}
if (dryRun != null) {
builder.append("dryRun=").append(dryRun).append(", ");
}
if (restrictedPackageName != null) {
builder.append("restrictedPackageName=").append(restrictedPackageName).append(", ");
}
if (!data.isEmpty()) {
builder.append("data: {");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(",");
}
builder.delete(builder.length() - 1, builder.length());
builder.append("}");
}
if (builder.charAt(builder.length() - 1) == ' ') {
builder.delete(builder.length() - 2, builder.length());
}
builder.append(")");
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.server;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result of a GCM multicast message request .
*/
public final class MulticastResult implements Serializable {
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
private final List<Result> results;
private final List<Long> retryMulticastIds;
public static final class Builder {
private final List<Result> results = new ArrayList<Result>();
// required parameters
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
// optional parameters
private List<Long> retryMulticastIds;
public Builder(int success, int failure, int canonicalIds,
long multicastId) {
this.success = success;
this.failure = failure;
this.canonicalIds = canonicalIds;
this.multicastId = multicastId;
}
public Builder addResult(Result result) {
results.add(result);
return this;
}
public Builder retryMulticastIds(List<Long> retryMulticastIds) {
this.retryMulticastIds = retryMulticastIds;
return this;
}
public MulticastResult build() {
return new MulticastResult(this);
}
}
private MulticastResult(Builder builder) {
success = builder.success;
failure = builder.failure;
canonicalIds = builder.canonicalIds;
multicastId = builder.multicastId;
results = Collections.unmodifiableList(builder.results);
List<Long> tmpList = builder.retryMulticastIds;
if (tmpList == null) {
tmpList = Collections.emptyList();
}
retryMulticastIds = Collections.unmodifiableList(tmpList);
}
/**
* Gets the multicast id.
*/
public long getMulticastId() {
return multicastId;
}
/**
* Gets the number of successful messages.
*/
public int getSuccess() {
return success;
}
/**
* Gets the total number of messages sent, regardless of the status.
*/
public int getTotal() {
return success + failure;
}
/**
* Gets the number of failed messages.
*/
public int getFailure() {
return failure;
}
/**
* Gets the number of successful messages that also returned a canonical
* registration id.
*/
public int getCanonicalIds() {
return canonicalIds;
}
/**
* Gets the results of each individual message, which is immutable.
*/
public List<Result> getResults() {
return results;
}
/**
* Gets additional ids if more than one multicast message was sent.
*/
public List<Long> getRetryMulticastIds() {
return retryMulticastIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MulticastResult(")
.append("multicast_id=").append(multicastId).append(",")
.append("total=").append(getTotal()).append(",")
.append("success=").append(success).append(",")
.append("failure=").append(failure).append(",")
.append("canonical_ids=").append(canonicalIds).append(",");
if (!results.isEmpty()) {
builder.append("results: " + results);
}
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm;
import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE;
import static com.google.android.gcm.GCMConstants.EXTRA_ERROR;
import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID;
import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE;
import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED;
import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK;
import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Skeleton for application-specific {@link IntentService}s responsible for
* handling communication from Google Cloud Messaging service.
* <p>
* The abstract methods in this class are called from its worker thread, and
* hence should run in a limited amount of time. If they execute long
* operations, they should spawn new threads, otherwise the worker thread will
* be blocked.
* <p>
* Subclasses must provide a public no-arg constructor.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public abstract class GCMBaseIntentService extends IntentService {
/**
* Old TAG used for logging. Marked as deprecated since it should have
* been private at first place.
*/
@Deprecated
public static final String TAG = "GCMBaseIntentService";
private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService",
"[" + getClass().getName() + "]: ");
// wakelock
private static final String WAKELOCK_KEY = "GCM_LIB";
private static PowerManager.WakeLock sWakeLock;
// Java lock used to synchronize access to sWakelock
private static final Object LOCK = GCMBaseIntentService.class;
private final String[] mSenderIds;
// instance counter
private static int sCounter = 0;
private static final Random sRandom = new Random();
private static final int MAX_BACKOFF_MS =
(int) TimeUnit.SECONDS.toMillis(3600); // 1 hour
/**
* Constructor that does not set a sender id, useful when the sender id
* is context-specific.
* <p>
* When using this constructor, the subclass <strong>must</strong>
* override {@link #getSenderIds(Context)}, otherwise methods such as
* {@link #onHandleIntent(Intent)} will throw an
* {@link IllegalStateException} on runtime.
*/
protected GCMBaseIntentService() {
this(getName("DynamicSenderIds"), null);
}
/**
* Constructor used when the sender id(s) is fixed.
*/
protected GCMBaseIntentService(String... senderIds) {
this(getName(senderIds), senderIds);
}
private GCMBaseIntentService(String name, String[] senderIds) {
super(name); // name is used as base name for threads, etc.
mSenderIds = senderIds;
mLogger.log(Log.VERBOSE, "Intent service name: %s", name);
}
private static String getName(String senderId) {
String name = "GCMIntentService-" + senderId + "-" + (++sCounter);
return name;
}
private static String getName(String[] senderIds) {
String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds);
return getName(flatSenderIds);
}
/**
* Gets the sender ids.
*
* <p>By default, it returns the sender ids passed in the constructor, but
* it could be overridden to provide a dynamic sender id.
*
* @throws IllegalStateException if sender id was not set on constructor.
*/
protected String[] getSenderIds(Context context) {
if (mSenderIds == null) {
throw new IllegalStateException("sender id not set on constructor");
}
return mSenderIds;
}
/**
* Called when a cloud message has been received.
*
* @param context application's context.
* @param intent intent containing the message payload as extras.
*/
protected abstract void onMessage(Context context, Intent intent);
/**
* Called when the GCM server tells pending messages have been deleted
* because the device was idle.
*
* @param context application's context.
* @param total total number of collapsed messages
*/
protected void onDeletedMessages(Context context, int total) {
}
/**
* Called on a registration error that could be retried.
*
* <p>By default, it does nothing and returns {@literal true}, but could be
* overridden to change that behavior and/or display the error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*
* @return if {@literal true}, failed operation will be retried (using
* exponential backoff).
*/
protected boolean onRecoverableError(Context context, String errorId) {
return true;
}
/**
* Called on registration or unregistration error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*/
protected abstract void onError(Context context, String errorId);
/**
* Called after a device has been registered.
*
* @param context application's context.
* @param registrationId the registration id returned by the GCM service.
*/
protected abstract void onRegistered(Context context,
String registrationId);
/**
* Called after a device has been unregistered.
*
* @param registrationId the registration id that was previously registered.
* @param context application's context.
*/
protected abstract void onUnregistered(Context context,
String registrationId);
@Override
public final void onHandleIntent(Intent intent) {
try {
Context context = getApplicationContext();
String action = intent.getAction();
if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) {
GCMRegistrar.setRetryBroadcastReceiver(context);
handleRegistration(context, intent);
} else if (action.equals(INTENT_FROM_GCM_MESSAGE)) {
// checks for special messages
String messageType =
intent.getStringExtra(EXTRA_SPECIAL_MESSAGE);
if (messageType != null) {
if (messageType.equals(VALUE_DELETED_MESSAGES)) {
String sTotal =
intent.getStringExtra(EXTRA_TOTAL_DELETED);
if (sTotal != null) {
try {
int total = Integer.parseInt(sTotal);
mLogger.log(Log.VERBOSE,
"Received notification for %d deleted"
+ "messages", total);
onDeletedMessages(context, total);
} catch (NumberFormatException e) {
mLogger.log(Log.ERROR, "GCM returned invalid "
+ "number of deleted messages (%d)",
sTotal);
}
}
} else {
// application is not using the latest GCM library
mLogger.log(Log.ERROR,
"Received unknown special message: %s",
messageType);
}
} else {
onMessage(context, intent);
}
} else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) {
String packageOnIntent = intent.getPackage();
if (packageOnIntent == null || !packageOnIntent.equals(
getApplicationContext().getPackageName())) {
mLogger.log(Log.ERROR,
"Ignoring retry intent from another package (%s)",
packageOnIntent);
return;
}
// retry last call
if (GCMRegistrar.isRegistered(context)) {
GCMRegistrar.internalUnregister(context);
} else {
String[] senderIds = getSenderIds(context);
GCMRegistrar.internalRegister(context, senderIds);
}
}
} finally {
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If onMessage() needs to spawn a thread or do something else,
// it should use its own lock.
synchronized (LOCK) {
// sanity check for null as this is a public method
if (sWakeLock != null) {
sWakeLock.release();
} else {
// should never happen during normal workflow
mLogger.log(Log.ERROR, "Wakelock reference is null");
}
}
}
}
/**
* Called from the broadcast receiver.
* <p>
* Will process the received intent, call handleMessage(), registered(),
* etc. in background threads, with a wake lock, while keeping the service
* alive.
*/
static void runIntentInService(Context context, Intent intent,
String className) {
synchronized (LOCK) {
if (sWakeLock == null) {
// This is called from BroadcastReceiver, there is no init.
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WAKELOCK_KEY);
}
}
sWakeLock.acquire();
intent.setClassName(context, className);
context.startService(intent);
}
private void handleRegistration(final Context context, Intent intent) {
GCMRegistrar.cancelAppPendingIntent();
String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
String error = intent.getStringExtra(EXTRA_ERROR);
String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, "
+ "error = %s, unregistered = %s",
registrationId, error, unregistered);
// registration succeeded
if (registrationId != null) {
GCMRegistrar.resetBackoff(context);
GCMRegistrar.setRegistrationId(context, registrationId);
onRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null) {
// Remember we are unregistered
GCMRegistrar.resetBackoff(context);
String oldRegistrationId =
GCMRegistrar.clearRegistrationId(context);
onUnregistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
// Registration failed
if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
boolean retry = onRecoverableError(context, error);
if (retry) {
int backoffTimeMs = GCMRegistrar.getBackoff(context);
int nextAttempt = backoffTimeMs / 2 +
sRandom.nextInt(backoffTimeMs);
mLogger.log(Log.DEBUG,
"Scheduling registration retry, backoff = %d (%d)",
nextAttempt, backoffTimeMs);
Intent retryIntent =
new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
retryIntent.setPackage(context.getPackageName());
PendingIntent retryPendingIntent = PendingIntent
.getBroadcast(context, 0, retryIntent, 0);
AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + nextAttempt,
retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MAX_BACKOFF_MS) {
GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
}
} else {
mLogger.log(Log.VERBOSE, "Not retrying failed operation");
}
} else {
// Unrecoverable error, notify app
onError(context, error);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities for device registration.
* <p>
* <strong>Note:</strong> this class uses a private {@link SharedPreferences}
* object to keep track of the registration token.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMRegistrar {
/**
* Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)}
* flag until it is considered expired.
*/
// NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8
public static final long DEFAULT_ON_SERVER_LIFESPAN_MS =
1000 * 3600 * 24 * 7;
private static final String TAG = "GCMRegistrar";
private static final String BACKOFF_MS = "backoff_ms";
private static final String GSF_PACKAGE = "com.google.android.gsf";
private static final String PREFERENCES = "com.google.android.gcm";
private static final int DEFAULT_BACKOFF_MS = 3000;
private static final String PROPERTY_REG_ID = "regId";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String PROPERTY_ON_SERVER = "onServer";
private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
"onServerExpirationTime";
private static final String PROPERTY_ON_SERVER_LIFESPAN =
"onServerLifeSpan";
/**
* {@link GCMBroadcastReceiver} instance used to handle the retry intent.
*
* <p>
* This instance cannot be the same as the one defined in the manifest
* because it needs a different permission.
*/
// guarded by GCMRegistrar.class
private static GCMBroadcastReceiver sRetryReceiver;
// guarded by GCMRegistrar.class
private static Context sRetryReceiverContext;
// guarded by GCMRegistrar.class
private static String sRetryReceiverClassName;
// guarded by GCMRegistrar.class
private static PendingIntent sAppPendingIntent;
/**
* Checks if the device has the proper dependencies installed.
* <p>
* This method should be called when the application starts to verify that
* the device supports GCM.
*
* @param context application context.
* @throws UnsupportedOperationException if the device does not support GCM.
*/
public static void checkDevice(Context context) {
int version = Build.VERSION.SDK_INT;
if (version < 8) {
throw new UnsupportedOperationException("Device must be at least " +
"API Level 8 (instead of " + version + ")");
}
PackageManager packageManager = context.getPackageManager();
try {
packageManager.getPackageInfo(GSF_PACKAGE, 0);
} catch (NameNotFoundException e) {
throw new UnsupportedOperationException(
"Device does not have package " + GSF_PACKAGE);
}
}
/**
* Checks that the application manifest is properly configured.
* <p>
* A proper configuration means:
* <ol>
* <li>It creates a custom permission called
* {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
* <li>It defines at least one {@link BroadcastReceiver} with category
* {@code PACKAGE_NAME}.
* <li>The {@link BroadcastReceiver}(s) uses the
* {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS}
* permission.
* <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents
* ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* and
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
* </ol>
* ...where {@code PACKAGE_NAME} is the application package.
* <p>
* This method should be used during development time to verify that the
* manifest is properly set up, but it doesn't need to be called once the
* application is deployed to the users' devices.
*
* @param context application context.
* @throws IllegalStateException if any of the conditions above is not met.
*/
public static void checkManifest(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
String permissionName = packageName + ".permission.C2D_MESSAGE";
// check permission
try {
packageManager.getPermissionInfo(permissionName,
PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Application does not define permission " + permissionName);
}
// check receivers
PackageInfo receiversInfo;
try {
receiversInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Could not get receivers for package " + packageName);
}
ActivityInfo[] receivers = receiversInfo.receivers;
if (receivers == null || receivers.length == 0) {
throw new IllegalStateException("No receiver for package " +
packageName);
}
log(context, Log.VERBOSE, "number of receivers for %s: %d",
packageName, receivers.length);
Set<String> allowedReceivers = new HashSet<String>();
for (ActivityInfo receiver : receivers) {
if (GCMConstants.PERMISSION_GCM_INTENTS.equals(
receiver.permission)) {
allowedReceivers.add(receiver.name);
}
}
if (allowedReceivers.isEmpty()) {
throw new IllegalStateException("No receiver allowed to receive " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void checkReceiver(Context context,
Set<String> allowedReceivers, String action) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
Intent intent = new Intent(action);
intent.setPackage(packageName);
List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent,
PackageManager.GET_INTENT_FILTERS);
if (receivers.isEmpty()) {
throw new IllegalStateException("No receivers for action " +
action);
}
log(context, Log.VERBOSE, "Found %d receivers for action %s",
receivers.size(), action);
// make sure receivers match
for (ResolveInfo receiver : receivers) {
String name = receiver.activityInfo.name;
if (!allowedReceivers.contains(name)) {
throw new IllegalStateException("Receiver " + name +
" is not set with permission " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
}
}
/**
* Initiate messaging registration for the current application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with
* either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or
* {@link GCMConstants#EXTRA_ERROR}.
*
* @param context application context.
* @param senderIds Google Project ID of the accounts authorized to send
* messages to this application.
* @throws IllegalStateException if device does not have all GCM
* dependencies installed.
*/
public static void register(Context context, String... senderIds) {
GCMRegistrar.resetBackoff(context);
internalRegister(context, senderIds);
}
static void internalRegister(Context context, String... senderIds) {
String flatSenderIds = getFlatSenderIds(senderIds);
log(context, Log.VERBOSE, "Registering app for senders %s",
flatSenderIds);
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
context.startService(intent);
}
/**
* Unregister the application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an
* {@link GCMConstants#EXTRA_UNREGISTERED} extra.
*/
public static void unregister(Context context) {
GCMRegistrar.resetBackoff(context);
internalUnregister(context);
}
static void internalUnregister(Context context) {
log(context, Log.VERBOSE, "Unregistering app");
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
context.startService(intent);
}
static String getFlatSenderIds(String... senderIds) {
if (senderIds == null || senderIds.length == 0) {
throw new IllegalArgumentException("No senderIds");
}
StringBuilder builder = new StringBuilder(senderIds[0]);
for (int i = 1; i < senderIds.length; i++) {
builder.append(',').append(senderIds[i]);
}
return builder.toString();
}
/**
* Clear internal resources.
*
* <p>
* This method should be called by the main activity's {@code onDestroy()}
* method.
*/
public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
log(context, Log.VERBOSE, "Unregistering retry receiver");
sRetryReceiverContext.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
sRetryReceiverContext = null;
}
}
static synchronized void cancelAppPendingIntent() {
if (sAppPendingIntent != null) {
sAppPendingIntent.cancel();
sAppPendingIntent = null;
}
}
private synchronized static void setPackageNameExtra(Context context,
Intent intent) {
if (sAppPendingIntent == null) {
log(context, Log.VERBOSE,
"Creating pending intent to get package name");
sAppPendingIntent = PendingIntent.getBroadcast(context, 0,
new Intent(), 0);
}
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
sAppPendingIntent);
}
/**
* Lazy initializes the {@link GCMBroadcastReceiver} instance.
*/
static synchronized void setRetryBroadcastReceiver(Context context) {
if (sRetryReceiver == null) {
if (sRetryReceiverClassName == null) {
// should never happen
log(context, Log.ERROR,
"internal error: retry receiver class not set yet");
sRetryReceiver = new GCMBroadcastReceiver();
} else {
Class<?> clazz;
try {
clazz = Class.forName(sRetryReceiverClassName);
sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
} catch (Exception e) {
log(context, Log.ERROR, "Could not create instance of %s. "
+ "Using %s directly.", sRetryReceiverClassName,
GCMBroadcastReceiver.class.getName());
sRetryReceiver = new GCMBroadcastReceiver();
}
}
String category = context.getPackageName();
IntentFilter filter = new IntentFilter(
GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.addCategory(category);
log(context, Log.VERBOSE, "Registering retry receiver");
sRetryReceiverContext = context;
sRetryReceiverContext.registerReceiver(sRetryReceiver, filter);
}
}
/**
* Sets the name of the retry receiver class.
*/
static synchronized void setRetryReceiverClassName(Context context,
String className) {
log(context, Log.VERBOSE,
"Setting the name of retry receiver class to %s", className);
sRetryReceiverClassName = className;
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
log(context, Log.VERBOSE, "App version changed from %d to %d;"
+ "resetting registration id", oldVersion, newVersion);
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
/**
* Checks whether the application was successfully registered on GCM
* service.
*/
public static boolean isRegistered(Context context) {
return getRegistrationId(context).length() > 0;
}
/**
* Clears the registration id in the persistence store.
*
* <p>As a side-effect, it also expires the registeredOnServer property.
*
* @param context application's context.
* @return old registration id.
*/
static String clearRegistrationId(Context context) {
setRegisteredOnServer(context, null, 0);
return setRegistrationId(context, "");
}
/**
* Sets the registration id in the persistence store.
*
* @param context application's context.
* @param regId registration id
*/
static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
}
/**
* Sets whether the device was successfully registered in the server side.
*/
public static void setRegisteredOnServer(Context context, boolean flag) {
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
setRegisteredOnServer(context, flag, expirationTime);
}
private static void setRegisteredOnServer(Context context, Boolean flag,
long expirationTime) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
if (flag != null) {
editor.putBoolean(PROPERTY_ON_SERVER, flag);
log(context, Log.VERBOSE,
"Setting registeredOnServer flag as %b until %s",
flag, new Timestamp(expirationTime));
} else {
log(context, Log.VERBOSE,
"Setting registeredOnServer expiration to %s",
new Timestamp(expirationTime));
}
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side,
* as set by {@link #setRegisteredOnServer(Context, boolean)}.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, this flag has an expiration date, which
* is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed
* by {@link #setRegisterOnServerLifespan(Context, long)}).
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false);
log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered);
if (isRegistered) {
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
if (System.currentTimeMillis() > expirationTime) {
log(context, Log.VERBOSE, "flag expired on: %s",
new Timestamp(expirationTime));
return false;
}
}
return isRegistered;
}
/**
* Gets how long (in milliseconds) the {@link #isRegistered(Context)}
* property is valid.
*
* @return value set by {@link #setRegisteredOnServer(Context, boolean)} or
* {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set.
*/
public static long getRegisterOnServerLifespan(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN,
DEFAULT_ON_SERVER_LIFESPAN_MS);
return lifespan;
}
/**
* Sets how long (in milliseconds) the {@link #isRegistered(Context)}
* flag is valid.
*/
public static void setRegisterOnServerLifespan(Context context,
long lifespan) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan);
editor.commit();
}
/**
* Gets the application version.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
}
/**
* Resets the backoff counter.
* <p>
* This method should be called after a GCM call succeeds.
*
* @param context application's context.
*/
static void resetBackoff(Context context) {
log(context, Log.VERBOSE, "Resetting backoff");
setBackoff(context, DEFAULT_BACKOFF_MS);
}
/**
* Gets the current backoff counter.
*
* @param context application's context.
* @return current backoff counter, in milliseconds.
*/
static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
/**
* Sets the backoff counter.
* <p>
* This method should be called after a GCM call fails, passing an
* exponential value.
*
* @param context application's context.
* @param backoff new backoff counter, in milliseconds.
*/
static void setBackoff(Context context, int backoff) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putInt(BACKOFF_MS, backoff);
editor.commit();
}
private static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
/**
* Logs a message on logcat.
*
* @param context application's context.
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
private static void log(Context context, int priority, String template,
Object... args) {
if (Log.isLoggable(TAG, priority)) {
String message = String.format(template, args);
Log.println(priority, TAG, "[" + context.getPackageName() + "]: "
+ message);
}
}
private GCMRegistrar() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm;
/**
* Constants used by the GCM library.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMConstants {
/**
* Intent sent to GCM to register the application.
*/
public static final String INTENT_TO_GCM_REGISTRATION =
"com.google.android.c2dm.intent.REGISTER";
/**
* Intent sent to GCM to unregister the application.
*/
public static final String INTENT_TO_GCM_UNREGISTRATION =
"com.google.android.c2dm.intent.UNREGISTER";
/**
* Intent sent by GCM indicating with the result of a registration request.
*/
public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK =
"com.google.android.c2dm.intent.REGISTRATION";
/**
* Intent used by the GCM library to indicate that the registration call
* should be retried.
*/
public static final String INTENT_FROM_GCM_LIBRARY_RETRY =
"com.google.android.gcm.intent.RETRY";
/**
* Intent sent by GCM containing a message.
*/
public static final String INTENT_FROM_GCM_MESSAGE =
"com.google.android.c2dm.intent.RECEIVE";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to indicate which senders (Google API project ids) can send messages to
* the application.
*/
public static final String EXTRA_SENDER = "sender";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to get the application info.
*/
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate that the application has been unregistered.
*/
public static final String EXTRA_UNREGISTERED = "unregistered";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate an error when the registration fails.
* See constants starting with ERROR_ for possible values.
*/
public static final String EXTRA_ERROR = "error";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate the registration id when the registration succeeds.
*/
public static final String EXTRA_REGISTRATION_ID = "registration_id";
/**
* Type of message present in the
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* intent.
* This extra is only set for special messages sent from GCM, not for
* messages originated from the application.
*/
public static final String EXTRA_SPECIAL_MESSAGE = "message_type";
/**
* Special message indicating the server deleted the pending messages.
*/
public static final String VALUE_DELETED_MESSAGES = "deleted_messages";
/**
* Number of messages deleted by the server because the device was idle.
* Present only on messages of special type
* {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES}
*/
public static final String EXTRA_TOTAL_DELETED = "total_deleted";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* to indicate which sender (Google API project id) sent the message.
*/
public static final String EXTRA_FROM = "from";
/**
* Permission necessary to receive GCM intents.
*/
public static final String PERMISSION_GCM_INTENTS =
"com.google.android.c2dm.permission.SEND";
/**
* @see GCMBroadcastReceiver
*/
public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME =
".GCMIntentService";
/**
* The device can't read the response, or there was a 500/503 from the
* server that can be retried later. The application should use exponential
* back off and retry.
*/
public static final String ERROR_SERVICE_NOT_AVAILABLE =
"SERVICE_NOT_AVAILABLE";
/**
* There is no Google account on the phone. The application should ask the
* user to open the account manager and add a Google account.
*/
public static final String ERROR_ACCOUNT_MISSING =
"ACCOUNT_MISSING";
/**
* Bad password. The application should ask the user to enter his/her
* password, and let user retry manually later. Fix on the device side.
*/
public static final String ERROR_AUTHENTICATION_FAILED =
"AUTHENTICATION_FAILED";
/**
* The request sent by the phone does not contain the expected parameters.
* This phone doesn't currently support GCM.
*/
public static final String ERROR_INVALID_PARAMETERS =
"INVALID_PARAMETERS";
/**
* The sender account is not recognized. Fix on the device side.
*/
public static final String ERROR_INVALID_SENDER =
"INVALID_SENDER";
/**
* Incorrect phone registration with Google. This phone doesn't currently
* support GCM.
*/
public static final String ERROR_PHONE_REGISTRATION_ERROR =
"PHONE_REGISTRATION_ERROR";
private GCMConstants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm;
import android.util.Log;
/**
* Custom logger.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
class GCMLogger {
private final String mTag;
// can't use class name on TAG since size is limited to 23 chars
private final String mLogPrefix;
GCMLogger(String tag, String logPrefix) {
mTag = tag;
mLogPrefix = logPrefix;
}
/**
* Logs a message on logcat.
*
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
protected void log(int priority, String template, Object... args) {
if (Log.isLoggable(mTag, priority)) {
String message = String.format(template, args);
Log.println(priority, mTag, mLogPrefix + message);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm;
import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* {@link BroadcastReceiver} that receives GCM messages and delivers them to
* an application-specific {@link GCMBaseIntentService} subclass.
* <p>
* By default, the {@link GCMBaseIntentService} class belongs to the application
* main package and is named
* {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class,
* the {@link #getGCMIntentServiceClassName(Context)} must be overridden.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static boolean mReceiverSet = false;
private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver",
"[" + getClass().getName() + "]: ");
@Override
public final void onReceive(Context context, Intent intent) {
mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction());
// do a one-time check if app is using a custom GCMBroadcastReceiver
if (!mReceiverSet) {
mReceiverSet = true;
GCMRegistrar.setRetryReceiverClassName(context,
getClass().getName());
}
String className = getGCMIntentServiceClassName(context);
mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className);
// Delegates to the application-specific intent service.
GCMBaseIntentService.runIntentInService(context, intent, className);
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
/**
* Gets the class name of the intent service that will handle GCM messages.
*/
protected String getGCMIntentServiceClassName(Context context) {
return getDefaultIntentServiceClassName(context);
}
/**
* Gets the default class name of the intent service that will handle GCM
* messages.
*/
static final String getDefaultIntentServiceClassName(Context context) {
String className = context.getPackageName() +
DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gcm;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
private static final int MULTICAST_SIZE = 1000;
private Sender sender;
private static final Executor threadPool = Executors.newFixedThreadPool(5);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String registrationId = devices.get(0);
Message message = new Message.Builder().build();
Result result = sender.send(message, registrationId, 5);
status = "Sent message to one device: " + result;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == MULTICAST_SIZE || counter == total) {
asyncSend(partialDevices);
partialDevices.clear();
tasks++;
}
}
status = "Asynchronously sending " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
private void asyncSend(List<String> partialDevices) {
// make a copy
final List<String> devices = new ArrayList<String>(partialDevices);
threadPool.execute(new Runnable() {
public void run() {
Message message = new Message.Builder().build();
MulticastResult multicastResult;
try {
multicastResult = sender.send(message, devices, 5);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error posting messages", e);
return;
}
List<Result> results = multicastResult.getResults();
// analyze the results
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logger.fine("Succesfully sent message to device: " + regId +
"; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.info("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
logger.info("Unregistered device: " + regId);
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to " + regId + ": " + error);
}
}
}
}});
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is thread-safe but not persistent (it will lost the data when the
* app is restarted) - it is meant just as an example.
*/
public final class Datastore {
private static final List<String> regIds = new ArrayList<String>();
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
synchronized (regIds) {
regIds.add(regId);
}
}
/**
* Unregisters a device.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
synchronized (regIds) {
regIds.remove(regId);
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
synchronized (regIds) {
regIds.remove(oldId);
regIds.add(newId);
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
synchronized (regIds) {
return new ArrayList<String>(regIds);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from a
* {@value #PATH} file located in the classpath (typically under
* {@code WEB-INF/classes}).
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String PATH = "/api.key";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
logger.info("Reading " + PATH + " from resources (probably from " +
"WEB-INF/classes");
String key = getKey();
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key);
}
/**
* Gets the access key.
*/
protected String getKey() {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(PATH);
if (stream == null) {
throw new IllegalStateException("Could not find file " + PATH +
" on web resources)");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
String key = reader.readLine();
return key;
} catch (IOException e) {
throw new RuntimeException("Could not read file " + PATH, e);
} finally {
try {
reader.close();
} catch (IOException e) {
logger.log(Level.WARNING, "Exception closing " + PATH, e);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty()) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import com.google.android.gcm.GCMRegistrar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
/*
* Typically, an application registers automatically, so options
* below are disabled. Uncomment them if you want to manually
* register or unregister the device (you will also need to
* uncomment the equivalent options on options_menu.xml).
*/
/*
case R.id.options_register:
GCMRegistrar.register(this, SENDER_ID);
return true;
case R.id.options_unregister:
GCMRegistrar.unregister(this);
return true;
*/
case R.id.options_clear:
mDisplay.setText(null);
return true;
case R.id.options_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.app;
import android.content.Context;
import android.content.Intent;
/**
* Helper class providing methods and constants common to other classes in the
* app.
*/
public final class CommonUtilities {
/**
* Base URL of the Demo Server (such as http://my_host:8080/gcm-demo)
*/
static final String SERVER_URL = null;
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = null;
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
/**
* Intent used to display a message in the screen.
*/
static final String DISPLAY_MESSAGE_ACTION =
"com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered,
registrationId));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message. Extras: " + intent.getExtras());
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
Queue queue = QueueFactory.getQueue("gcm");
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String device = devices.get(0);
queue.add(withUrl("/send").param(
SendMessageServlet.PARAMETER_DEVICE, device));
status = "Single message queued for registration id " + device;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
String multicastKey = Datastore.createMulticast(partialDevices);
logger.fine("Queuing " + partialSize + " devices on multicast " +
multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/send")
.param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey)
.method(Method.POST);
queue.add(taskOptions);
partialDevices.clear();
tasks++;
}
}
status = "Queued tasks to send " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed 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 com.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that sends a message to a device.
* <p>
* This servlet is invoked by AppEngine's Push Queue mechanism.
*/
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount";
private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName";
private static final int MAX_RETRY = 3;
static final String PARAMETER_DEVICE = "device";
static final String PARAMETER_MULTICAST = "multicastKey";
private Sender sender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp) {
resp.setStatus(200);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getHeader(HEADER_QUEUE_NAME) == null) {
throw new IOException("Missing header " + HEADER_QUEUE_NAME);
}
String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT);
logger.fine("retry count: " + retryCountHeader);
if (retryCountHeader != null) {
int retryCount = Integer.parseInt(retryCountHeader);
if (retryCount > MAX_RETRY) {
logger.severe("Too many retries, dropping task");
taskDone(resp);
return;
}
}
String regId = req.getParameter(PARAMETER_DEVICE);
if (regId != null) {
sendSingleMessage(regId, resp);
return;
}
String multicastKey = req.getParameter(PARAMETER_MULTICAST);
if (multicastKey != null) {
sendMulticastMessage(multicastKey, resp);
return;
}
logger.severe("Invalid request!");
taskDone(resp);
return;
}
private Message createMessage() {
Message message = new Message.Builder().build();
return message;
}
private void sendSingleMessage(String regId, HttpServletResponse resp) {
logger.info("Sending message to device " + regId);
Message message = createMessage();
Result result;
try {
result = sender.sendNoRetry(message, regId);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
taskDone(resp);
return;
}
if (result == null) {
retryTask(resp);
return;
}
if (result.getMessageId() != null) {
logger.info("Succesfully sent message to device " + regId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.finest("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to device " + regId
+ ": " + error);
}
}
}
private void sendMulticastMessage(String multicastKey,
HttpServletResponse resp) {
// Recover registration ids from datastore
List<String> regIds = Datastore.getMulticast(multicastKey);
Message message = createMessage();
MulticastResult multicastResult;
try {
multicastResult = sender.sendNoRetry(message, regIds);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
multicastDone(resp, multicastKey);
return;
}
boolean allDone = true;
// check if any registration id must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = regIds.get(i);
Datastore.updateRegistration(regId, canonicalRegId);
}
}
}
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retriableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = regIds.get(i);
logger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
}
if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retriableRegIds.add(regId);
}
}
}
if (!retriableRegIds.isEmpty()) {
// update task
Datastore.updateMulticast(multicastKey, retriableRegIds);
allDone = false;
retryTask(resp);
}
}
if (allDone) {
multicastDone(resp, multicastKey);
} else {
retryTask(resp);
}
}
private void multicastDone(HttpServletResponse resp, String encodedKey) {
Datastore.deleteMulticast(encodedKey);
taskDone(resp);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.