code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
package com.zyeeda.framework.knowledge.internal;
import org.drools.KnowledgeBase;
import org.drools.audit.WorkingMemoryLogger;
import org.drools.audit.event.LogEvent;
import org.drools.audit.event.RuleFlowLogEvent;
import org.drools.audit.event.RuleFlowNodeLogEvent;
import org.drools.definition.process.Node;
import org.drools.definition.process.Process;
import org.drools.definition.process.WorkflowProcess;
import org.drools.event.KnowledgeRuntimeEventManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.entities.ActionHistory;
import com.zyeeda.framework.entities.ProcessHistory;
import com.zyeeda.framework.managers.ActionHistoryManager;
import com.zyeeda.framework.managers.ProcessHistoryManager;
import com.zyeeda.framework.managers.internal.DefaultActionHistoryManager;
import com.zyeeda.framework.managers.internal.DefaultProcessHistoryManager;
import com.zyeeda.framework.persistence.PersistenceService;
public class HistoryLogger extends WorkingMemoryLogger {
private final static Logger logger = LoggerFactory.getLogger(HistoryLogger.class);
private PersistenceService persistenceSvc;
private KnowledgeBase kbase;
private ProcessHistoryManager pHisMgr;
private ActionHistoryManager aHisMgr;
/*
public HistoryLogger(WorkingMemory workingMemory, PersistenceService persistenceSvc, KnowledgeService knowledgeSvc) {
super(workingMemory);
this.persistenceSvc = persistenceSvc;
this.knowledgeSvc = knowledgeSvc;
this.init();
}*/
public HistoryLogger(KnowledgeRuntimeEventManager session, PersistenceService persistenceSvc, KnowledgeBase kbase) {
super(session);
this.persistenceSvc = persistenceSvc;
this.kbase = kbase;
this.init();
}
private void init() {
this.pHisMgr = new DefaultProcessHistoryManager(this.persistenceSvc);
this.aHisMgr = new DefaultActionHistoryManager(this.persistenceSvc);
}
@Override
public void logEventCreated(LogEvent logEvent) {
switch (logEvent.getType()) {
case LogEvent.BEFORE_RULEFLOW_CREATED: {
RuleFlowLogEvent event = (RuleFlowLogEvent) logEvent;
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append("BEFORE RULEFLOW CREATED\n");
sb.append(String.format("\tprocess id = %s\n", event.getProcessId()));
sb.append(String.format("\tprocess name = %s\n", event.getProcessName()));
sb.append(String.format("\tprocess instance id = %s", event.getProcessInstanceId()));
logger.debug(sb.toString());
}
ProcessHistory history = new ProcessHistory();
history.setProcessId(event.getProcessId());
history.setName(event.getProcessName());
history.setProcessInstanceId(event.getProcessInstanceId());
this.pHisMgr.persist(history);
break;
}
case LogEvent.AFTER_RULEFLOW_COMPLETED: {
RuleFlowLogEvent event = (RuleFlowLogEvent) logEvent;
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append("AFTER RULEFLOW COMPLETED\n");
sb.append(String.format("\tprocess id = %s\n", event.getProcessId()));
sb.append(String.format("\tprocess name = %s\n", event.getProcessName()));
sb.append(String.format("\tprocess instance id = %s", event.getProcessInstanceId()));
logger.debug(sb.toString());
}
ProcessHistory history = this.pHisMgr.findByProcessInstanceId(event.getProcessInstanceId());
if (history == null) {
logger.warn("Cannot find process history by process instance id {}.", event.getProcessInstanceId());
} else {
history.setEnded(true);
this.pHisMgr.save(history);
}
break;
}
case LogEvent.BEFORE_RULEFLOW_NODE_TRIGGERED: {
RuleFlowNodeLogEvent event = (RuleFlowNodeLogEvent) logEvent;
String nodeType = null;
Process process = this.kbase.getProcess(event.getProcessId());
if (process instanceof WorkflowProcess) {
WorkflowProcess workflow = (WorkflowProcess) process;
try {
Node node = workflow.getNode(Long.parseLong(event.getNodeId()));
nodeType = node.getClass().getSimpleName();
} catch (NumberFormatException e) {
logger.warn("node is is not a long value", e);
}
} else {
logger.warn("process {} is not of WorkflowProcess type.", event.getProcessId());
}
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append("BEFORE RULEFLOW NODE TRIGGERED\n");
sb.append(String.format("\tprocess id = %s\n", event.getProcessId()));
sb.append(String.format("\tprocess name = %s\n", event.getProcessName()));
sb.append(String.format("\tprocess instance id = %s\n", event.getProcessInstanceId()));
sb.append(String.format("\tnode id = %s\n", event.getNodeId()));
sb.append(String.format("\tnode name = %s\n", event.getNodeName()));
sb.append(String.format("\tnode istance id = %s\n", event.getNodeInstanceId()));
sb.append(String.format("\tnode type = %s", nodeType));
logger.debug(sb.toString());
}
ProcessHistory proHist = this.pHisMgr.findByProcessInstanceId(event.getProcessInstanceId());
if (proHist == null) {
logger.warn("Cannot find process history by process instance id {}.", event.getProcessInstanceId());
} else {
proHist.setCurrentState(event.getNodeName());
this.pHisMgr.save(proHist);
}
ActionHistory actHist = new ActionHistory();
actHist.setProcessId(event.getProcessId());
actHist.setProcessName(event.getProcessName());
actHist.setProcessInstanceId(event.getProcessInstanceId());
actHist.setNodeId(event.getNodeId());
actHist.setNodeInstanceId(event.getNodeInstanceId());
actHist.setName(event.getNodeName());
actHist.setNodeType(nodeType);
this.aHisMgr.persist(actHist);
break;
}
case LogEvent.BEFORE_RULEFLOW_NODE_EXITED: {
RuleFlowNodeLogEvent event = (RuleFlowNodeLogEvent) logEvent;
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append("BEFORE RULEFLOW NODE EXITED\n");
sb.append(String.format("\tprocess id = %s\n", event.getProcessId()));
sb.append(String.format("\tprocess name = %s\n", event.getProcessName()));
sb.append(String.format("\tprocess instance id = %s\n", event.getProcessInstanceId()));
sb.append(String.format("\tnode id = %s\n", event.getNodeId()));
sb.append(String.format("\tnode name = %s\n", event.getNodeName()));
sb.append(String.format("\tnode istance id = %s", event.getNodeInstanceId()));
logger.debug(sb.toString());
}
ProcessHistory proHist = this.pHisMgr.findByProcessInstanceId(event.getProcessInstanceId());
if (proHist == null) {
logger.warn("Cannot find process history by process instance id {}.", event.getProcessInstanceId());
} else {
this.pHisMgr.save(proHist);
}
ActionHistory actHist = aHisMgr.findAlive(event.getProcessInstanceId(), event.getNodeInstanceId());
if (actHist == null) {
logger.warn("Cannot find action history by process instance id {} and node instance id {}.",
event.getProcessInstanceId(), event.getNodeInstanceId());
} else {
actHist.setAlive(false);
this.aHisMgr.save(actHist);
}
break;
}
default:
// ignore
}
this.persistenceSvc.getCurrentSession().flush();
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/knowledge/internal/HistoryLogger.java | Java | asf20 | 7,535 |
package com.zyeeda.framework.knowledge.internal;
import java.io.File;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.configuration.Configuration;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.SystemEventListenerFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.persistence.jpa.JPAKnowledgeService;
import org.drools.process.workitem.wsht.WSHumanTaskHandler;
import org.drools.runtime.Environment;
import org.drools.runtime.EnvironmentName;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.task.service.TaskServer;
import org.drools.task.service.TaskService;
import org.drools.task.service.mina.MinaTaskServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.knowledge.KnowledgeService;
import com.zyeeda.framework.knowledge.StatefulSessionCommand;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.persistence.annotations.DroolsTask;
import com.zyeeda.framework.service.AbstractService;
import com.zyeeda.framework.transaction.TransactionService;
@ServiceId("drools-knowledge-service")
@Marker(Primary.class)
public class DroolsKnowledgeServiceProvider extends AbstractService implements KnowledgeService {
private static final Logger logger = LoggerFactory.getLogger(DroolsKnowledgeServiceProvider.class);
private static final String AUDIT_LOG_FILE_PATH = "auditLogFilePath";
private static final String AUDIT_LOG_FLUSH_INTERVAL = "auditLogFlushInterval";
private static final String TASK_SERVER_PORT = "taskServerPort";
private static final String DEFAUL_AUDIT_LOG_FILE_PATH = "/WEB-INF/logs/drools_audit";
private static final int DEFAULT_AUDIT_LOG_FLUSH_INTERVAL = 60 * 60 * 1000;
private static final int DEFAULT_TASK_SERVER_PORT = -1;
private final ConfigurationService configSvc;
private final PersistenceService defaultPersistenceSvc;
private final PersistenceService droolsTaskPersistenceSvc;
private final TransactionService txSvc;
private KnowledgeBase kbase;
private TaskService taskService;
private TaskServer taskServer;
private String auditLogFilePath;
private int auditLogFlushInterval;
private int taskServerPort;
public DroolsKnowledgeServiceProvider(
@Primary ConfigurationService configSvc,
@DroolsTask PersistenceService droolsTaskPersistenceSvc,
@Primary PersistenceService defaultPersistenceSvc,
@Primary TransactionService txSvc,
RegistryShutdownHub shutdownHub) throws Exception {
super(shutdownHub);
this.configSvc = configSvc;
this.defaultPersistenceSvc = defaultPersistenceSvc;
this.droolsTaskPersistenceSvc = droolsTaskPersistenceSvc;
this.txSvc = txSvc;
Configuration config = this.getConfiguration(configSvc);
this.init(config);
}
private void init(Configuration config) throws Exception {
this.auditLogFilePath = config.getString(AUDIT_LOG_FILE_PATH, DEFAUL_AUDIT_LOG_FILE_PATH);
this.auditLogFlushInterval = config.getInt(AUDIT_LOG_FLUSH_INTERVAL, DEFAULT_AUDIT_LOG_FLUSH_INTERVAL);
this.taskServerPort = config.getInt(TASK_SERVER_PORT, DEFAULT_TASK_SERVER_PORT);
if (logger.isDebugEnabled()) {
logger.debug("{} = {}", AUDIT_LOG_FILE_PATH, this.auditLogFilePath);
logger.debug("{} = {}", AUDIT_LOG_FLUSH_INTERVAL, this.auditLogFlushInterval);
logger.debug("{} = {}", TASK_SERVER_PORT, this.taskServerPort);
}
File auditLogFile = new File(this.configSvc.getApplicationRoot(), this.auditLogFilePath);
if (!auditLogFile.exists()) {
File logDir = auditLogFile.getParentFile();
if (!logDir.exists()) {
logger.info("Audit log file container {} does not exist, make dir first.", logDir);
logDir.mkdirs();
} else {
if (!logDir.isDirectory()) {
logger.warn("Audit log file container {} should be a directory but a file found instead, delete the file then make dir.", logDir);
logDir.delete();
logDir.mkdirs();
}
}
}
}
@Override
public void start() throws Exception {
// add knowledge changeset
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("drools-changeset.xml"), ResourceType.CHANGE_SET);
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error: errors) {
logger.error(error.toString());
}
throw new IllegalArgumentException("Could not parse knowledge changeset.");
}
this.kbase = kbuilder.newKnowledgeBase();
this.kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
// start task server
EntityManagerFactory emf = this.droolsTaskPersistenceSvc.getSessionFactory();
this.taskService = new TaskService(emf, SystemEventListenerFactory.getSystemEventListener());
if (this.taskServerPort < 0) {
this.taskServer = new MinaTaskServer(this.taskService);
} else {
this.taskServer = new MinaTaskServer(this.taskService, this.taskServerPort);
}
Thread taskServerThread = new Thread(this.taskServer, "DroolsTaskServer");
taskServerThread.start();
}
@Override
public void stop() throws Exception {
this.taskServer.stop();
// Because MinaTaskServer checks running status every 100ms,
// so we wait here for 150ms to ensure that the task server thread
// has been completely stopped.
Thread.sleep(150);
}
@Override
public KnowledgeBase getKnowledgeBase() {
return this.kbase;
}
@Override
public TaskService getTaskService() {
return this.taskService;
}
@Override
public <T> T execute(StatefulSessionCommand<T> command) throws Exception {
StatefulKnowledgeSession ksession = null;
KnowledgeRuntimeLogger rtLogger = null;
WSHumanTaskHandler taskHandler = null;
try {
Environment env = KnowledgeBaseFactory.newEnvironment();
env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, this.defaultPersistenceSvc.getSessionFactory());
env.set(EnvironmentName.APP_SCOPED_ENTITY_MANAGER, this.defaultPersistenceSvc.getCurrentSession());
env.set(EnvironmentName.TRANSACTION_MANAGER, this.txSvc.getTransactionManager());
env.set(EnvironmentName.TRANSACTION, this.txSvc.getTransaction());
env.set(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY, this.txSvc.getTransactionSynchronizationRegistry());
if (command.getSessionId() > 0) {
ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(
command.getSessionId(), this.kbase, null, env);
} else {
ksession = JPAKnowledgeService.newStatefulKnowledgeSession(this.kbase, null, env);
}
taskHandler = new WSHumanTaskHandler();
if (this.taskServerPort > 0) {
taskHandler.setConnection("localhost", this.taskServerPort);
}
ksession.getWorkItemManager().registerWorkItemHandler("Human Task", taskHandler);
//EmailWorkItemHandler emailHandler = new EmailWorkItemHandler();
//emailHandler.setConnection("mail.tangrui.net", "21", "webmaster@tangrui.net", "P@$ther0");
//ksession.getWorkItemManager().registerWorkItemHandler("Email", emailHandler);
rtLogger = KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(ksession, this.configSvc.mapPath(this.auditLogFilePath), this.auditLogFlushInterval);
//new JPAWorkingMemoryDbLogger(ksession);
new HistoryLogger(ksession, this.defaultPersistenceSvc, this.kbase);
T result = command.execute(ksession);
return result;
} catch (Throwable t) {
logger.error("Execute command failed.", t);
throw new Exception(t);
} finally {
if (rtLogger != null) {
try {
rtLogger.close();
} catch (Throwable t) {
logger.error("Close knowledge runtime logger failed.", t);
}
}
if (taskHandler != null) {
taskHandler.dispose();
}
if (ksession != null) {
ksession.dispose();
}
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/knowledge/internal/DroolsKnowledgeServiceProvider.java | Java | asf20 | 8,633 |
package com.zyeeda.framework.knowledge.internal;
import org.drools.runtime.process.WorkItem;
import org.drools.runtime.process.WorkItemHandler;
import org.drools.runtime.process.WorkItemManager;
public class EmailWorkItemHandler implements WorkItemHandler {
@Override
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
//String from = (String) workItem.getParameter("From");
}
@Override
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
// TODO Auto-generated method stub
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/knowledge/internal/EmailWorkItemHandler.java | Java | asf20 | 562 |
package com.zyeeda.framework.knowledge;
public abstract class AbstractStatefulSessionCommand<T> implements StatefulSessionCommand<T> {
private int sessionId = -1;
public void setSessionId(int sessionId) {
this.sessionId = sessionId;
}
public int getSessionId() {
return this.sessionId;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/knowledge/AbstractStatefulSessionCommand.java | Java | asf20 | 306 |
package com.zyeeda.framework.scripting;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import javax.script.ScriptException;
import com.zyeeda.framework.service.Service;
public interface ScriptingService extends Service {
public Object eval(File scriptFile, Map<String, Object> args) throws FileNotFoundException, ScriptException;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/scripting/ScriptingService.java | Java | asf20 | 374 |
package com.zyeeda.framework.scripting.internal;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.apache.commons.configuration.Configuration;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.scripting.ScriptingService;
import com.zyeeda.framework.service.AbstractService;
@ServiceId("jsr223-scripting-service")
@Marker(Primary.class)
public class Jsr223ScriptingServiceProvider extends AbstractService implements ScriptingService {
private static final Logger logger = LoggerFactory.getLogger(Jsr223ScriptingServiceProvider.class);
private static final String SCRIPT_REPOSITORY_ROOT = "scriptRepositoryRoot";
private static final String DEFAULT_SCRIPT_REPOSITORY_ROOT = "WEB-INF/scripts";
private static final String DEFAULT_SCRIPT_ENGINE_NAME = "groovy";
private final ConfigurationService configSvc;
private File repoRoot;
private ScriptEngineManager manager;
public Jsr223ScriptingServiceProvider(ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) throws Exception {
super(shutdownHub);
this.configSvc = configSvc;
Configuration config = this.getConfiguration(this.configSvc);
this.init(config);
}
private void init(Configuration config) throws Exception {
String repoRoot = config.getString(SCRIPT_REPOSITORY_ROOT, DEFAULT_SCRIPT_REPOSITORY_ROOT);
logger.debug("script repository root = {}", repoRoot);
this.repoRoot = new File(this.configSvc.getApplicationRoot(), repoRoot);
if (!this.repoRoot.exists()) {
throw new FileNotFoundException(this.repoRoot.toString());
}
}
@Override
public void start() {
this.manager = new ScriptEngineManager(this.getClass().getClassLoader());
}
@Override
public Object eval(File scriptFile, Map<String, Object> args) throws FileNotFoundException, ScriptException {
ScriptEngine engine = manager.getEngineByName(DEFAULT_SCRIPT_ENGINE_NAME);
Bindings bindings = engine.createBindings();
bindings.putAll(args);
FileReader reader = null;
try {
reader = new FileReader(scriptFile);
return engine.eval(reader, bindings);
} finally {
if (reader != null) {
try {
reader.close();
} catch (Throwable t) {
logger.error("Close script file reader failed.", t);
}
}
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/scripting/internal/Jsr223ScriptingServiceProvider.java | Java | asf20 | 2,864 |
package com.zyeeda.framework.openid.provider.internal;
import org.apache.commons.configuration.Configuration;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.openid4java.association.AssociationException;
import org.openid4java.message.Message;
import org.openid4java.message.MessageException;
import org.openid4java.message.ParameterList;
import org.openid4java.server.InMemoryServerAssociationStore;
import org.openid4java.server.ServerException;
import org.openid4java.server.ServerManager;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.openid.provider.OpenIdProviderService;
import com.zyeeda.framework.service.AbstractService;
@ServiceId("default-openid-provider-service")
@Marker(Primary.class)
public class DefaultOpenIdProviderService extends AbstractService implements OpenIdProviderService {
private final static String ENDPOINT_URL_KEY = "endpointUrl";
private final static String DEFAULT_ENDPOINT_URL = "/provider/endpoint";
private final static String DEFAULT_ENDPOINT_COMPLETE_URL = "/provider/endpoint/complete";
private String endpointUrl;
private ServerManager serverManager;
public DefaultOpenIdProviderService(
@Primary ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) {
super(shutdownHub);
Configuration config = this.getConfiguration(configSvc);
this.init(config);
}
private void init(Configuration config) {
this.endpointUrl = config.getString(ENDPOINT_URL_KEY, DEFAULT_ENDPOINT_URL);
this.serverManager = new ServerManager();
this.serverManager.setOPEndpointUrl(this.endpointUrl);
this.serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
this.serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
this.serverManager.getRealmVerifier().setEnforceRpId(false);
}
@Override
public Message associateRequest(ParameterList params) {
Message message = this.serverManager.associationResponse(params);
return message;
}
@Override
public Message verifyRequest(ParameterList params) {
Message message = this.serverManager.verify(params);
return message;
}
@Override
public Message authResponse(ParameterList params, String userSelectedId,
String userSelectedClaimedId, boolean authenticatedAndApproved, String opEndpointUrl) throws MessageException, ServerException, AssociationException {
Message message = this.serverManager.authResponse(params, userSelectedId,
userSelectedClaimedId, authenticatedAndApproved, opEndpointUrl, true);
/*if (message instanceof AuthSuccess) {
AuthSuccess authSuccess = (AuthSuccess) message;
AuthRequest authReq = AuthRequest.createAuthRequest(params, this.serverManager.getRealmVerifier());
if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
MessageExtension ext = authReq.getExtension(AxMessage.OPENID_NS_AX);
if (ext instanceof FetchRequest) {
FetchRequest fetchReq = (FetchRequest)ext;
Map<?, ?> required = fetchReq.getAttributes(true);
//Map<?, ?> optional = fetchReq.getAttributes(false);
Map<String, String> userData = new HashMap<String, String>(10);
if (required.containsKey("id")) {
userData.put("id", userSelectedClaimedId);
}
FetchResponse fetchResp = FetchResponse.createFetchResponse(fetchReq, userData);
authSuccess.addExtension(fetchResp);
}
}
// TODO other extensions support
this.serverManager.sign(authSuccess);
}*/
return message;
}
@Override
public String getEndpointUrl() {
return this.endpointUrl;
}
@Override
public String getEndpointCompleteUrl() {
return DEFAULT_ENDPOINT_COMPLETE_URL;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/provider/internal/DefaultOpenIdProviderService.java | Java | asf20 | 3,973 |
package com.zyeeda.framework.openid.provider.shiro;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.tapestry5.ioc.Registry;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.DirectError;
import org.openid4java.message.Message;
import org.openid4java.message.ParameterList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.openid.provider.OpenIdProviderService;
import com.zyeeda.framework.utils.IocUtils;
public class OpenIdProviderEndpointFilter extends PathMatchingFilter {
private static final Logger logger = LoggerFactory.getLogger(OpenIdProviderEndpointFilter.class);
private final static String OPENID_NAMESPACE = "http://specs.openid.net/auth/2.0";
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
Registry registry = IocUtils.getRegistry(this.getServletContext());
OpenIdProviderService opSvc = registry.getService(OpenIdProviderService.class);
ParameterList params = null;
if (this.pathsMatch(opSvc.getEndpointCompleteUrl(), httpReq)) {
logger.debug("OpenID provider endpoint complete request detected!");
params = (ParameterList) SecurityUtils.getSubject().getSession().getAttribute("params");
if (params == null) {
this.outputInvalidAuthRequestMessage(httpRes);
return false;
}
} else {
logger.debug("OpenID provider endpoint direct request detected!");
params = new ParameterList(httpReq.getParameterMap());
}
if (!params.hasParameter("openid.ns") || !params.hasParameter("openid.mode")) {
this.outputInvalidAuthRequestMessage(httpRes);
return false;
}
String ns = params.getParameterValue("openid.ns");
if (!OPENID_NAMESPACE.equals(ns)) {
this.outputInvalidAuthRequestMessage(httpRes);
return false;
}
String mode = params.getParameterValue("openid.mode");
logger.debug("OpenID mode = {}", mode);
if ("associate".equals(mode)) {
logger.debug("OpenID request mode [associate] detected!");
Message message = opSvc.associateRequest(params);
this.outputMessage(message, httpRes);
return false;
}
if ("check_authentication".equals(mode)) {
logger.debug("OpenID request mode [check_authentication] detected!");
Message message = opSvc.verifyRequest(params);
this.outputMessage(message, httpRes);
return false;
}
if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
logger.debug("OpenID request mode [checkid_immediate] or [checkid_setup] detected!");
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
logger.debug("User is authenticated.");
SecurityUtils.getSubject().getSession().removeAttribute("params");
String urlPrefix = httpReq.getScheme() + "://" + httpReq.getServerName() + ":" + httpReq.getServerPort() + httpReq.getContextPath();
String userSelectedId = (subject.getPrincipals().iterator().next()).toString();
userSelectedId = urlPrefix + "/provider/user.jsp?id=" + userSelectedId;
String userSelectedClaimedId = userSelectedId;
String fullEndpointUrl = urlPrefix + opSvc.getEndpointUrl();
if (logger.isDebugEnabled()) {
logger.debug("user selected id = {}", userSelectedId);
logger.debug("user selected claimed id = {}", userSelectedClaimedId);
logger.debug("full endpoint url = {}", fullEndpointUrl);
}
Message message = opSvc.authResponse(params, userSelectedId, userSelectedClaimedId, subject.isAuthenticated(), fullEndpointUrl);
if (message instanceof AuthSuccess) {
httpRes.sendRedirect(message.getDestinationUrl(true));
return false;
}
// TODO
httpRes.sendRedirect(message.getDestinationUrl(true));
return false;
}
SecurityUtils.getSubject().getSession().setAttribute("params", params);
return true;
}
logger.debug("Unknown OpenID request mode [{}]", mode);
this.outputInvalidAuthRequestMessage(httpRes);
return false;
}
private void outputMessage(Message message, HttpServletResponse httpRes) throws IOException {
String messageText = message.keyValueFormEncoding();
httpRes.getWriter().print(messageText);
}
private void output400Message(Message message, HttpServletResponse httpRes) throws IOException {
httpRes.setStatus(HttpServletResponse.SC_BAD_REQUEST);
this.outputMessage(message, httpRes);
}
private void outputInvalidAuthRequestMessage(HttpServletResponse httpRes) throws IOException {
Message message = DirectError.createDirectError("Invalid OpenID auth request!");
this.output400Message(message, httpRes);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/provider/shiro/OpenIdProviderEndpointFilter.java | Java | asf20 | 5,639 |
package com.zyeeda.framework.openid.provider.shiro;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.tapestry5.ioc.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.openid.provider.OpenIdProviderService;
import com.zyeeda.framework.utils.IocUtils;
public class OpenIdProviderAuthcFilter extends FormAuthenticationFilter {
private final static Logger logger = LoggerFactory.getLogger(OpenIdProviderAuthcFilter.class);
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
logger.debug("on access denied");
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
// 访问登录页面
if (this.isLoginRequest(httpReq, httpRes)) {
logger.debug("Sign in request detected!");
// 提交数据到登录页面
if (this.isLoginSubmission(httpReq, httpRes)) {
logger.debug("Sign in submission request detected!");
return this.executeLogin(httpReq, httpRes);
}
// 直接访问登录页面
logger.debug("Sign in view request detected!");
return true;
}
// 访问其它页面,转发到登录页面
logger.debug("Redirect to sign in page {}!", this.getLoginUrl());
httpRes.sendRedirect(this.getLoginUrl());
return false;
}
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
ServletRequest request, ServletResponse response) throws Exception {
logger.debug("subject.isAuthenticated = {}, subject.isRemembered = {}",
subject.isAuthenticated(), subject.isRemembered());
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
Registry registry = IocUtils.getRegistry(this.getServletContext());
OpenIdProviderService opSvc = registry.getService(OpenIdProviderService.class);
if (this.isOpenIdRequest(httpReq)) {
httpRes.sendRedirect(this.getServletContext().getContextPath() + opSvc.getEndpointCompleteUrl());
return false;
}
return true;
}
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
ServletResponse response) {
logger.error("login failure", e);
super.onLoginFailure(token, e, request, response);
return true;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
boolean result = super.isAccessAllowed(request, response, mappedValue);
logger.debug("is access allowed = {}", result);
return result;
}
private boolean isOpenIdRequest(HttpServletRequest httpReq) {
return SecurityUtils.getSubject().getSession().getAttribute("params") != null;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/provider/shiro/OpenIdProviderAuthcFilter.java | Java | asf20 | 3,296 |
package com.zyeeda.framework.openid.provider;
import org.openid4java.association.AssociationException;
import org.openid4java.message.Message;
import org.openid4java.message.MessageException;
import org.openid4java.message.ParameterList;
import org.openid4java.server.ServerException;
import com.zyeeda.framework.service.Service;
public interface OpenIdProviderService extends Service {
public Message associateRequest(ParameterList params);
public Message verifyRequest(ParameterList params);
public Message authResponse(ParameterList params, String userSelectedId,
String userSelectedClaimedId, boolean authenticatedAndApproved, String opEndpointUrl) throws MessageException, ServerException, AssociationException;
public String getEndpointUrl();
public String getEndpointCompleteUrl();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/provider/OpenIdProviderService.java | Java | asf20 | 837 |
package com.zyeeda.framework.openid.consumer;
import org.openid4java.message.MessageException;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
public interface AxExtensionConsumer {
public FetchRequest prepareFetchRequest() throws MessageException;
public void processFetchResponse(FetchResponse fetchResp);
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/AxExtensionConsumer.java | Java | asf20 | 381 |
package com.zyeeda.framework.openid.consumer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openid4java.OpenIDException;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
public interface OpenIdConsumer {
public abstract AuthRequest authRequest(String userSuppliedId,
HttpServletRequest httpReq, HttpServletResponse httpRes)
throws OpenIDException;
public abstract Identifier verifyResponse(HttpServletRequest httpReq)
throws OpenIDException;
public abstract void setReturnToUrl(String returnToUrl);
public abstract String getReturnToUrl();
public abstract String getRealm();
public abstract void setRealm(String realm);
public abstract void storeDiscoveryInfo(HttpServletRequest httpReq,
DiscoveryInformation discovered);
public abstract DiscoveryInformation retrieveDiscoveryInfo(
HttpServletRequest httpReq);
//public AxExtensionConsumer getAxExtensionConsumer();
//public void setAxExtensionConsumer(AxExtensionConsumer axExtConsumer);
} | zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/OpenIdConsumer.java | Java | asf20 | 1,169 |
package com.zyeeda.framework.openid.consumer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openid4java.OpenIDException;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import com.zyeeda.framework.service.Service;
public interface OpenIdConsumerService extends Service {
public AuthRequest authRequest(HttpServletRequest request, HttpServletResponse response) throws OpenIDException;
public Identifier verifyResponse(HttpServletRequest request) throws OpenIDException;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/OpenIdConsumerService.java | Java | asf20 | 599 |
package com.zyeeda.framework.openid.consumer.internal;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.discovery.DiscoveryInformation;
public class ShiroSessionOpenIdConsumer extends HttpSessionOpenIdConsumer {
public ShiroSessionOpenIdConsumer() throws ConsumerException {
super();
}
@Override
public void storeDiscoveryInfo(HttpServletRequest httpReq, DiscoveryInformation discovered) {
SecurityUtils.getSubject().getSession().setAttribute(OPENID_DISCOVERED_KEY, discovered);
}
@Override
public DiscoveryInformation retrieveDiscoveryInfo(HttpServletRequest httpReq) {
return (DiscoveryInformation) SecurityUtils.getSubject().getSession().getAttribute(OPENID_DISCOVERED_KEY);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/internal/ShiroSessionOpenIdConsumer.java | Java | asf20 | 842 |
package com.zyeeda.framework.openid.consumer.internal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.InMemoryConsumerAssociationStore;
import org.openid4java.consumer.InMemoryNonceVerifier;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.openid.consumer.OpenIdConsumer;
public class HttpSessionOpenIdConsumer implements OpenIdConsumer {
private final static Logger logger = LoggerFactory.getLogger(HttpSessionOpenIdConsumer.class);
protected final static String OPENID_DISCOVERED_KEY = "openid.discovered";
private String returnToUrl;
private String realm;
private ConsumerManager manager;
public HttpSessionOpenIdConsumer() throws ConsumerException {
this.manager = new ConsumerManager();
this.manager.setConnectTimeout(300000);
this.manager.setSocketTimeout(300000);
this.manager.setAssociations(new InMemoryConsumerAssociationStore());
this.manager.setNonceVerifier(new InMemoryNonceVerifier(60000));
this.manager.getRealmVerifier().setEnforceRpId(false);
}
@Override
public AuthRequest authRequest(String userSuppliedId,
HttpServletRequest httpReq,
HttpServletResponse httpRes) throws OpenIDException {
logger.info("user supplied id = {}", userSuppliedId);
List<?> discos = this.manager.discover(userSuppliedId);
DiscoveryInformation discovered = this.manager.associate(discos);
this.storeDiscoveryInfo(httpReq, discovered);
AuthRequest authReq = this.manager.authenticate(discovered, this.returnToUrl);
authReq.setRealm(this.realm);
return authReq;
}
@Override
public Identifier verifyResponse(HttpServletRequest httpReq) throws OpenIDException {
ParameterList response = new ParameterList(httpReq.getParameterMap());
DiscoveryInformation discovered = this.retrieveDiscoveryInfo(httpReq);
StringBuilder receivingURL = new StringBuilder(this.returnToUrl);
String queryString = httpReq.getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(httpReq.getQueryString());
}
VerificationResult verification = this.manager.verify(receivingURL.toString(), response, discovered);
Identifier verified = verification.getVerifiedId();
if (verified == null) {
throw new OpenIDException("Cannot verify OpenID auth response.");
}
/*AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX) && this.axExtConsumer != null) {
MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX);
if (ext instanceof FetchResponse) {
FetchResponse fetchResp = (FetchResponse) ext;
this.axExtConsumer.processFetchResponse(fetchResp);
}
}*/
// TODO some more extension
return verified;
}
@Override
public void setReturnToUrl(String returnToUrl) {
this.returnToUrl = returnToUrl;
}
@Override
public String getReturnToUrl() {
return this.returnToUrl;
}
@Override
public String getRealm() {
return realm;
}
@Override
public void setRealm(String realm) {
this.realm = realm;
}
@Override
public void storeDiscoveryInfo(HttpServletRequest httpReq, DiscoveryInformation discovered) {
httpReq.getSession().setAttribute(OPENID_DISCOVERED_KEY, discovered);
}
@Override
public DiscoveryInformation retrieveDiscoveryInfo(HttpServletRequest httpReq) {
return (DiscoveryInformation) httpReq.getSession().getAttribute(OPENID_DISCOVERED_KEY);
}
/*@Override
public AxExtensionConsumer getAxExtensionConsumer() {
return this.axExtConsumer;
}
@Override
public void setAxExtensionConsumer(AxExtensionConsumer axExtConsumer) {
this.axExtConsumer = axExtConsumer;
}*/
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/internal/HttpSessionOpenIdConsumer.java | Java | asf20 | 4,325 |
package com.zyeeda.framework.openid.consumer.internal;
import org.openid4java.message.MessageException;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
import com.zyeeda.framework.openid.consumer.AxExtensionConsumer;
public class UserInfoAxExtensionConsumer implements AxExtensionConsumer {
@Override
public FetchRequest prepareFetchRequest() throws MessageException {
FetchRequest fetchReq = FetchRequest.createFetchRequest();
fetchReq.addAttribute("id", "http://axschema.org/namePerson/friendly", true);
fetchReq.addAttribute("username", "http://axschema.org/namePerson", false);
fetchReq.addAttribute("gender", "http://axschema.org/person/gender", false);
fetchReq.addAttribute("position", "http://zyeeda.com/openid/ax/csg/person/position", false);
fetchReq.addAttribute("degree", "http://zyeeda.com/openid/ax/csg/person/degree", false);
fetchReq.addAttribute("email", "http://axschema.org/contact/email", false);
fetchReq.addAttribute("mobile", "http://axschema.org/contact/phone/cell", false);
fetchReq.addAttribute("birthday", "http://axschema.org/birthDate", false);
fetchReq.addAttribute("dateOfWork", "http://zyeeda.com/openid/ax/csg/person/dateOfWork", false);
fetchReq.addAttribute("department", "http://zyeeda.com/openid/ax/csg/person/department", false);
return fetchReq;
}
@Override
public void processFetchResponse(FetchResponse fetchResp) {
// TODO Auto-generated method stub
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/internal/UserInfoAxExtensionConsumer.java | Java | asf20 | 1,517 |
package com.zyeeda.framework.openid.consumer.internal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.configuration.Configuration;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.openid4java.OpenIDException;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.openid.consumer.OpenIdConsumer;
import com.zyeeda.framework.openid.consumer.OpenIdConsumerService;
import com.zyeeda.framework.service.AbstractService;
@ServiceId("default-openid-consumer-service")
@Marker(Primary.class)
public class DefaultOpenIdConsumerServiceProvider extends AbstractService
implements OpenIdConsumerService {
private final static String RETURN_TO_URL_KEY = "returnToUrl";
private final static String OPENID_PROVIDER_KEY = "openIdProvider";
private final static String REALM_KEY = "realm";
private String returnToUrl;
private String openIdProvider;
private String realm;
private OpenIdConsumer consumer;
public DefaultOpenIdConsumerServiceProvider(
@Primary ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) {
super(shutdownHub);
Configuration config = this.getConfiguration(configSvc);
this.init(config);
}
private void init(Configuration config) {
this.returnToUrl = config.getString(RETURN_TO_URL_KEY);
this.openIdProvider = config.getString(OPENID_PROVIDER_KEY);
this.realm = config.getString(REALM_KEY);
}
@Override
public void start() throws Exception {
this.consumer = new ShiroSessionOpenIdConsumer();
this.consumer.setReturnToUrl(this.returnToUrl);
this.consumer.setRealm(this.realm);
}
@Override
public void stop() {
this.consumer = null;
}
@Override
public AuthRequest authRequest(HttpServletRequest request, HttpServletResponse response) throws OpenIDException {
return this.consumer.authRequest(this.openIdProvider, request, response);
}
@Override
public Identifier verifyResponse(HttpServletRequest request) throws OpenIDException {
return this.consumer.verifyResponse(request);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/internal/DefaultOpenIdConsumerServiceProvider.java | Java | asf20 | 2,425 |
package com.zyeeda.framework.openid.consumer.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OpenIdConsumerRealm extends AuthorizingRealm {
private static final Logger logger = LoggerFactory.getLogger(OpenIdConsumerRealm.class);
public OpenIdConsumerRealm() {
this.setAuthenticationTokenClass(PasswordFreeAuthenticationToken.class);
this.setCredentialsMatcher(new BypassCredentialsMatcher());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
logger.debug("authentication token type = {}", token.getClass().getName());
Object principal = token.getPrincipal();
if (principal == null) {
throw new AuthenticationException("Cannot authenticate with null principal.");
}
return new SimpleAuthenticationInfo(principal, null, this.getName());
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/shiro/OpenIdConsumerRealm.java | Java | asf20 | 1,403 |
package com.zyeeda.framework.openid.consumer.shiro;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
public class BypassCredentialsMatcher implements CredentialsMatcher {
@Override
public boolean doCredentialsMatch(AuthenticationToken token,
AuthenticationInfo info) {
return true;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/shiro/BypassCredentialsMatcher.java | Java | asf20 | 426 |
package com.zyeeda.framework.openid.consumer.shiro;
import org.apache.shiro.authc.AuthenticationToken;
public class PasswordFreeAuthenticationToken implements AuthenticationToken {
private static final long serialVersionUID = 6738193152053272419L;
private String userId;
public PasswordFreeAuthenticationToken(String userId) {
this.userId = userId;
}
@Override
public Object getPrincipal() {
return this.userId;
}
@Override
public Object getCredentials() {
return null;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/shiro/PasswordFreeAuthenticationToken.java | Java | asf20 | 525 |
package com.zyeeda.framework.openid.consumer.shiro;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.apache.tapestry5.ioc.Registry;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.openid.consumer.OpenIdConsumerService;
import com.zyeeda.framework.utils.IocUtils;
public class OpenIdConsumerAuthcFilter extends AuthenticatingFilter {
private static final Logger logger = LoggerFactory.getLogger(OpenIdConsumerAuthcFilter.class);
private String callbackUrl;
private String returnToUrl;
@Override
public void setLoginUrl(String loginUrl) {
String previous = getLoginUrl();
if (previous != null) {
this.appliedPaths.remove(previous);
}
super.setLoginUrl(loginUrl);
logger.trace("Adding login url to applied paths.");
this.appliedPaths.put(getLoginUrl(), null);
}
public void setReturnToUrl(String returnToUrl) {
/*String previous = this.returnToUrl;
if (previous != null) {
this.appliedPaths.remove(previous);
}*/
this.returnToUrl = returnToUrl;
/*logger.trace("Adding OpenId returnTo url to applied paths.");
this.appliedPaths.put(this.returnToUrl, null);*/
}
@Override
protected AuthenticationToken createToken(ServletRequest request,
ServletResponse response) throws Exception {
HttpServletRequest httpReq = (HttpServletRequest) request;
Registry registry = IocUtils.getRegistry(this.getServletContext());
OpenIdConsumerService openidConsumer = registry.getService(OpenIdConsumerService.class);
Identifier id = openidConsumer.verifyResponse(httpReq);
logger.info("Create OpenID authentication info.");
AuthenticationToken token = new OpenIdAuthenticationToken(id);
return token;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
logger.debug("Access denied.");
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
if (logger.isDebugEnabled()) {
Cookie[] cookies = httpReq.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
logger.debug(cookie.getName() + " : " + cookie.getValue());
}
}
}
Registry registry = IocUtils.getRegistry(this.getServletContext());
OpenIdConsumerService openidConsumer = registry.getService(OpenIdConsumerService.class);
if (logger.isDebugEnabled()) {
logger.debug("http request uri = {}", httpReq.getRequestURI());
logger.debug("login url = {}", this.getLoginUrl());
}
if (this.isLoginRequest(httpReq, httpRes)) {
// 如果请求的是登录地址,继续进入 OpenID 的登录界面
logger.debug("OpenID login request detected, redirect to OP endpoint.");
AuthRequest authReq = openidConsumer.authRequest(httpReq, httpRes);
httpReq.setAttribute("message", authReq);
return true;
}
logger.debug("success url = {}", this.getSuccessUrl());
if (this.pathsMatch(this.getSuccessUrl(), request)) {
// 如果请求的是认证成功地址 (一般是首页),重定向到登录界面
logger.debug("Trying to visit login success URL, redirect to sign in page.");
WebUtils.getAndClearSavedRequest(request);
this.redirectToLogin(request, response);
return false;
}
logger.debug("return to url = {}", this.returnToUrl);
if (this.pathsMatch(this.returnToUrl, request)) {
// 如果请求的是验证地址,处理登录
logger.debug("OpenID verify request detected, attempt to perform signin.");
boolean success = this.executeLogin(httpReq, httpRes);
logger.debug("OpenID login result = {}", success);
if (success) {
this.issueSuccessRedirect(httpReq, httpRes);
} else {
httpRes.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
return false;
}
// 请求其它地址,返回 401
logger.debug("Permission denied on visiting resource [{}].", httpReq.getPathInfo());
this.saveRequest(request);
httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
boolean result = super.isAccessAllowed(request, response, mappedValue);
logger.debug("is access allowed = {}", result);
return result;
}
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
ServletResponse response) {
logger.error(e.getMessage(), e);
return false;
}
protected boolean issueSuccessRedirect(HttpServletRequest httpReq, HttpServletResponse httpRes) throws IOException {
SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(httpReq);
if (savedRequest == null) {
logger.debug("saved request is null");
WebUtils.issueRedirect(httpReq, httpRes, this.getSuccessUrl());
return false;
}
Map<String, String> params = new HashMap<String, String>(2);
params.put("_url", savedRequest.getRequestUrl());
params.put("_method", savedRequest.getMethod());
logger.debug("saved request is {}", params);
WebUtils.issueRedirect(httpReq, httpRes, this.callbackUrl, params);
return false;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/shiro/OpenIdConsumerAuthcFilter.java | Java | asf20 | 6,116 |
package com.zyeeda.framework.openid.consumer.shiro;
import org.apache.commons.lang.StringUtils;
import org.openid4java.discovery.Identifier;
public class OpenIdAuthenticationToken extends PasswordFreeAuthenticationToken {
private static final long serialVersionUID = 7305997052059544245L;
public OpenIdAuthenticationToken(Identifier id) {
super(StringUtils.substringAfter(id.getIdentifier(), "id="));
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/openid/consumer/shiro/OpenIdAuthenticationToken.java | Java | asf20 | 430 |
package com.zyeeda.framework.entities;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.zyeeda.framework.entities.base.RevisionDomainEntity;
@Entity
@Table(name = "ZDA_SYS_PROCESS_HISTORY")
public class ProcessHistory extends RevisionDomainEntity {
private static final long serialVersionUID = 7750232753102958884L;
private String processId;
private Long processInstanceId;
private String currentState;
private Boolean ended = false;
@Basic
@Column(name = "F_PROCESS_ID")
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
@Basic
@Column(name = "F_PROCESS_INS_ID")
public Long getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(Long processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Basic
@Column(name = "F_CURRENT_STATE")
public String getCurrentState() {
return currentState;
}
public void setCurrentState(String currentState) {
this.currentState = currentState;
}
@Basic
@Column(name = "F_ENDED")
public Boolean isEnded() {
return ended;
}
public void setEnded(Boolean ended) {
this.ended = ended;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/ProcessHistory.java | Java | asf20 | 1,355 |
package com.zyeeda.framework.entities;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "department")
public class Department/* extends SimpleDomainEntity*/ implements Serializable {
private static final long serialVersionUID = 8606771207286469030L;
private String id;
private String parent;
private String name;
private String deptFullPath;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeptFullPath() {
return deptFullPath;
}
public void setDeptFullPath(String deptFullPath) {
this.deptFullPath = deptFullPath;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/Department.java | Java | asf20 | 1,131 |
package com.zyeeda.framework.entities;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.zyeeda.framework.entities.base.RevisionDomainEntity;
@Entity
@Table(name = "ZDA_SYS_ACTION_HISTORY")
public class ActionHistory extends RevisionDomainEntity {
private static final long serialVersionUID = 79794909507686169L;
private String processId;
private String processName;
private Long processInstanceId;
private String nodeId;
private String nodeType;
private String nodeInstanceId;
private Boolean alive = true;
@Basic
@Column(name = "F_PROCESS_ID")
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
@Basic
@Column(name = "F_PROCESS_NAME")
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
@Basic
@Column(name = "F_PROCESS_INS_ID")
public Long getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(Long processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Basic
@Column(name = "F_NODE_ID")
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
@Basic
@Column(name = "F_NODE_TYPE")
public String getNodeType() {
return nodeType;
}
public void setNodeType(String nodeType) {
this.nodeType = nodeType;
}
@Basic
@Column(name = "F_NODE_INS_ID")
public void setNodeInstanceId(String nodeInstanceId) {
this.nodeInstanceId = nodeInstanceId;
}
public void setAlive(Boolean alive) {
this.alive = alive;
}
@Basic
@Column(name = "F_ALIVE")
public Boolean isAlive() {
return alive;
}
public String getNodeInstanceId() {
return nodeInstanceId;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/ActionHistory.java | Java | asf20 | 2,004 |
package com.zyeeda.framework.entities;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "testEntity")
public class TestEntity {
private String name;
private List<TestEntity> children;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TestEntity> getChildren() {
return children;
}
public void setChildren(List<TestEntity> children) {
this.children = children;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/TestEntity.java | Java | asf20 | 528 |
package com.zyeeda.framework.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.TemporalType;
@Entity(name = "ZDA_SYS_USER")
public class User/* extends SimpleDomainEntity*/ implements Serializable {
private static final long serialVersionUID = -411862891641683217L;
private String id;
private String username;
private String password;
private String gender;
private String position;
private String degree;
private String email;
private String mobile;
private Date birthday;
private Date dateOfWork;
private Boolean status;
private Boolean postStatus;
// private byte[] photo;
private String departmentName;
private String deptFullPath;
private String departmentNo;
@Id @Column(name = "F_ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "F_USERNAME", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "F_PASSWORD", nullable = false, length = 36)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "F_GENDER", length = 4)
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Column(name = "F_POSITION", length = 100)
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Column(name = "F_DEGREE", length = 100)
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
@Column(name = "F_EMAIL", length = 50)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "F_MOBILE", length = 13)
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@javax.persistence.Temporal(TemporalType.TIMESTAMP)
@javax.persistence.Column(name = "F_BIRTHDAY")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@javax.persistence.Temporal(TemporalType.TIMESTAMP)
@javax.persistence.Column(name = "F_DATEOFWORK")
public Date getDateOfWork() {
return dateOfWork;
}
public void setDateOfWork(Date dateOfWork) {
this.dateOfWork = dateOfWork;
}
@Column(name = "STATUS")
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
@Column(name = "POSTSTATUS")
public Boolean getPostStatus() {
return postStatus;
}
public void setPostStatus(Boolean postStatus) {
this.postStatus = postStatus;
}
// public byte[] getPhoto() {
// return photo;
// }
//
// public void setPhoto(byte[] photo) {
// this.photo = photo;
// }
@Column(name = "F_DEPARTMENTNAME", length = 100)
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Column(name = "F_DEPTFULLPATH", length = 100)
public String getDeptFullPath() {
return deptFullPath;
}
public void setDeptFullPath(String deptFullPath) {
this.deptFullPath = deptFullPath;
}
@Column(name = "F_DEPARTMENT_NO", length = 100)
public String getDepartmentNo() {
return this.departmentNo;
}
public void setDepartmentNo(String departmentNo) {
this.departmentNo = departmentNo;
}
} | zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/User.java | Java | asf20 | 3,832 |
package com.zyeeda.framework.entities;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.entities.base.RevisionDomainEntity;
@Entity
@Table(name = "ZDA_ACTION_LOGS")
@XmlRootElement(name = "actionLogs")
public class ActionLog extends RevisionDomainEntity {
private static final long serialVersionUID = -7970644520971484077L;
/**
* 执行人
*/
private String actor;
/**
* 执行动作
*/
private String action;
/**
* 执行人
*/
@Basic
@Column(name = "F_ACTOR", length = 30)
public String getActor() {
return actor;
}
/**
* 执行人
*/
public void setActor(String actor) {
this.actor = actor;
}
/**
* 执行动作
*/
@Basic
@Column(name = "F_ACTION", length = 50)
public String getAction() {
return action;
}
/**
* 执行动作
*/
public void setAction(String action) {
this.action = action;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/ActionLog.java | Java | asf20 | 1,075 |
package com.zyeeda.framework.entities;
import java.io.InputStream;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.entities.base.RevisionDomainEntity;
@Entity
@Table(name = "ZDA_SYS_DOCUMENTS")
@XmlRootElement(name = "document")
public class Document extends RevisionDomainEntity {
private static final long serialVersionUID = -5913731949268189623L;
// 外键
private String foreignId;
// 排序
private int weight;
// 所有者
private String owner;
// 文件大小
private long fileSize;
// 文件类型,保存文件扩展名
private String fileType;
// 文件类型(完整的 Media Type)
private String contentType;
// 文件类型(Media Type 的主类型)
private String primaryType;
// 文件类型(Media Type 的子类型)
private String subType;
// 关键字
private String keyword;
// 类别
private String category;
// 是否为临时文件
private boolean temp;
// 文件内容
private InputStream content;
public String getForeignId() {
return foreignId;
}
public void setForeignId(String foreignId) {
this.foreignId = foreignId;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getSubType() {
return subType;
}
public void setSubType(String subType) {
this.subType = subType;
}
public String getPrimaryType() {
return primaryType;
}
public void setPrimaryType(String primaryType) {
this.primaryType = primaryType;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public InputStream getContent() {
return content;
}
public void setContent(InputStream content) {
this.content = content;
}
public boolean isTemp() {
return temp;
}
public void setTemp(boolean temp) {
this.temp = temp;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/Document.java | Java | asf20 | 2,793 |
package com.zyeeda.framework.entities.base;
import java.io.Serializable;
@javax.persistence.MappedSuperclass
public class DomainEntity implements Serializable {
private static final long serialVersionUID = 6570499338336870036L;
private String id;
@javax.persistence.Id
@javax.persistence.Column(name = "F_ID")
@javax.persistence.GeneratedValue(generator="system-uuid")
@org.hibernate.annotations.GenericGenerator(name="system-uuid", strategy = "uuid")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/base/DomainEntity.java | Java | asf20 | 601 |
package com.zyeeda.framework.entities.base;
@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {
private static final long serialVersionUID = -2200108673372668900L;
private String name;
private String description;
@javax.persistence.Basic
@javax.persistence.Column(name = "F_NAME")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@javax.persistence.Basic
@javax.persistence.Column(name = "F_DESC", length = 2000)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/base/SimpleDomainEntity.java | Java | asf20 | 756 |
package com.zyeeda.framework.entities.base;
import java.util.Date;
import javax.persistence.TemporalType;
@javax.persistence.MappedSuperclass
public class RevisionDomainEntity extends SimpleDomainEntity {
private static final long serialVersionUID = 2055338408696881639L;
private String creator;
private Date createdTime;
private String lastModifier;
private Date lastModifiedTime;
@javax.persistence.Basic
@javax.persistence.Column(name = "F_CREATOR", length = 20)
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
@javax.persistence.Temporal(TemporalType.TIMESTAMP)
@javax.persistence.Column(name = "F_CREATED_TIME")
public Date getCreatedTime() {
return this.createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
@javax.persistence.Basic
@javax.persistence.Column(name = "F_LAST_MODIFIER", length = 20)
public String getLastModifier() {
return this.lastModifier;
}
public void setLastModifier(String lastModifier) {
this.lastModifier = lastModifier;
}
@javax.persistence.Temporal(TemporalType.TIMESTAMP)
@javax.persistence.Column(name = "F_LAST_MODIFIED_TIME")
public Date getLastModifiedTime() {
return this.lastModifiedTime;
}
public void setLastModifiedTime(Date lastModifiedTime) {
this.lastModifiedTime = lastModifiedTime;
}
public void prePersist(RevisionDomainEntity e) {
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/base/RevisionDomainEntity.java | Java | asf20 | 1,674 |
package com.zyeeda.framework.entities;
import java.io.Serializable;
public class Account implements Serializable {
private static final long serialVersionUID = -7523580183398096125L;
private String userName;
private String password;
private String systemName;
private String userFullPath;
private Boolean status = false;
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserFullPath() {
return this.userFullPath;
}
public void setUserFullPath(String userFullPath) {
this.userFullPath = userFullPath;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/Account.java | Java | asf20 | 1,078 |
package com.zyeeda.framework.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.entities.base.SimpleDomainEntity;
@Entity
@Table(name = "ZDA_SYS_DICT")
@XmlRootElement(name = "dict")
public class Dictionary extends SimpleDomainEntity {
private static final long serialVersionUID = 5516157716776374792L;
@Column(name = "F_VALUE")
private String value;
@Column(name = "F_TYPE")
private String type;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/entities/Dictionary.java | Java | asf20 | 817 |
package com.zyeeda.framework.viewmodels;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "roleWithUserVo")
public class RoleWithUserVo {
private Set<UserNameVo> userName = new HashSet<UserNameVo>();
private List<PermissionVo> permission = new ArrayList<PermissionVo>();
public List<PermissionVo> getPermission() {
return permission;
}
public void setPermission(List<PermissionVo> permission) {
this.permission = permission;
}
public Set<UserNameVo> getUserName() {
return userName;
}
public void setUserName(Set<UserNameVo> userName) {
this.userName = userName;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/RoleWithUserVo.java | Java | asf20 | 761 |
package com.zyeeda.framework.viewmodels;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.entities.Account;
@XmlRootElement(name="avo")
public class AccountVo {
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/AccountVo.java | Java | asf20 | 418 |
package com.zyeeda.framework.viewmodels;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.entities.Role;
@XmlRootElement(name = "roleVoAndQualification")
public class RoleVoAndQualification {
private List<DepartmentVo> departmentVo = new ArrayList<DepartmentVo>();
public List<DepartmentVo> getDepartmentVo() {
return departmentVo;
}
public void setDepartmentVo(List<DepartmentVo> departmentVo) {
this.departmentVo = departmentVo;
}
private List<Role> role = new ArrayList<Role>();
public List<Role> getRole() {
return role;
}
public void setRole(List<Role> role) {
this.role = role;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/RoleVoAndQualification.java | Java | asf20 | 734 |
package com.zyeeda.framework.viewmodels;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "roleVo")
public class RoleVo {
private String id;
private String type;
private String checkName;
private String label;
private boolean leaf;
private String io;
private String fullPath;
/*标识是用户还是部门*/
private String kind;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCheckName() {
return checkName;
}
public void setCheckName(String checkName) {
this.checkName = checkName;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public String getIo() {
return io;
}
public void setIo(String io) {
this.io = io;
}
public String getFullPath() {
return fullPath;
}
public void setFullPath(String fullPath) {
this.fullPath = fullPath;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/RoleVo.java | Java | asf20 | 1,356 |
package com.zyeeda.framework.viewmodels;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "document")
public class DocumentVo {
private static final long serialVersionUID = 6753120023803767202L;
private String id;
private String fileName;
private long fileSize;
private String fileType;
private String creator;
private String createdTime;
private String updateUrl;
private String viewUrl;
private String downloadUrl;
private String deleteUrl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public String getUpdateUrl() {
return updateUrl;
}
public void setUpdateUrl(String updateUrl) {
this.updateUrl = updateUrl;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public String getDeleteUrl() {
return deleteUrl;
}
public void setDeleteUrl(String deleteUrl) {
this.deleteUrl = deleteUrl;
}
public String getViewUrl() {
return viewUrl;
}
public void setViewUrl(String viewUrl) {
this.viewUrl = viewUrl;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/DocumentVo.java | Java | asf20 | 1,873 |
package com.zyeeda.framework.viewmodels;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "departmentVo")
public class DepartmentVo implements Serializable {
private static final long serialVersionUID = 8606771207287369030L;
private String id;
private String type;
private String checkName;
private String label;
private boolean leaf;
private String io;
private String kind;
private String deptFullPath;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCheckName() {
return checkName;
}
public void setCheckName(String checkName) {
this.checkName = checkName;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public String getIo() {
return io;
}
public void setIo(String io) {
this.io = io;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getDeptFullPath() {
return deptFullPath;
}
public void setDeptFullPath(String deptFullPath) {
this.deptFullPath = deptFullPath;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/DepartmentVo.java | Java | asf20 | 1,482 |
package com.zyeeda.framework.viewmodels;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "organizationNodeVo")
public class OrganizationNodeVo implements Serializable{
private static final long serialVersionUID = 8606771207287369030L;
private String id;
private String type;
private String checkName;
private String label;
private boolean leaf;
private String io;
private String fullPath;
private Boolean checkedAuth;
private Boolean checked;
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
/*标识是用户还是部门*/
private String kind;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCheckName() {
return checkName;
}
public void setCheckName(String checkName) {
this.checkName = checkName;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public String getIo() {
return io;
}
public void setIo(String io) {
this.io = io;
}
public String getFullPath() {
return fullPath;
}
public void setFullPath(String fullPath) {
this.fullPath = fullPath;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Boolean getCheckedAuth() {
return checkedAuth;
}
public void setCheckedAuth(Boolean checkedAuth) {
this.checkedAuth = checkedAuth;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/OrganizationNodeVo.java | Java | asf20 | 1,858 |
package com.zyeeda.framework.viewmodels;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "documentListView")
public class DocumentsVo {
private int totalRecords;
private int startIndex;
private String sort;
private String dir;
private List<DocumentVo> records;
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public List<DocumentVo> getRecords() {
return records;
}
public void setRecords(List<DocumentVo> records) {
this.records = records;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/DocumentsVo.java | Java | asf20 | 1,007 |
package com.zyeeda.framework.viewmodels;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "userVo")
public class UserVo implements Serializable{
private static final long serialVersionUID = 8606771207287369030L;
private String id;
private String type;
private String checkName;
private String label;
private String uid;
private boolean leaf;
private String deptFullPath;
private String kind;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCheckName() {
return checkName;
}
public void setCheckName(String checkName) {
this.checkName = checkName;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public String getDeptFullPath() {
return deptFullPath;
}
public void setDeptFullPath(String deptFullPath) {
this.deptFullPath = deptFullPath;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/UserVo.java | Java | asf20 | 1,496 |
package com.zyeeda.framework.viewmodels;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "menuAndPermission")
public class MenuAndPermission {
private List<MenuVo> listMenu = new ArrayList<MenuVo>();
private List<PermissionVo> listPermission = new ArrayList<PermissionVo>();
public List<MenuVo> getListMenu() {
return listMenu;
}
public void setListMenu(List<MenuVo> listMenu) {
this.listMenu = listMenu;
}
public List<PermissionVo> getListPermission() {
return listPermission;
}
public void setListPermission(List<PermissionVo> listPermission) {
this.listPermission = listPermission;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/MenuAndPermission.java | Java | asf20 | 723 |
package com.zyeeda.framework.viewmodels;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "authVO")
public class AuthVO {
private String type;
private String id;
private String label;
private boolean leaf;
private String io;
private String tag;
private Boolean checked;
// public Boolean getChecked() {
// return checked;
// }
// public void setChecked(Boolean checked) {
// this.checked = checked;
// }
// public String getPermission() {
// return permission;
// }
public String getTag() {
return tag;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getIo() {
return io;
}
public void setIo(String io) {
this.io = io;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/AuthVO.java | Java | asf20 | 1,331 |
package com.zyeeda.framework.viewmodels;
import java.util.ArrayList;
import java.util.List;
public class PermissionVo {
private String id;
private String name;
private String value;
private Boolean isHaveIO;
private int path;
private String orderBy;
private List<PermissionVo> permissionList = new ArrayList<PermissionVo>();
public List<PermissionVo> getPermissionList() {
return permissionList;
}
public void setPermissionList(List<PermissionVo> permissionList) {
this.permissionList = permissionList;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public int getPath() {
return path;
}
public void setPath(int path) {
this.path = path;
}
private Boolean checked;
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public Boolean getIsHaveIO() {
return isHaveIO;
}
public void setIsHaveIO(Boolean isHaveIO) {
this.isHaveIO = isHaveIO;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/PermissionVo.java | Java | asf20 | 1,436 |
package com.zyeeda.framework.viewmodels;
import java.util.List;
public class GenericListVo<T> {
private int currentPage;
private int totalPages;
private int totalRecords;
private List<T> records;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public List<T> getRecords() {
return records;
}
public void setRecords(List<T> records) {
this.records = records;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/GenericListVo.java | Java | asf20 | 806 |
package com.zyeeda.framework.viewmodels;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "userName")
public class UserNameVo {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/UserNameVo.java | Java | asf20 | 332 |
package com.zyeeda.framework.viewmodels;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.utils.MenuListComparator;
@XmlRootElement(name = "menuVo")
public class MenuVo {
private String id;
private String name;
private String auth;
private List<MenuVo> permissionSet = new ArrayList<MenuVo>();
private MenuVo parentMenu;
private String orderBy;
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public MenuVo getParentMenu() {
return parentMenu;
}
public List<MenuVo> getPermissionSet() {
if(permissionSet.size() > 0) {
MenuListComparator comparator = new MenuListComparator();
Collections.sort(permissionSet, comparator);
}
return permissionSet;
}
public void setPermissionSet(List<MenuVo> permissionSet) {
this.permissionSet = permissionSet;
}
public void setParentMenu(MenuVo parentMenu) {
this.parentMenu = parentMenu;
}
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// public Set<MenuVo> getPermissionSet() {
// return permissionSet;
// }
//
// public void setPermissionSet(Set<MenuVo> permissionSet) {
// this.permissionSet = permissionSet;
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/viewmodels/MenuVo.java | Java | asf20 | 1,627 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.jpassport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JPassport implementation of {@link javax.servlet.http.HttpServletRequest HttpServletRequest}.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class JPassportHttpServletRequest extends HttpServletRequestWrapper {
private static final Logger logger = LoggerFactory.getLogger(JPassportHttpServletRequest.class);
private String remoteUser;
public JPassportHttpServletRequest(HttpServletRequest request) {
super(request);
}
public void setRemoteUser(String remoteUser) {
logger.debug("remote user = {}", remoteUser);
this.remoteUser = remoteUser;
}
@Override
public String getRemoteUser() {
return this.remoteUser;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/jpassport/JPassportHttpServletRequest.java | Java | asf20 | 1,524 |
package com.zyeeda.framework.jobs;
import org.apache.tapestry5.ioc.ScopeConstants;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.Scope;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.managers.DocumentManager;
import com.zyeeda.framework.managers.internal.MongoDbDocumentManager;
import com.zyeeda.framework.nosql.MongoDbService;
@ServiceId("erase-temp-document-job")
@Scope(ScopeConstants.PERTHREAD)
public class EraseTempDocumentJob implements Job {
private final static Logger logger = LoggerFactory.getLogger(EraseTempDocumentJob.class);
private MongoDbService mongoSvc;
public EraseTempDocumentJob(@Primary MongoDbService mongoSvc) {
this.mongoSvc = mongoSvc;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
DocumentManager mgr = new MongoDbDocumentManager(this.mongoSvc);
long count = mgr.countByIsTemp();
logger.info("Erasing temporary documents, {} to erase ...", count);
mgr.eraseTemp();
logger.info("Temporary documents erased!");
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/jobs/EraseTempDocumentJob.java | Java | asf20 | 1,303 |
package com.zyeeda.framework;
public class Test {
public static void main(String[] args) {
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/Test.java | Java | asf20 | 116 |
package com.zyeeda.framework.cxf;
import java.text.SimpleDateFormat;
import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.SerializationConfig.Feature;
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
public JacksonJsonProvider() {
ObjectMapper m = this._mapperConfig.getConfiguredMapper();
if (m == null) {
m = this._mapperConfig.getDefaultMapper();
}
SerializationConfig sc = m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
sc.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
sc.set(Feature.FAIL_ON_EMPTY_BEANS, false);
m.setSerializationConfig(sc);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/cxf/JacksonJsonProvider.java | Java | asf20 | 866 |
package com.zyeeda.framework.cxf;
import org.apache.cxf.jaxrs.provider.JSONProvider;
public class DedicatedJsonProvider extends JSONProvider {
public DedicatedJsonProvider() {
super();
this.setSerializeAsArray(true);
this.setDropRootElement(true);
this.setDropCollectionWrapperElement(true);
this.setEnableBuffering(true);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/cxf/DedicatedJsonProvider.java | Java | asf20 | 360 |
package com.zyeeda.framework.cxf;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.ext.ParameterHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DateParameterHandler implements ParameterHandler<Date> {
private static final Logger logger = LoggerFactory.getLogger(DateParameterHandler.class);
@Override
public Date fromString(String str) {
logger.debug("date/datetime string = {}", str);
if (StringUtils.isBlank(str)) {
return null;
}
String[] parts = StringUtils.split(str);
SimpleDateFormat sdf = null;
try {
if (parts.length == 1) {
logger.debug("parsing string using date format: yyyy-MM-dd");
sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(str);
}
if (parts.length == 2) {
logger.debug("parsing string using datetime format: yyyy-MM-dd hh:mm:ss");
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return sdf.parse(str);
}
throw new RuntimeException("Invalid date/datetime format.");
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/cxf/DateParameterHandler.java | Java | asf20 | 1,228 |
package com.zyeeda.framework.scheduler;
import com.zyeeda.framework.service.Service;
public interface SchedulerService<T> extends Service {
public T getScheduler();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/scheduler/SchedulerService.java | Java | asf20 | 182 |
package com.zyeeda.framework.scheduler.internal;
import org.apache.tapestry5.ioc.ServiceResources;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import com.zyeeda.framework.scheduler.SchedulerService;
import com.zyeeda.framework.service.AbstractService;
@ServiceId("quartz-scheduler-serivce")
@Marker(Primary.class)
public class QuartzSchedulerServiceProvider extends AbstractService implements SchedulerService<Scheduler> {
private ServiceResources resources;
private SchedulerFactory schedulerFac;
private Scheduler scheduler;
public QuartzSchedulerServiceProvider(
ServiceResources resources,
RegistryShutdownHub shutdownHub) throws SchedulerException {
super(shutdownHub);
this.resources = resources;
this.init();
}
private void init() throws SchedulerException {
this.schedulerFac = new StdSchedulerFactory();
this.scheduler = this.schedulerFac.getScheduler();
this.scheduler.setJobFactory(new TapestryIocJobFactory(this.resources));
}
@Override
public void start() throws SchedulerException {
this.scheduler.start();
}
@Override
public void stop() throws SchedulerException {
this.scheduler.shutdown();
}
@Override
public Scheduler getScheduler() {
return this.scheduler;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/scheduler/internal/QuartzSchedulerServiceProvider.java | Java | asf20 | 1,616 |
package com.zyeeda.framework.scheduler.internal;
import org.apache.tapestry5.ioc.ServiceResources;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.AnnotationException;
import com.zyeeda.framework.utils.IocUtils;
public class TapestryIocJobFactory implements JobFactory {
private final static Logger logger = LoggerFactory.getLogger(TapestryIocJobFactory.class);
private ServiceResources resources;
public TapestryIocJobFactory(ServiceResources resources) {
this.resources = resources;
}
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
JobDetail detail = bundle.getJobDetail();
Class<? extends Job> jobClass = detail.getJobClass();
try {
Job job = this.resources.getService(IocUtils.getServiceId(jobClass), Job.class);
logger.debug("New {} job instance from IoC container", jobClass.getSimpleName());
return job;
} catch (AnnotationException e) {
logger.trace(e.getMessage(), e);
}
try {
Job job = jobClass.newInstance();
logger.debug("New {} job instance via constructor", jobClass.getSimpleName());
return job;
} catch (InstantiationException e) {
throw new SchedulerException(e);
} catch (IllegalAccessException e) {
throw new SchedulerException(e);
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/scheduler/internal/TapestryIocJobFactory.java | Java | asf20 | 1,563 |
package com.zyeeda.framework.transaction.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BTM {
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/transaction/annotations/BTM.java | Java | asf20 | 384 |
package com.zyeeda.framework.transaction.internal;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import javax.transaction.TransactionManager;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.service.AbstractService;
import com.zyeeda.framework.transaction.TransactionService;
import com.zyeeda.framework.transaction.TransactionServiceException;
@Marker(Primary.class)
@ServiceId("default-transaction-service")
public class DefaultTransactionServiceProvider extends AbstractService implements TransactionService {
public DefaultTransactionServiceProvider(RegistryShutdownHub shutdownHub) {
super(shutdownHub);
}
@Override
@SuppressWarnings("rawtypes")
public UserTransaction getTransaction() throws TransactionServiceException {
try {
Hashtable env = new Hashtable();
Context ctx = new InitialContext(env);
UserTransaction utx = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
return utx;
} catch (NamingException e) {
throw new TransactionServiceException(e);
}
}
@Override
@SuppressWarnings("rawtypes")
public TransactionManager getTransactionManager() throws TransactionServiceException {
try {
Hashtable env = new Hashtable();
Context ctx = new InitialContext(env);
TransactionManager tm = (TransactionManager) ctx.lookup("java:comp/env/TransactionManager");
return tm;
} catch (NamingException e) {
throw new TransactionServiceException(e);
}
}
@SuppressWarnings("rawtypes")
@Override
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry()
throws TransactionServiceException {
try {
Hashtable env = new Hashtable();
Context ctx = new InitialContext(env);
TransactionSynchronizationRegistry tsr = (TransactionSynchronizationRegistry) ctx.lookup("java:comp/env/TransactionSynchronizationRegistry");
return tsr;
} catch (NamingException e) {
throw new TransactionServiceException(e);
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/transaction/internal/DefaultTransactionServiceProvider.java | Java | asf20 | 2,335 |
package com.zyeeda.framework.transaction.internal;
import java.net.URL;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.service.AbstractService;
import com.zyeeda.framework.transaction.TransactionService;
import com.zyeeda.framework.transaction.TransactionServiceException;
import com.zyeeda.framework.transaction.annotations.BTM;
import bitronix.tm.Configuration;
import bitronix.tm.TransactionManagerServices;
@Marker(BTM.class)
@ServiceId("bitronix-transaction-service")
public class BitronixTransactionServiceProvider extends AbstractService implements TransactionService {
private static final Logger logger = LoggerFactory.getLogger(BitronixTransactionServiceProvider.class);
private final static String JNDI_USER_TRANSACTION_NAME = "btmTransactionManager";
private final static String JNDI_TRANSACTION_SYNCHRONIZATION_REGISTRY_NAME = "btmSynchronizationRegistry";
public BitronixTransactionServiceProvider(RegistryShutdownHub shutdownHub) {
super(shutdownHub);
}
@Override
public void start() {
Configuration cfg = TransactionManagerServices.getConfiguration();
URL url = this.getClass().getClassLoader().getResource("bitronix-datasources.properties");
logger.debug("resource configuration file name = {}", url.getPath());
cfg.setResourceConfigurationFilename(url.getPath());
cfg.setJndiUserTransactionName(JNDI_USER_TRANSACTION_NAME);
cfg.setJndiTransactionSynchronizationRegistryName(JNDI_TRANSACTION_SYNCHRONIZATION_REGISTRY_NAME);
TransactionManagerServices.getTransactionManager();
}
@Override
public void stop() {
TransactionManagerServices.getTransactionManager().shutdown();
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public UserTransaction getTransaction() throws TransactionServiceException {
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "bitronix.tm.jndi.BitronixInitialContextFactory");
Context ctx = new InitialContext(env);
UserTransaction utx = (UserTransaction) ctx.lookup(JNDI_USER_TRANSACTION_NAME);
return utx;
} catch (NamingException e) {
throw new TransactionServiceException(e);
}
}
@Override
public TransactionManager getTransactionManager() {
return TransactionManagerServices.getTransactionManager();
}
@Override
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry()
throws TransactionServiceException {
return TransactionManagerServices.getTransactionSynchronizationRegistry();
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/transaction/internal/BitronixTransactionServiceProvider.java | Java | asf20 | 2,979 |
package com.zyeeda.framework.transaction;
public class TransactionServiceException extends Exception {
private static final long serialVersionUID = -2032004573046150921L;
public TransactionServiceException(Throwable cause) {
super(cause);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/transaction/TransactionServiceException.java | Java | asf20 | 253 |
package com.zyeeda.framework.transaction;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import com.zyeeda.framework.service.Service;
public interface TransactionService extends Service {
public TransactionManager getTransactionManager() throws TransactionServiceException;
public UserTransaction getTransaction() throws TransactionServiceException;
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() throws TransactionServiceException;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/transaction/TransactionService.java | Java | asf20 | 584 |
package com.zyeeda.framework.template;
public class TemplateServiceException extends RuntimeException {
private static final long serialVersionUID = -2569455526509633862L;
public TemplateServiceException(Throwable cause) {
super(cause);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/template/TemplateServiceException.java | Java | asf20 | 251 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.template.internal;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.service.AbstractService;
import com.zyeeda.framework.template.TemplateService;
import com.zyeeda.framework.template.TemplateServiceException;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
/**
* Freemarker template service.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
@ServiceId("freemarker-template-service")
@Marker(Primary.class)
public class FreemarkerTemplateServiceProvider extends AbstractService implements TemplateService {
private static final Logger logger = LoggerFactory.getLogger(FreemarkerTemplateServiceProvider.class);
private static final String TEMPLATE_REPOSITORY_ROOT = "templateRepositoryRoot";
private static final String DATE_FORMAT = "dateFormat";
private static final String TIME_FORMAT = "timeFormat";
private static final String DATETIME_FORMAT = "datetimeFormat";
private static final String DEFAULT_TEMPLATE_REPOSITORY_ROOT = "WEB-INF/templates";
private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private static final String DEFAULT_TIME_FORMAT = "hh:mm:ss";
private static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
// Injected
private ConfigurationService configSvc;
private File repoRoot;
private String dateFormat;
private String timeFormat;
private String datetimeFormat;
private freemarker.template.Configuration config;
public FreemarkerTemplateServiceProvider(
ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) throws Exception {
super(shutdownHub);
this.configSvc = configSvc;
this.init(this.getConfiguration(this.configSvc));
}
private void init(org.apache.commons.configuration.Configuration config) throws Exception {
String repoRoot = config.getString(TEMPLATE_REPOSITORY_ROOT, DEFAULT_TEMPLATE_REPOSITORY_ROOT);
logger.debug("template repository root = {}", repoRoot);
this.repoRoot = new File(this.configSvc.getApplicationRoot(), repoRoot);
if (!this.repoRoot.exists()) {
throw new FileNotFoundException(this.repoRoot.toString());
}
this.dateFormat = config.getString(DATE_FORMAT, DEFAULT_DATE_FORMAT);
this.timeFormat = config.getString(TIME_FORMAT, DEFAULT_TIME_FORMAT);
this.datetimeFormat = config.getString(DATETIME_FORMAT, DEFAULT_DATETIME_FORMAT);
logger.debug("template root = {}", this.repoRoot);
logger.debug("date format = {}", this.dateFormat);
logger.debug("time format = {}", this.timeFormat);
logger.debug("datetime format = {}", this.dateFormat);
}
@Override
public void start() throws Exception {
this.config = new freemarker.template.Configuration();
this.config.setDirectoryForTemplateLoading(this.repoRoot);
this.config.setDefaultEncoding("UTF-8");
this.config.setOutputEncoding("UTF-8");
this.config.setDateFormat(this.dateFormat);
this.config.setTimeFormat(this.timeFormat);
this.config.setDateTimeFormat(this.datetimeFormat);
this.config.setObjectWrapper(new DefaultObjectWrapper());
this.config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
@Override
public void stop() throws Exception {
this.config = null;
this.repoRoot = null;
this.dateFormat = null;
this.timeFormat = null;
this.datetimeFormat = null;
}
@Override
public void paint(String tplPath, Writer out, Map<String, Object> args) throws IOException {
logger.debug("painting template = {}", tplPath);
logger.debug("template varables = {}", args);
Template template = this.config.getTemplate(tplPath);
try {
this.putBuildinVariables(args);
template.process(args, out);
} catch (TemplateException e) {
throw new TemplateServiceException(e);
}
}
@Override
public void paint(String tplPath, Writer out) throws IOException {
Map<String, Object> args = new HashMap<String, Object>();
this.paint(tplPath, out, args);
}
@Override
public String render(String template, Map<String, Object> args) throws IOException {
Reader reader = null;
Writer writer = null;
try {
reader = new StringReader(template);
Template tpl = new Template(null, reader, this.config);
writer = new StringWriter();
this.putBuildinVariables(args);
tpl.process(args, writer);
writer.flush();
return writer.toString();
} catch (TemplateException e) {
throw new TemplateServiceException(e);
} finally {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
}
}
private void putBuildinVariables(Map<String, Object> args) {
args.put("APPLICATION_ROOT", this.configSvc.getApplicationRoot());
args.put("CONTEXT_PATH", this.configSvc.getContextPath());
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/template/internal/FreemarkerTemplateServiceProvider.java | Java | asf20 | 6,499 |
package com.zyeeda.framework.template;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import com.zyeeda.framework.service.Service;
public interface TemplateService extends Service {
public void paint(String tplPath, Writer out, Map<String, Object> args) throws IOException;
public void paint(String tplPath, Writer out) throws IOException;
public String render(String template, Map<String, Object> args) throws IOException;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/template/TemplateService.java | Java | asf20 | 463 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.intfs;
/**
* Interface to handle search result.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public interface SearchHandler<T1, T2> {
public void process(T1 obj) throws Exception;
public T2 getResult();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/intfs/SearchHandler.java | Java | asf20 | 896 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.intfs;
import java.util.Collection;
/**
* Interface to build trees.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public interface TreeNode {
public TreeNode getParent();
public Collection<? extends TreeNode> getChildren();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/intfs/TreeNode.java | Java | asf20 | 919 |
package com.zyeeda.framework.web;
import java.util.Map;
import org.apache.shiro.config.ConfigurationException;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.IniShiroFilter;
import org.apache.tapestry5.ioc.Registry;
import com.zyeeda.framework.security.SecurityService;
import com.zyeeda.framework.utils.IocUtils;
public abstract class SecurityFilter extends IniShiroFilter {
@Override
protected Map<String, ?> applySecurityManager(Ini ini) {
Registry registry = IocUtils.getRegistry(this.getFilterConfig().getServletContext());
SecurityService<?> securitySvc = this.getSecurityService(registry);
SecurityManager securityMgr = (SecurityManager) securitySvc.getSecurityManager();
if (!(securityMgr instanceof WebSecurityManager)) {
String msg = "The configured security manager is not an instance of WebSecurityManager, so " +
"it can not be used with the Shiro servlet filter.";
throw new ConfigurationException(msg);
}
this.setSecurityManager((WebSecurityManager) securitySvc.getSecurityManager());
return null;
}
protected abstract SecurityService<?> getSecurityService(Registry registry);
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/SecurityFilter.java | Java | asf20 | 1,296 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.transaction.UserTransaction;
import org.apache.tapestry5.ioc.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.FrameworkConstants;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.persistence.internal.DefaultPersistenceServiceProvider;
import com.zyeeda.framework.transaction.TransactionService;
import com.zyeeda.framework.transaction.internal.DefaultTransactionServiceProvider;
import com.zyeeda.framework.utils.IocUtils;
/**
* Open session in view servlet filter.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class OpenSessionInViewFilter implements Filter {
private final static Logger logger = LoggerFactory.getLogger(OpenSessionInViewFilter.class);
private FilterConfig config;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Registry reg = (Registry) this.config.getServletContext().getAttribute(FrameworkConstants.SERVICE_REGISTRY);
PersistenceService defaultPersistenceSvc = null;
UserTransaction utx = null;
try {
TransactionService txSvc = reg.getService(IocUtils.getServiceId(DefaultTransactionServiceProvider.class), TransactionService.class);
defaultPersistenceSvc = reg.getService(IocUtils.getServiceId(DefaultPersistenceServiceProvider.class), PersistenceService.class);
utx = txSvc.getTransaction();
logger.debug("tx status before begin = {}", utx.getStatus());
utx.begin();
logger.debug("tx status after begin = {}", utx.getStatus());
defaultPersistenceSvc.openSession();
chain.doFilter(request, response);
logger.debug("tx status before commit = {}", utx.getStatus());
utx.commit();
logger.debug("tx status after commit = {}", utx.getStatus());
} catch (Throwable t) {
try {
if (utx != null) {
logger.debug("tx status before rollback = {}", utx.getStatus());
utx.rollback();
logger.debug("tx status after successfully rollback = {}", utx.getStatus());
}
} catch (Throwable t2) {
logger.error("Cannot rollback transaction.", t2);
}
throw new ServletException(t);
} finally {
if (defaultPersistenceSvc != null) {
defaultPersistenceSvc.closeSession();
}
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/OpenSessionInViewFilter.java | Java | asf20 | 3,683 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.web.mock;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.zyeeda.framework.jpassport.JPassportHttpServletRequest;
/**
* Mock filter for testing {@link com.zyeeda.framework.jpassport.JPassportHttpServletRequest JPassportHttpServletRequest}.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class RemoteUserMockFilter implements Filter {
private static final long serialVersionUID = -4188351109178565968L;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String remoteUser = request.getParameter("remoteUser");
JPassportHttpServletRequest req = new JPassportHttpServletRequest((HttpServletRequest) request);
req.setRemoteUser(remoteUser);
chain.doFilter(req, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/mock/RemoteUserMockFilter.java | Java | asf20 | 1,872 |
package com.zyeeda.framework.web;
import org.apache.tapestry5.ioc.Registry;
import com.zyeeda.framework.security.SecurityService;
import com.zyeeda.framework.security.internal.OpenIdConsumerSecurityServiceProvider;
import com.zyeeda.framework.utils.IocUtils;
public class OpenIdConsumerSecurityFilter extends SecurityFilter {
@Override
protected SecurityService<?> getSecurityService(Registry registry) {
return registry.getService(IocUtils.getServiceId(OpenIdConsumerSecurityServiceProvider.class), SecurityService.class);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/OpenIdConsumerSecurityFilter.java | Java | asf20 | 554 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
/**
* Charactor encoding filter.
* This filter is to fix the encoding problems that are caused by incorrect implementation of Web browsers.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class CharacterEncodingFilter implements Filter {
private String encoding;
private boolean forceEncoding = false;
@Override
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("encoding");
forceEncoding = BooleanUtils.toBoolean(config.getInitParameter("forceEncoding"));
if (StringUtils.isBlank(encoding)) {
this.setEncoding("UTF-8");
}
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
if (this.encoding != null && (this.forceEncoding || StringUtils.isBlank(req.getCharacterEncoding()))) {
req.setCharacterEncoding(encoding);
if (this.forceEncoding) {
res.setCharacterEncoding(this.encoding);
}
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
public void setForceEncoding(boolean forceEncoding) {
this.forceEncoding = forceEncoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/CharacterEncodingFilter.java | Java | asf20 | 2,427 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.web;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.tapestry5.ioc.IOCUtilities;
import org.apache.tapestry5.ioc.Registry;
import org.apache.tapestry5.ioc.RegistryBuilder;
import org.apache.tapestry5.ioc.def.ContributionDef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.FrameworkConstants;
import com.zyeeda.framework.config.internal.ConfigurationServiceContributionDef;
import com.zyeeda.framework.ioc.CustomModuleDef;
/**
* Context listener.
* When the context is initialized, construct and start the server then bind it to JNDI.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class ContextListener implements ServletContextListener {
private final static Logger logger = LoggerFactory.getLogger(ContextListener.class);
private final RegistryBuilder builder = new RegistryBuilder();
@Override
public void contextInitialized(ServletContextEvent event) {
logger.info("context initialized");
try {
ServletContext context = event.getServletContext();
IOCUtilities.addDefaultModules(builder);
ContributionDef contributionDef = new ConfigurationServiceContributionDef(context);
builder.add(new CustomModuleDef(contributionDef));
builder.add(this.provideExtraModules());
Registry registry = builder.build();
context.setAttribute(FrameworkConstants.SERVICE_REGISTRY, registry);
registry.performRegistryStartup();
} catch (Throwable t) {
logger.error("Initialize context failed.", t);
System.exit(1);
}
}
@Override
public void contextDestroyed(ServletContextEvent event) {
logger.info("context destroyed");
try {
ServletContext context = event.getServletContext();
Registry registry = (Registry) context.getAttribute(FrameworkConstants.SERVICE_REGISTRY);
registry.shutdown();
context.removeAttribute(FrameworkConstants.SERVICE_REGISTRY);
} catch (Throwable t) {
logger.error("destroy context failed.", t);
System.exit(1);
}
}
protected Class<?>[] provideExtraModules() {
return new Class<?>[0];
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/ContextListener.java | Java | asf20 | 3,071 |
package com.zyeeda.framework.web;
import java.io.IOException;
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.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.openid.consumer.OpenIdConsumer;
import com.zyeeda.framework.openid.consumer.internal.HttpSessionOpenIdConsumer;
public abstract class OpenIdConsumerServlet extends HttpServlet {
private static final long serialVersionUID = 6393634729613708155L;
private static final Logger logger = LoggerFactory.getLogger(OpenIdConsumerServlet.class);
private static final String OPENID_CONSUMER_KEY = "openid.consumer";
private static final String REDIRECT_TO_URL_KEY = "redirect.to.url";
private static final String RETURN_TO_URL_KEY = "return.to.url";
private static final String PUBLIC_IDENTIFIER_KEY = "public.identifier";
protected static final String OPENID_IDENTIFIER_KEY = "openid.identifier";
private String publicIdentifier;
private String returnToUrl;
private OpenIdConsumer consumer;
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.publicIdentifier = config.getInitParameter(PUBLIC_IDENTIFIER_KEY);
this.returnToUrl = config.getInitParameter(REDIRECT_TO_URL_KEY);
this.consumer = (OpenIdConsumer) this.getServletContext().getAttribute(OPENID_CONSUMER_KEY);
if (this.consumer == null) {
try {
this.consumer = new HttpSessionOpenIdConsumer();
this.consumer.setReturnToUrl(config.getInitParameter(RETURN_TO_URL_KEY));
this.getServletContext().setAttribute(OPENID_CONSUMER_KEY, this.consumer);
} catch (ConsumerException e) {
throw new ServletException(e);
}
}
logger.info("Initialized OpenID Consumer Servlet.");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("servlet path info = {}", request.getPathInfo());
if ("/verify".equals(request.getPathInfo())) {
logger.info("Verify OpenId auth response.");
try {
Identifier id = this.consumer.verifyResponse(request);
if (id == null) {
logger.info("Access denied");
this.onAccessDenied(request, response);
return;
}
logger.info("openid identifier = {}", id.getIdentifier());
this.onAccessGranted(request, response);
return;
} catch (OpenIDException e) {
throw new ServletException(e);
}
}
try {
logger.info("Send OpenId auth request.");
AuthRequest authReq = this.consumer.authRequest(this.publicIdentifier, request, response);
request.setAttribute("message", authReq);
request.getRequestDispatcher(this.returnToUrl).forward(request, response);
} catch (OpenIDException e) {
throw new ServletException(e);
}
}
protected abstract void onAccessGranted(HttpServletRequest request, HttpServletResponse response);
protected abstract void onAccessDenied(HttpServletRequest request, HttpServletResponse response);
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/OpenIdConsumerServlet.java | Java | asf20 | 3,378 |
package com.zyeeda.framework.web.demo;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.web.OpenIdConsumerServlet;
public class DemoOpenIdConsumerServlet extends OpenIdConsumerServlet {
private static final long serialVersionUID = -6625819751410795172L;
private static final Logger logger = LoggerFactory.getLogger(DemoOpenIdConsumerServlet.class);
@Override
protected void onAccessGranted(HttpServletRequest request, HttpServletResponse response) {
try {
response.getWriter().println("OK");
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
@Override
protected void onAccessDenied(HttpServletRequest request, HttpServletResponse response) {
try {
response.getWriter().println("FAILED");
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/demo/DemoOpenIdConsumerServlet.java | Java | asf20 | 1,003 |
package com.zyeeda.framework.web;
import org.apache.tapestry5.ioc.Registry;
import com.zyeeda.framework.security.SecurityService;
import com.zyeeda.framework.security.internal.OpenIdProviderSecurityServiceProvider;
import com.zyeeda.framework.utils.IocUtils;
public class OpenIdProviderSecurityFilter extends SecurityFilter {
@Override
protected SecurityService<?> getSecurityService(Registry registry) {
return registry.getService(IocUtils.getServiceId(OpenIdProviderSecurityServiceProvider.class), SecurityService.class);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/web/OpenIdProviderSecurityFilter.java | Java | asf20 | 554 |
package com.zyeeda.framework;
public class AnnotationException extends RuntimeException {
private static final long serialVersionUID = 3219751360676915317L;
public AnnotationException(String message) {
super(message);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/AnnotationException.java | Java | asf20 | 243 |
package com.zyeeda.framework.sync.internal;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.message.BasicNameValuePair;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.entities.User;
import com.zyeeda.framework.service.AbstractService;
import com.zyeeda.framework.sync.UserSyncService;
import com.zyeeda.framework.utils.DatetimeUtils;
@ServiceId("httpclient-user-sync-service")
@Marker(Primary.class)
public class HttpClientUserSyncServiceProvider extends AbstractService implements UserSyncService {
private static final String SYNC_URLS = "syncUrls";
private static final String NTHREADS = "nThreads";
private static final String SYNC_PERSIST_PATH = "/rest/sync/persist";
private static final String SYNC_UPDATE_PATH = "/rest/sync/update";
private static final String SYNC_ENABLE_PATH = "/rest/sync/enable";
private static final String SYNC_DISABLE_PATH = "/rest/sync/disable";
private String syncUrls = null;
private String[] urls = null;
private Integer nThreads = null;
private ThreadPoolExecutor poolExecutor = null;
public HttpClientUserSyncServiceProvider(
@Primary ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) throws Exception {
super(shutdownHub);
Configuration config = this.getConfiguration(configSvc);
this.init(config);
}
public void init(Configuration config) throws Exception {
this.syncUrls = config.getString(HttpClientUserSyncServiceProvider.SYNC_URLS);
this.urls = StringUtils.split(this.syncUrls, ",");
this.nThreads = Integer.parseInt(config.getString(NTHREADS));
this.poolExecutor = this.getThreadPool();
}
@Override
public void persist(User user) {
if (this.urls.length <= 0) {
return;
}
HttpPost post = null;
HttpEntity entity = null;
try {
entity = this.getUrlEncodedFormEntity(this.buildMap(user));
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
for (String url : this.urls) {
post = new HttpPost(url + SYNC_PERSIST_PATH);
post.setEntity(entity);
this.poolExecutor.execute(new HttpPostTask(post));
}
}
@Override
public void enable(String... ids) {
setVisible(true, ids);
}
@Override
public void disable(String... ids) {
setVisible(false, ids);
}
@Override
public void update(User user) {
if (this.urls.length <= 0) {
return;
}
HttpPut put = null;
HttpEntity entity = null;
try {
entity = this.getUrlEncodedFormEntity(this.buildMap(user));
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
for (String url : this.urls) {
put = new HttpPut(url + SYNC_UPDATE_PATH);
put.setEntity(entity);
this.poolExecutor.execute(new HttpPutTask(put));
}
}
private void setVisible(Boolean visible, String... ids) {
if (this.urls.length <= 0) {
return;
}
HttpPut put = null;
HttpEntity entity = null;
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
StringBuffer buffer = null;
for (String id : ids) {
buffer = new StringBuffer();
buffer.append(StringUtils.substring(id, StringUtils.indexOf(id, "="), StringUtils.indexOf(id, ","))).append(",");
}
if (buffer.length() > 0) {
buffer.deleteCharAt(buffer.lastIndexOf(","));
}
formParams.add(new BasicNameValuePair("id", buffer.toString()));
formParams.add(new BasicNameValuePair("status", visible.toString()));
try {
entity = new UrlEncodedFormEntity(formParams, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String setVisibleUrl = null;
if (visible) {
setVisibleUrl = SYNC_ENABLE_PATH;
} else {
setVisibleUrl = SYNC_DISABLE_PATH;
}
for (String url : this.urls) {
put = new HttpPut(url + setVisibleUrl);
put.setEntity(entity);
this.poolExecutor.execute(new HttpPutTask(put));
}
}
private Map<String, Object> buildMap(Object obj) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Class<?> clazz = obj.getClass();
Method methods[] = clazz.getDeclaredMethods();
Map<String, Object> paramsMap = new HashMap<String, Object>();
for (int i = 0; i < methods.length; i ++) {
if (methods[i].getName().indexOf("get") == 0) {
paramsMap.put(this.getFunctionNameToFieldName(methods[i].getName()), methods[i].invoke(obj, new Object[0]));
}
}
return paramsMap;
}
private String getFunctionNameToFieldName(String functionName) {
StringBuffer buffer = new StringBuffer();
buffer.append(Character.toLowerCase(functionName.charAt("get".length())))
.append(functionName.substring("get".length() + 1, functionName.length()));
return buffer.toString();
}
private UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, Object> paramsMap) {
List<NameValuePair> formParams = new ArrayList<NameValuePair>(paramsMap.size());
for (String key : paramsMap.keySet()) {
if (paramsMap.get(key) instanceof Boolean) {
formParams.add(new BasicNameValuePair(key, paramsMap.get(key).toString()));
} else if (paramsMap.get(key) instanceof String) {
formParams.add(new BasicNameValuePair(key, (String) paramsMap.get(key)));
} else if (paramsMap.get(key) instanceof Date) {
formParams.add(new BasicNameValuePair(key, DatetimeUtils.formatDate((Date) paramsMap.get(key))));
}
}
try {
return new UrlEncodedFormEntity(formParams, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private ThreadPoolExecutor getThreadPool() {
return (ThreadPoolExecutor) Executors.newFixedThreadPool(this.nThreads);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/sync/internal/HttpClientUserSyncServiceProvider.java | Java | asf20 | 6,966 |
package com.zyeeda.framework.sync.internal;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientHelper {
private static Logger logger = (Logger) LoggerFactory.getLogger(HttpClientHelper.class);
public static void sendPostRequest(HttpPost post) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
Integer statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
return;
} else {
printEntityInfo(response);
}
}
public static void sendGetRequest(HttpGet get) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
Integer statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
return;
} else {
printEntityInfo(response);
}
}
public static void sendPutRequest(HttpPut put) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(put);
Integer statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
return;
} else {
printEntityInfo(response);
}
}
public static void sendDeleteRequest(HttpDelete delete) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(delete);
Integer statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
return;
} else {
printEntityInfo(response);
}
}
private static void printEntityInfo(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity != null) {
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
logger.info("response head info:{}", headers[i]);
}
} else {
logger.error("no response info");
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/sync/internal/HttpClientHelper.java | Java | asf20 | 2,594 |
package com.zyeeda.framework.sync.internal;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
public class HttpPutTask implements Runnable {
private HttpPut put = null;
public HttpPutTask() {}
public HttpPutTask(HttpPut put) {
this.put = put;
}
@Override
public void run() {
try {
HttpClientHelper.sendPutRequest(this.put);
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/sync/internal/HttpPutTask.java | Java | asf20 | 604 |
package com.zyeeda.framework.sync.internal;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
public class HttpPostTask implements Runnable {
private HttpPost post = null;
public HttpPostTask() {}
public HttpPostTask(HttpPost post) {
this.post = post;
}
@Override
public void run() {
try {
HttpClientHelper.sendPostRequest(this.post);
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/sync/internal/HttpPostTask.java | Java | asf20 | 617 |
package com.zyeeda.framework.sync;
import com.zyeeda.framework.entities.User;
import com.zyeeda.framework.service.Service;
public interface UserSyncService extends Service {
public void persist(User user);
public void update(User user);
public void enable(String... ids);
public void disable(String... ids);
// public void setVisible(Boolean visible, String... ids);
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/sync/UserSyncService.java | Java | asf20 | 402 |
package com.zyeeda.framework.utils;
import javax.servlet.ServletContext;
import org.apache.tapestry5.ioc.LoggerSource;
import org.apache.tapestry5.ioc.Registry;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.slf4j.Logger;
import com.zyeeda.framework.AnnotationException;
import com.zyeeda.framework.FrameworkConstants;
public class IocUtils {
public static String getServiceId(Class<?> clazz) {
ServiceId svcId = clazz.getAnnotation(ServiceId.class);
if (svcId == null) {
throw new AnnotationException("No [ServiceId] annotation defined.");
}
return svcId.value();
}
public static Logger getLogger(Registry reg, Class<?> clazz) {
LoggerSource loggerSource = reg.getService(LoggerSource.class);
return loggerSource.getLogger(clazz);
}
public static Registry getRegistry(ServletContext ctx) {
return (Registry) ctx.getAttribute(FrameworkConstants.SERVICE_REGISTRY);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/IocUtils.java | Java | asf20 | 921 |
package com.zyeeda.framework.utils;
import javax.naming.ldap.Control;
public class TreeDeleteControlUtils implements Control {
private static final long serialVersionUID = 1L;
@Override
public byte[] getEncodedValue() {
return null;
}
@Override
public String getID() {
return "1.2.840.113556.1.4.805";
}
@Override
public boolean isCritical() {
return Control.CRITICAL;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/TreeDeleteControlUtils.java | Java | asf20 | 423 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.zyeeda.framework.intfs.SearchHandler;
import com.zyeeda.framework.intfs.TreeNode;
/**
* Tree utils.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class TreeUtils {
@SuppressWarnings("unchecked")
public static <NODE extends TreeNode, RESULT> RESULT breadthFirstSearch(
Collection<NODE> nodes, SearchHandler<NODE, RESULT> handler) throws Exception {
List<NODE> cache = new ArrayList<NODE>(nodes);
while (cache.size() > 0) {
NODE node = cache.remove(0);
cache.addAll((Collection<? extends NODE>) node.getChildren());
handler.process(node);
}
return handler.getResult();
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/TreeUtils.java | Java | asf20 | 1,412 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.utils;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* JNDI utils
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*/
public class JndiUtils {
public static Object getObjectFromJndi(String jndi) throws NamingException {
Context initCtx = new InitialContext();
return initCtx.lookup(jndi);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/JndiUtils.java | Java | asf20 | 1,065 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.zyeeda.framework.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Datetime utils.
*
* @author Rui Tang
* @version %I%, %G%
* @since 1.0
*
*/
public class DatetimeUtils {
public static final String DEFAULT_DATE_FORMAT_PATTERN = "yyyy-MM-dd";
public static final String DEFAULT_DATETIME_FORMAT_PATTERN = "yyyy-MM-dd hh:mm:ss";
public static final String GMT_DATETIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ssz";
private static SimpleDateFormat getDefaultDateFormat() {
return new SimpleDateFormat(DEFAULT_DATE_FORMAT_PATTERN);
}
private static SimpleDateFormat getDefaultDatetimeFormat() {
return new SimpleDateFormat(DEFAULT_DATETIME_FORMAT_PATTERN);
}
private static SimpleDateFormat getGMTDatetimeFormat() {
return new SimpleDateFormat(GMT_DATETIME_FORMAT_PATTERN);
}
public static Date parseDate(String str) throws ParseException {
SimpleDateFormat sdf = getDefaultDateFormat();
return sdf.parse(str);
}
public static Date parseDatetime(String str) throws ParseException {
SimpleDateFormat sdf = getDefaultDatetimeFormat();
return sdf.parse(str);
}
public static Date parseGMTDatetime(String str) throws ParseException {
SimpleDateFormat sdf = getGMTDatetimeFormat();
return sdf.parse(str);
}
public static String formatDate(Date date) {
SimpleDateFormat sdf = getDefaultDateFormat();
return sdf.format(date);
}
public static String formatDatetime(Date date) {
SimpleDateFormat sdf = getDefaultDatetimeFormat();
return sdf.format(date);
}
public static String formatGMTDatetime(Date date) {
SimpleDateFormat sdf = getGMTDatetimeFormat();
return sdf.format(date);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/DatetimeUtils.java | Java | asf20 | 2,395 |
package com.zyeeda.framework.utils;
import java.util.Comparator;
import com.zyeeda.framework.viewmodels.MenuVo;
public class MenuListComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
MenuVo menu = (MenuVo)o1;
int flag = 0;
MenuVo menu1 = (MenuVo)o2;
if(menu != null && menu1 != null) {
String menuOrder1 = menu.getOrderBy();
String menuOrder2 = menu.getOrderBy();
if(menuOrder1 != null && menuOrder2 != null){
flag = menu.getOrderBy().compareTo(menu1.getOrderBy());
}
}
return flag;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/MenuListComparator.java | Java | asf20 | 595 |
package com.zyeeda.framework.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
@Deprecated
public class LdapEncryptUtils {
public static String md5Encode(String standardMd5) throws UnsupportedEncodingException {
// String standardMd5 = DigestUtils.md5Hex(password);
byte[] ba = new byte[standardMd5.length() / 2];
for (int i = 0; i < standardMd5.length(); i = i + 2) {
ba[i == 0 ? 0 : i / 2] = (byte) (0xff & Integer.parseInt(
standardMd5.substring(i, i + 2), 16));
}
Base64 base64 = new Base64();
return new String(base64.encode(ba), "UTF-8").trim();
}
@SuppressWarnings("restriction")
public static boolean verifySHA(String ldapPw, String inputPw)
throws NoSuchAlgorithmException {
// MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 取出加密字符
if (ldapPw.startsWith("{SSHA}")) {
ldapPw = ldapPw.substring(6);
} else if (ldapPw.startsWith("{SHA}")) {
ldapPw = ldapPw.substring(5);
}
// 解码BASE64
// byte[] ldapPwByte = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(ldapPw);
byte[] ldapPwByte = Base64.decodeBase64(ldapPw);
byte[] shaCode;
byte[] salt;
// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (ldapPwByte.length <= 20) {
shaCode = ldapPwByte;
salt = new byte[0];
} else {
shaCode = new byte[20];
salt = new byte[ldapPwByte.length - 20];
System.arraycopy(ldapPwByte, 0, shaCode, 0, 20);
System.arraycopy(ldapPwByte, 20, salt, 0, salt.length);
}
// 把用户输入的密码添加到摘要计算信息
md.update(inputPw.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);
// 按SSHA把当前用户密码进行计算
byte[] inputPwByte = md.digest();
// 返回校验结果
return MessageDigest.isEqual(shaCode, inputPwByte);
}
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//e10adc3949ba59abbe56e057f20f883e
System.out.println(DigestUtils.md5Hex("admin"));
System.out.println(verifySHA("{SSHA}6GjgruydvdSc7zNuTKvSSzQgKFDEg/SuE4MqIg==", DigestUtils.md5Hex("111111")));
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/LdapEncryptUtils.java | Java | asf20 | 2,500 |
//package com.zyeeda.framework.utils;
//
//import java.io.UnsupportedEncodingException;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//
//import org.apache.commons.codec.digest.DigestUtils;
////
//import sun.misc.BASE64Encoder;
//
//public class SshaEncrypt {
//
// private static String SecretKey = "test_ssha_key_word";
// private static BASE64Encoder enc = new BASE64Encoder();
// private static SshaEncrypt inst = new SshaEncrypt("SHA-1");
// private MessageDigest sha = null;
//
// public static SshaEncrypt getInstance() {
// return inst;
// }
//
// public SshaEncrypt(String alg) {
// try {
// sha = MessageDigest.getInstance(alg);
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// }
//
// public String createDigest(String entity) {
// return createDigest(SecretKey.getBytes(), entity);
// }
//
// public String createDigest(String salt, String entity) {
// return createDigest(salt.getBytes(), entity);
// }
//
// public String createDigest(byte[] salt, String entity) {
// sha.reset();
// sha.update(entity.getBytes());
// sha.update(salt);
// byte[] pwhash = sha.digest();
// return new String(enc.encode(concatenate(pwhash, salt)));
// }
//
// private static byte[] concatenate(byte[] l, byte[] r) {
// byte[] b = new byte[l.length + r.length];
// System.arraycopy(l, 0, b, 0, l.length);
// System.arraycopy(r, 0, b, l.length, r.length);
// return b;
// }
//
// public static void main(String[] args) throws UnsupportedEncodingException {
// SshaEncrypt ssha = SshaEncrypt.getInstance();
// String ssha_password = ssha.createDigest("123456");
// System.out.println(ssha_password);
// }
//} | zyeeda-framework | core/src/main/java/com/zyeeda/framework/utils/SshaEncrypt.java | Java | asf20 | 1,747 |
package com.zyeeda.framework.config;
import java.io.File;
import org.apache.commons.configuration.Configuration;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.services.RegistryShutdownListener;
import com.zyeeda.framework.service.Service;
public interface ConfigurationService extends Service, RegistryShutdownListener {
Configuration getConfiguration(Resource resource);
File getApplicationRoot();
String getContextPath();
String mapPath(String path);
String getContextParameter(String name);
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/config/ConfigurationService.java | Java | asf20 | 567 |
package com.zyeeda.framework.config.internal;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.ServletContext;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.service.AbstractService;
@ServiceId("default-configuration-service")
@Marker(Primary.class)
public class DefaultConfigurationServiceProvider extends AbstractService implements ConfigurationService {
private ServletContext context;
public DefaultConfigurationServiceProvider(
Collection<ServletContext> contexts, RegistryShutdownHub shutdownHub) {
super(shutdownHub);
if (contexts.size() != 1) {
throw new IllegalStateException("There should be one and only one context.");
}
this.context = contexts.iterator().next();
}
@Override
public Configuration getConfiguration(Resource resource) {
if (resource == null) {
throw new IllegalArgumentException("Argument [resource] should not be null.");
}
if (!resource.exists()) {
throw new RuntimeException(String.format("Resource [%s] not found.", resource.toString()));
}
try {
if (resource.getFile().endsWith(".xml")) {
XMLConfiguration xmlConfig = new XMLConfiguration();
xmlConfig.load(resource.openStream(), "UTF-8");
return xmlConfig;
}
if (resource.getFile().endsWith(".properties")) {
PropertiesConfiguration propConfig = new PropertiesConfiguration();
propConfig.load(resource.openStream(), "UTF-8");
return propConfig;
}
throw new RuntimeException(String.format("Unsupported configuration file type. [%s]", resource.toString()));
} catch (ConfigurationException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public File getApplicationRoot() {
String contextRoot = this.context.getRealPath("/");
return new File(contextRoot);
}
public String getContextPath() {
return this.context.getContextPath();
}
@Override
public String mapPath(String path) {
File f = new File(this.getApplicationRoot(), path);
return f.getAbsolutePath();
}
@Override
public String getContextParameter(String name) {
return this.context.getInitParameter(name);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/config/internal/DefaultConfigurationServiceProvider.java | Java | asf20 | 2,978 |
package com.zyeeda.framework.config.internal;
import javax.servlet.ServletContext;
import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.ModuleBuilderSource;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.ServiceResources;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.def.ContributionDef;
public class ConfigurationServiceContributionDef implements ContributionDef {
private ServletContext context;
public ConfigurationServiceContributionDef(ServletContext context) {
this.context = context;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
Configuration configuration) {
configuration.add(this.context);
}
@Override
@SuppressWarnings("rawtypes")
public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
OrderedConfiguration configuration) {
}
@SuppressWarnings("rawtypes")
@Override
public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
MappedConfiguration configuration) {
}
@Override
public String getServiceId() {
return DefaultConfigurationServiceProvider.class.getAnnotation(ServiceId.class).value();
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/config/internal/ConfigurationServiceContributionDef.java | Java | asf20 | 1,373 |
package com.zyeeda.framework.validation;
public enum ValidationEvent {
PRE_INSERT,
PRE_UPDATE,
PRE_DELETE;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/ValidationEvent.java | Java | asf20 | 116 |
package com.zyeeda.framework.validation.internal;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.service.AbstractService;
import com.zyeeda.framework.validation.ValidationEvent;
import com.zyeeda.framework.validation.ValidationService;
@ServiceId("hibernate-validation-service")
@Marker(Primary.class)
public class HibernateValidationServiceProvider extends AbstractService implements ValidationService {
// Injected
private final PersistenceService persistenceSvc;
private ValidatorFactory preInsertValidatorFactory;
private ValidatorFactory preUpdateValidatorFactory;
private ValidatorFactory preDeleteValidatorFactory;
public HibernateValidationServiceProvider(
@Primary PersistenceService persistenceSvc, RegistryShutdownHub shutdownHub) {
super(shutdownHub);
this.persistenceSvc = persistenceSvc;
}
@Override
public void start() throws Exception {
this.preInsertValidatorFactory = this.getValidatorFactory(ValidationEvent.PRE_INSERT);
this.preUpdateValidatorFactory = this.getValidatorFactory(ValidationEvent.PRE_UPDATE);
this.preDeleteValidatorFactory = this.getValidatorFactory(ValidationEvent.PRE_DELETE);
}
private ValidatorFactory getValidatorFactory(ValidationEvent event) {
HibernateValidatorConfiguration config = Validation.byProvider(HibernateValidator.class).configure();
return config.constraintValidatorFactory(
new CustomConstraintValidatorFactory(this.persistenceSvc, event)).buildValidatorFactory();
}
@Override
public ValidatorFactory getPreInsertValidatorFactory() {
return this.preInsertValidatorFactory;
}
@Override
public ValidatorFactory getPreUpdateValidatorFactory() {
return this.preUpdateValidatorFactory;
}
@Override
public ValidatorFactory getPreDeleteValidatorFactory() {
return this.preDeleteValidatorFactory;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/internal/HibernateValidationServiceProvider.java | Java | asf20 | 2,364 |
package com.zyeeda.framework.validation.internal;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.ValidationException;
import org.hibernate.validator.engine.ConstraintValidatorFactoryImpl;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.validation.ValidationEvent;
public class CustomConstraintValidatorFactory extends ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory {
private final PersistenceService persistenceSvc;
private final ValidationEvent event;
public CustomConstraintValidatorFactory(PersistenceService persistenceSvc, ValidationEvent event) {
this.persistenceSvc = persistenceSvc;
this.event = event;
}
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
if (key.getSuperclass().equals(AbstractConstraintValidator.class)) {
Constructor<T> ctor;
try {
ctor = key.getConstructor(PersistenceService.class, ValidationEvent.class);
T constraintValidator = ctor.newInstance(this.persistenceSvc, this.event);
return constraintValidator;
} catch (SecurityException e) {
throw new ValidationException(e);
} catch (NoSuchMethodException e) {
throw new ValidationException(e);
} catch (IllegalArgumentException e) {
throw new ValidationException(e);
} catch (InstantiationException e) {
throw new ValidationException(e);
} catch (IllegalAccessException e) {
throw new ValidationException(e);
} catch (InvocationTargetException e) {
throw new ValidationException(e);
}
}
return super.getInstance(key);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/internal/CustomConstraintValidatorFactory.java | Java | asf20 | 1,757 |
package com.zyeeda.framework.validation.internal;
import java.lang.annotation.Annotation;
import javax.validation.ConstraintValidator;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.validation.ValidationEvent;
public abstract class AbstractConstraintValidator<A extends Annotation, T> implements ConstraintValidator<A, T> {
// Injected
private final PersistenceService persistenceSvc;
private final ValidationEvent event;
public AbstractConstraintValidator(PersistenceService persistenceSvc, ValidationEvent event) {
this.persistenceSvc = persistenceSvc;
this.event = event;
}
protected PersistenceService getPersistenceService() {
return this.persistenceSvc;
}
protected ValidationEvent getValidationEvent() {
return this.event;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/internal/AbstractConstraintValidator.java | Java | asf20 | 843 |
package com.zyeeda.framework.validation.validators;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.validation.ValidationEvent;
import com.zyeeda.framework.validation.constraints.Unique;
import com.zyeeda.framework.validation.internal.AbstractConstraintValidator;
public class UniqueConstraintValidator extends AbstractConstraintValidator<Unique, Object> {
private final static Logger logger = LoggerFactory.getLogger(UniqueConstraintValidator.class);
private Unique constraint;
public UniqueConstraintValidator(PersistenceService persistenceSvc, ValidationEvent event) {
super(persistenceSvc, event);
}
@Override
public void initialize(Unique constraintAnnotation) {
this.constraint = constraintAnnotation;
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext ctx) {
if (this.getValidationEvent() != this.constraint.event()) {
return true;
}
EntityManager session = this.getPersistenceService().getCurrentSession();
Query query = session.createNamedQuery(this.constraint.namedQuery());
Set<Parameter<?>> params = query.getParameters();
try {
for (Parameter<?> param : params) {
String name = param.getName();
query.setParameter(name, BeanUtils.getNestedProperty(obj, name));
}
int count = query.getMaxResults();
return count == 0;
} catch (NoSuchMethodException e) {
logger.error(e.getMessage(), e);
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
}
return false;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/validators/UniqueConstraintValidator.java | Java | asf20 | 1,947 |
package com.zyeeda.framework.validation.constraints;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import javax.validation.Constraint;
import com.zyeeda.framework.validation.ValidationEvent;
import com.zyeeda.framework.validation.validators.UniqueConstraintValidator;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueConstraintValidator.class)
@Documented
public @interface Unique {
ValidationEvent event() default ValidationEvent.PRE_INSERT;
String namedQuery();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/constraints/Unique.java | Java | asf20 | 677 |