List of usage examples for org.apache.commons.logging Log debug
void debug(Object message);
From source file:com.acc.web.manager.LogManager.java
private void log(Object logTypeObject, Object prefixObject, Object informationObject, LogType logType) { if (!AppLibConstant.isUseLog()) { return;/*w w w. j a v a 2 s . c o m*/ } Log log = logType == LogType.SYSTEMOUT || logType == LogType.FILE ? null : this.getLogger(logTypeObject); String logString = this.getLogString(prefixObject, informationObject); switch (logType) { case SYSTEMOUT: super.systemOut(logString); break; case FILE: super.fileOut(logString); break; case INFO: log.info(logString); break; case WARN: log.warn(logString); break; case DEBUG: log.debug(logString); break; case ERROR: log.error(logString); break; case FATAL: log.fatal(logString); break; } }
From source file:com.curl.orb.servlet.InvokeHttpSessionServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { super.doPost(request, response); Log log = LogFactory.getLog(getClass()); InvokeHttpSessionRequest invokeRequest = (InvokeHttpSessionRequest) InstanceManagementUtil .getRequest(request);//from ww w .ja va2 s.c o m try { String methodName = invokeRequest.getMethodName(); Object[] arguments = invokeRequest.getArguments(); Object returnValue = null; Method method = null; HttpSession session = request.getSession(false); if (invokeRequest.getObjectId() == null) { // static method if (invokeRequest.getClass() == null) throw new InstanceManagementException("Does not exist class name and object id."); String className = invokeRequest.getClassName(); // security Class<?> cls = Class.forName(className); RemoteServiceAnnotationChecker.check(cls, environment); Object[] switchedArguments = switchRemoteObject(arguments, session); method = InstanceManagementUtil.getStaticMethod(cls, methodName, switchedArguments); returnValue = InstanceManagementUtil.invokeStaticMethod(method, cls, switchedArguments); // debug log.debug("Request invoke static method(HttpSession)"); } else { // non static method if (session == null) throw new InstanceManagementException("Does not exist HttpSession."); Object obj = session.getAttribute(invokeRequest.getObjectId()); // security RemoteServiceAnnotationChecker.check(obj.getClass(), environment); Object[] switchedArguments = switchRemoteObject(arguments, session); method = InstanceManagementUtil.getMethod(obj, methodName, switchedArguments); returnValue = InstanceManagementUtil.invokeMethod(method, obj, switchedArguments); // debug log.debug("Request invoke method(HttpSession)"); } InstanceManagementUtil.setResponse(request, returnValue, InstanceManagementUtil.getSurborinateObject(method)); } // IOException, SerializerException, InstanceManagementException ...etc catch (Exception e) { InstanceManagementUtil.setResponse(request, e, null); } }
From source file:com.moss.error_reporting.server.ErrorReportServer.java
public ErrorReportServer(ServerConfiguration config) { final Log log = LogFactory.getLog(this.getClass()); try {/* w w w. j ava 2 s.co m*/ Server jetty = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(config.bindPort()); connector.setHost(config.bindAddress()); jetty.addConnector(connector); boolean initialize = false; if (!config.storageDir().exists() || config.storageDir().listFiles().length == 0) { initialize = true; } log.info("Using storage dir: " + config.storageDir().getAbsolutePath()); DataStore data = new DataStore(config.storageDir(), initialize); ReportingServiceImpl impl = new ReportingServiceImpl(data, new Notifier(config.smtpServer(), config.fromAddress(), config.emailReceipients())); final String path = "/Reporting"; final SwitchingContentHandler handler = new SwitchingContentHandler(path); final boolean jaxwsEnabled = Boolean .parseBoolean(System.getProperty("shell.rpc.jaxws.enabled", "true")); if (jaxwsEnabled) { if (log.isDebugEnabled()) { log.debug( "Constructing JAXWS http content handler RPC impl " + impl.getClass().getSimpleName()); } try { ContentHandler jaxwsHandler = new JAXWSContentHandler(impl); handler.addHandler(jaxwsHandler); } catch (Exception ex) { throw new RuntimeException("Failed to create JAXWS service for " + impl.getClass().getName(), ex); } } if (log.isDebugEnabled()) { log.debug("Constructing Hessian http content handler for RPC impl " + impl.getClass().getSimpleName()); } ContentHandler hessianHandler = new HessianContentHandler(ReportingService.class, impl); handler.addHandler(hessianHandler); jetty.addHandler(handler); jetty.start(); System.out.println("\n\nSERVER READY FOR ACTION\n\n"); } catch (Exception e) { e.printStackTrace(); System.out.println("Unexpected Error. Shutting Down."); System.exit(1); } }
From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java
/** * This returns a keystore as an <code>InputStream</code>. If the keystore * could not be loaded this method returns null. * * @param filename <code>String</code> to read * @param pt <code>PathType</code> how to read file * * @return <code>InputStream</code> keystore */// w ww .ja v a2s. c o m private InputStream getInputStream(final String filename, final PathType pt) { final Log logger = LogFactory.getLog(LdapTLSSocketFactory.class); InputStream is = null; if (pt == PathType.CLASSPATH) { is = LdapTLSSocketFactory.class.getResourceAsStream(filename); } else if (pt == PathType.FILEPATH) { File file; try { file = new File(URI.create(filename)); } catch (IllegalArgumentException e) { file = new File(filename); } try { is = new FileInputStream(file); } catch (IOException e) { if (logger.isWarnEnabled()) { logger.warn("Error loading keystore from " + filename, e); } } } if (is != null) { if (logger.isDebugEnabled()) { logger.debug("Successfully loaded " + filename + " from " + pt); } } else { if (logger.isDebugEnabled()) { logger.debug("Failed to load " + filename + " from " + pt); } } return is; }
From source file:helma.objectmodel.db.Transactor.java
/** * Commit the current transaction, persisting all changes to DB. * * @throws Exception .../*from w ww .j a v a 2s. c o m*/ */ public synchronized void commit() throws Exception { if (killed) { throw new DatabaseException("commit() called on killed transactor thread"); } else if (!active) { return; } int inserted = 0; int updated = 0; int deleted = 0; ArrayList insertedNodes = null; ArrayList updatedNodes = null; ArrayList deletedNodes = null; ArrayList modifiedParentNodes = null; // if nodemanager has listeners collect dirty nodes boolean hasListeners = nmgr.hasNodeChangeListeners(); if (hasListeners) { insertedNodes = new ArrayList(); updatedNodes = new ArrayList(); deletedNodes = new ArrayList(); modifiedParentNodes = new ArrayList(); } if (!dirtyNodes.isEmpty()) { Object[] dirty = dirtyNodes.values().toArray(); // the set to collect DbMappings to be marked as changed HashSet dirtyDbMappings = new HashSet(); Log eventLog = nmgr.app.getEventLog(); for (int i = 0; i < dirty.length; i++) { Node node = (Node) dirty[i]; // update nodes in db int nstate = node.getState(); if (nstate == Node.NEW) { nmgr.insertNode(nmgr.db, txn, node); dirtyDbMappings.add(node.getDbMapping()); node.setState(Node.CLEAN); // register node with nodemanager cache nmgr.registerNode(node); if (hasListeners) { insertedNodes.add(node); } inserted++; if (eventLog.isDebugEnabled()) { eventLog.debug("inserted node: " + node.getPrototype() + "/" + node.getID()); } } else if (nstate == Node.MODIFIED) { // only mark DbMapping as dirty if updateNode returns true if (nmgr.updateNode(nmgr.db, txn, node)) { dirtyDbMappings.add(node.getDbMapping()); } node.setState(Node.CLEAN); // update node with nodemanager cache nmgr.registerNode(node); if (hasListeners) { updatedNodes.add(node); } updated++; if (eventLog.isDebugEnabled()) { eventLog.debug("updated node: " + node.getPrototype() + "/" + node.getID()); } } else if (nstate == Node.DELETED) { nmgr.deleteNode(nmgr.db, txn, node); dirtyDbMappings.add(node.getDbMapping()); // remove node from nodemanager cache nmgr.evictNode(node); if (hasListeners) { deletedNodes.add(node); } deleted++; if (eventLog.isDebugEnabled()) { eventLog.debug("removed node: " + node.getPrototype() + "/" + node.getID()); } } node.clearWriteLock(); } // set last data change times in db-mappings // long now = System.currentTimeMillis(); for (Iterator i = dirtyDbMappings.iterator(); i.hasNext();) { DbMapping dbm = (DbMapping) i.next(); if (dbm != null) { dbm.setLastDataChange(); } } } long now = System.currentTimeMillis(); if (!parentNodes.isEmpty()) { // set last subnode change times in parent nodes for (Iterator i = parentNodes.iterator(); i.hasNext();) { Node node = (Node) i.next(); node.markSubnodesChanged(); if (hasListeners) { modifiedParentNodes.add(node); } } } if (hasListeners) { nmgr.fireNodeChangeEvent(insertedNodes, updatedNodes, deletedNodes, modifiedParentNodes); } // clear the node collections recycle(); if (active) { active = false; nmgr.db.commitTransaction(txn); txn = null; } StringBuffer msg = new StringBuffer(tname).append(" done in ").append(now - tstart).append(" millis"); if (inserted + updated + deleted > 0) { msg.append(" [+").append(inserted).append(", ~").append(updated).append(", -").append(deleted) .append("]"); } nmgr.app.logAccess(msg.toString()); // unset transaction name tname = null; }
From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java
/** * Initializes this FileSystemHotBeanModuleRepository. *///from w ww .j a v a 2s.c om public void init() throws Exception { synchronized (super.getLock()) { if (!initialized) { Log logger = this.getLog(); if (this.moduleRepositoryDirectory == null) this.moduleRepositoryDirectory = new File("hotModules"); if (this.temporaryDirectory == null) this.temporaryDirectory = new File(this.moduleRepositoryDirectory, "temp"); this.moduleRepositoryDirectory.mkdirs(); this.temporaryDirectory.mkdirs(); // Delete temporary directory on start up FileDeletor.delete(this.temporaryDirectory); if (logger.isDebugEnabled()) logger.debug("Initializing FileSystemHotBeanModuleRepository - moduleRepositoryDirectory: " + this.moduleRepositoryDirectory + ", temporaryDirectory: " + this.temporaryDirectory + "."); RepositoryFileLock fileLock = null; try { fileLock = this.obtainRepositoryFileLock(false); } catch (Exception e) { logger.error("Error obtaining repository file lock on init!", e); } finally { this.releaseRepositoryFileLock(fileLock); fileLock = null; } super.init(); initialized = true; } } }
From source file:helma.framework.core.RequestEvaluator.java
/** * *//*w ww .j ava 2 s.c o m*/ public void run() { // first, set a local variable to the current transactor thread so we know // when it's time to quit because another thread took over. Thread localThread = Thread.currentThread(); // spans whole execution loop - close connections in finally clause try { // while this thread is serving requests while (localThread == thread) { // object reference to ressolve request path Object currentElement; // Get req and res into local variables to avoid memory caching problems // in unsynchronized method. RequestTrans req = getRequest(); ResponseTrans res = getResponse(); // request path object RequestPath requestPath = new RequestPath(app); String txname = req.getMethod() + ":" + req.getPath(); Log eventLog = app.getEventLog(); if (eventLog.isDebugEnabled()) { eventLog.debug(txname + " starting"); } int tries = 0; boolean done = false; Throwable error = null; String functionName = function instanceof String ? (String) function : null; while (!done && localThread == thread) { // catch errors in path resolution and script execution try { // initialize scripting engine initScriptingEngine(); app.setCurrentRequestEvaluator(this); // update scripting prototypes scriptingEngine.enterContext(); // avoid going into transaction if called function doesn't exist. // this only works for the (common) case that method is a plain // method name, not an obj.method path if (reqtype == INTERNAL) { // if object is an instance of NodeHandle, get the node object itself. if (thisObject instanceof NodeHandle) { thisObject = ((NodeHandle) thisObject).getNode(app.nmgr.safe); // If no valid node object return immediately if (thisObject == null) { done = true; reqtype = NONE; break; } } // If function doesn't exist, return immediately if (functionName != null && !scriptingEngine.hasFunction(thisObject, functionName, true)) { app.logEvent(missingFunctionMessage(thisObject, functionName)); done = true; reqtype = NONE; break; } } else if (function != null && functionName == null) { // only internal requests may pass a function instead of a function name throw new IllegalStateException("No function name in non-internal request "); } // Update transaction name in case we're processing an error if (error != null) { txname = "error:" + txname; } // begin transaction transactor = Transactor.getInstance(app.nmgr); transactor.begin(txname); Object root = app.getDataRoot(scriptingEngine); initGlobals(root, requestPath); String action = null; if (error != null) { res.setError(error); } switch (reqtype) { case HTTP: // bring over the message from a redirect session.recoverResponseMessages(res); // catch redirect in path resolution or script execution try { // catch object not found in path resolution try { if (error != null) { // there was an error in the previous loop, call error handler currentElement = root; res.setStatus(500); // do not reset the requestPath so error handler can use the original one // get error handler action String errorAction = app.props.getProperty("error", "error"); action = getAction(currentElement, errorAction, req); if (action == null) { throw new RuntimeException(error); } } else if ((req.getPath() == null) || "".equals(req.getPath().trim())) { currentElement = root; requestPath.add(null, currentElement); action = getAction(currentElement, null, req); if (action == null) { throw new NotFoundException("Action not found"); } } else { // march down request path... StringTokenizer st = new StringTokenizer(req.getPath(), "/"); int ntokens = st.countTokens(); // limit path to < 50 tokens if (ntokens > 50) { throw new RuntimeException("Path too long"); } String[] pathItems = new String[ntokens]; for (int i = 0; i < ntokens; i++) pathItems[i] = st.nextToken(); currentElement = root; requestPath.add(null, currentElement); for (int i = 0; i < ntokens; i++) { if (currentElement == null) { throw new NotFoundException("Object not found."); } if (pathItems[i].length() == 0) { continue; } // if we're at the last element of the path, // try to interpret it as action name. if (i == (ntokens - 1) && !req.getPath().endsWith("/")) { action = getAction(currentElement, pathItems[i], req); } if (action == null) { currentElement = getChildElement(currentElement, pathItems[i]); // add object to request path if suitable if (currentElement != null) { // add to requestPath array requestPath.add(pathItems[i], currentElement); } } } if (currentElement == null) { throw new NotFoundException("Object not found."); } if (action == null) { action = getAction(currentElement, null, req); } if (action == null) { throw new NotFoundException("Action not found"); } } } catch (NotFoundException notfound) { if (error != null) { // we already have an error and the error template wasn't found, // display it instead of notfound message throw new RuntimeException(); } // The path could not be resolved. Check if there is a "not found" action // specified in the property file. res.setStatus(404); String notFoundAction = app.props.getProperty("notfound", "notfound"); currentElement = root; action = getAction(currentElement, notFoundAction, req); if (action == null) { throw new NotFoundException(notfound.getMessage()); } } // register path objects with their prototype names in // res.handlers Map macroHandlers = res.getMacroHandlers(); int l = requestPath.size(); Prototype[] protos = new Prototype[l]; for (int i = 0; i < l; i++) { Object obj = requestPath.get(i); protos[i] = app.getPrototype(obj); // immediately register objects with their direct prototype name if (protos[i] != null) { macroHandlers.put(protos[i].getName(), obj); macroHandlers.put(protos[i].getLowerCaseName(), obj); } } // in a second pass, we register path objects with their indirect // (i.e. parent prototype) names, starting at the end and only // if the name isn't occupied yet. for (int i = l - 1; i >= 0; i--) { if (protos[i] != null) { protos[i].registerParents(macroHandlers, requestPath.get(i)); } } ///////////////////////////////////////////////////////////////////////////// // end of path resolution section ///////////////////////////////////////////////////////////////////////////// // beginning of execution section // set the req.action property, cutting off the _action suffix req.setAction(action); // reset skin recursion detection counter skinDepth = 0; // try calling onRequest() function on object before // calling the actual action scriptingEngine.invoke(currentElement, "onRequest", EMPTY_ARGS, ScriptingEngine.ARGS_WRAP_DEFAULT, false); // reset skin recursion detection counter skinDepth = 0; Object actionProcessor = req.getActionHandler() != null ? req.getActionHandler() : action; // do the actual action invocation if (req.isXmlRpc()) { XmlRpcRequestProcessor xreqproc = new XmlRpcRequestProcessor(); XmlRpcServerRequest xreq = xreqproc .decodeRequest(req.getServletRequest().getInputStream()); Vector args = xreq.getParameters(); args.add(0, xreq.getMethodName()); result = scriptingEngine.invoke(currentElement, actionProcessor, args.toArray(), ScriptingEngine.ARGS_WRAP_XMLRPC, false); res.writeXmlRpcResponse(result); app.xmlrpcCount += 1; } else { scriptingEngine.invoke(currentElement, actionProcessor, EMPTY_ARGS, ScriptingEngine.ARGS_WRAP_DEFAULT, false); } // try calling onResponse() function on object before // calling the actual action scriptingEngine.invoke(currentElement, "onResponse", EMPTY_ARGS, ScriptingEngine.ARGS_WRAP_DEFAULT, false); } catch (RedirectException redirect) { // if there is a message set, save it on the user object for the next request if (res.getRedirect() != null) session.storeResponseMessages(res); } // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } commitTransaction(); done = true; break; case XMLRPC: case EXTERNAL: try { currentElement = root; if (functionName.indexOf('.') > -1) { StringTokenizer st = new StringTokenizer(functionName, "."); int cnt = st.countTokens(); for (int i = 1; i < cnt; i++) { String next = st.nextToken(); currentElement = getChildElement(currentElement, next); } if (currentElement == null) { throw new NotFoundException( "Method name \"" + function + "\" could not be resolved."); } functionName = st.nextToken(); } if (reqtype == XMLRPC) { // check XML-RPC access permissions String proto = app.getPrototypeName(currentElement); app.checkXmlRpcAccess(proto, functionName); } // reset skin recursion detection counter skinDepth = 0; if (!scriptingEngine.hasFunction(currentElement, functionName, false)) { throw new NotFoundException( missingFunctionMessage(currentElement, functionName)); } result = scriptingEngine.invoke(currentElement, functionName, args, ScriptingEngine.ARGS_WRAP_XMLRPC, false); // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } commitTransaction(); } catch (Exception x) { // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } abortTransaction(); app.logError(txname + " " + error, x); // If the transactor thread has been killed by the invoker thread we don't have to // bother for the error message, just quit. if (localThread != thread) { return; } this.exception = x; } done = true; break; case INTERNAL: try { // reset skin recursion detection counter skinDepth = 0; result = scriptingEngine.invoke(thisObject, function, args, ScriptingEngine.ARGS_WRAP_DEFAULT, true); // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } commitTransaction(); } catch (Exception x) { // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } abortTransaction(); app.logError(txname + " " + error, x); // If the transactor thread has been killed by the invoker thread we don't have to // bother for the error message, just quit. if (localThread != thread) { return; } this.exception = x; } done = true; break; } // switch (reqtype) } catch (AbortException x) { // res.abort() just aborts the transaction and // leaves the response untouched // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } abortTransaction(); done = true; } catch (ConcurrencyException x) { res.reset(); if (++tries < 8) { // try again after waiting some period // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } abortTransaction(); try { // wait a bit longer with each try int base = 800 * tries; Thread.sleep((long) (base + (Math.random() * base * 2))); } catch (InterruptedException interrupt) { // we got interrrupted, create minimal error message res.reportError(interrupt); done = true; // and release resources and thread thread = null; transactor = null; } } else { // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } abortTransaction(); // error in error action. use traditional minimal error message res.reportError("Application too busy, please try again later"); done = true; } } catch (Throwable x) { // check if request is still valid, or if the requesting thread has stopped waiting already if (localThread != thread) { return; } abortTransaction(); // If the transactor thread has been killed by the invoker thread we don't have to // bother for the error message, just quit. if (localThread != thread) { return; } res.reset(); // check if we tried to process the error already, // or if this is an XML-RPC request if (error == null) { if (!(x instanceof NotFoundException)) { app.errorCount += 1; } // set done to false so that the error will be processed done = false; error = x; app.logError(txname + " " + error, x); if (req.isXmlRpc()) { // if it's an XML-RPC exception immediately generate error response if (!(x instanceof Exception)) { // we need an exception to pass to XML-RPC responder x = new Exception(x.toString(), x); } res.writeXmlRpcError((Exception) x); done = true; } } else { // error in error action. use traditional minimal error message res.reportError(error); done = true; } } finally { app.setCurrentRequestEvaluator(null); // exit execution context if (scriptingEngine != null) { try { scriptingEngine.exitContext(); } catch (Throwable t) { // broken rhino, just get out of here } } } } notifyAndWait(); } } finally { Transactor tx = Transactor.getInstance(); if (tx != null) tx.closeConnections(); } }
From source file:com.googlecode.jcimd.PacketSerializer.java
private static Packet doDeserializePacket(InputStream inputStream, int maxMessageSize, boolean useChecksum, Log logger) throws IOException { ByteArrayOutputStream temp = new ByteArrayOutputStream(); int b;//from w w w . j a v a 2s . c om while ((b = inputStream.read()) != END_OF_STREAM) { // Any data transmitted between packets SHALL be ignored. if (b == STX) { temp.write(b); break; } } if (b != STX) { //throw new SoftEndOfStreamException(); throw new IOException("End of stream reached and still no <STX> byte"); } // Read the input stream until ETX while ((b = inputStream.read()) != END_OF_STREAM) { temp.write(b); if (b == ETX) { break; } if (temp.size() >= maxMessageSize) { // Protect from buffer overflow throw new IOException( "Buffer overflow reached at " + temp.size() + " byte(s) and still no <ETX> byte"); } } if (b != ETX) { throw new IOException("End of stream reached and still no <ETX> byte"); } // Parse contents of "temp" (it contains the entire CIMD message // including STX and ETX bytes). byte bytes[] = temp.toByteArray(); if (logger.isTraceEnabled()) { logger.trace("Received " + bytes.length + " byte(s)"); } if (useChecksum) { // Read two (2) bytes, just before the ETX byte. StringBuilder buffer = new StringBuilder(2); buffer.append((char) bytes[bytes.length - 3]); buffer.append((char) bytes[bytes.length - 2]); try { int checksum = Integer.valueOf(buffer.toString(), 16); int expectedChecksum = calculateCheckSum(bytes, 0, bytes.length - 3); if (checksum != expectedChecksum) { throw new IOException("Checksum error: expecting " + expectedChecksum + " but got " + checksum); } } catch (NumberFormatException e) { throw new IOException("Checksum error: expecting HEX digits, but got " + buffer); } } // Deserialize bytes, minus STX, CC (check sum), and ETX. int end = useChecksum ? bytes.length - 3 : bytes.length - 1; Packet packet = deserializeFromByteArray(bytes, 1, end); if (logger.isDebugEnabled()) { logger.debug("Received " + packet); } return packet; }
From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java
/** * Internal method to update a module.//from ww w. j ava2 s .c om */ protected HotBeanModuleInfo updateModuleInternal(String moduleName, final InputStream moduleFileStream, final boolean add) { long revisionNumber = -1; HotBeanModuleInfo hotBeanModuleInfo = null; Log logger = this.getLog(); synchronized (super.getLock()) { // If update - module name must be specified if (!add && ((moduleName == null) || (moduleName.trim().length() == 0))) throw new HotBeansException("Module name not specified!"); RepositoryFileLock fileLock = null; File moduleTempFile = null; InputStream moduleTempFileStream = null; try { // Save module file to temp file moduleTempFile = File.createTempFile("hotBeanModule", ".jar"); FileCopyUtils.copy(moduleFileStream, new FileOutputStream(moduleTempFile)); // Get name from mainfest Manifest manifest = ModuleManifestUtils.readManifest(moduleTempFile); String jarFileModuleName = ModuleManifestUtils.getName(manifest); if (logger.isDebugEnabled()) logger.debug("Module name in module manifest: '" + jarFileModuleName + "'."); // Validate name if (add) { if ((jarFileModuleName == null) || (jarFileModuleName.trim().length() == 0)) throw new InvalidModuleNameException("Module name not specified!"); else if (super.getHotBeanModule(jarFileModuleName) != null) throw new ModuleAlreadyExistsException("Module name already exists!"); } else if (!moduleName.equals(jarFileModuleName)) throw new InvalidModuleNameException( "Module name in jar file doesn't match specified module name!"); moduleName = jarFileModuleName; moduleTempFileStream = new FileInputStream(moduleTempFile); if (add & logger.isInfoEnabled()) logger.info("Adding module '" + moduleName + "'."); fileLock = this.obtainRepositoryFileLock(false); // Obtain lock File moduleDirectory = new File(this.moduleRepositoryDirectory, moduleName); if (!moduleDirectory.exists()) moduleDirectory.mkdirs(); // Get next revision number revisionNumber = this.getLastRevisionOnFileSystem(moduleName); if (logger.isDebugEnabled()) { if (add) logger.debug("Adding module - last revision on file system: " + revisionNumber + "."); else logger.debug("Updating module - last revision on file system: " + revisionNumber + "."); } if (revisionNumber < 0) revisionNumber = 0; File moduleFile = new File(moduleDirectory, revisionNumber + MODULE_FILE_SUFFIX); while (moduleFile.exists()) // This should't really be necessary, but still... { revisionNumber++; moduleFile = new File(moduleDirectory, revisionNumber + MODULE_FILE_SUFFIX); } if (logger.isDebugEnabled()) { if (add) logger.debug("Adding module - revision of new module: " + revisionNumber + "."); else logger.debug("Updating module - revision of new module: " + revisionNumber + "."); } // Save module file FileCopyUtils.copy(moduleTempFileStream, new FileOutputStream(moduleFile)); // Deploy at once hotBeanModuleInfo = this.loadModule(moduleName, revisionNumber); } catch (Exception e) { String moduleNameString = ""; if (moduleName != null) moduleNameString = "'" + moduleName + "' "; if (add) { logger.error("Error adding module " + moduleNameString + "- " + e, e); if (e instanceof HotBeansException) throw (HotBeansException) e; else throw new HotBeansException("Error adding module " + moduleNameString + "- " + e, e); } else { logger.error("Error updating module " + moduleNameString + "- " + e, e); if (e instanceof HotBeansException) throw (HotBeansException) e; else throw new HotBeansException("Error updating module " + moduleNameString + "- " + e, e); } } finally { this.releaseRepositoryFileLock(fileLock); fileLock = null; if (moduleTempFileStream != null) { // Delete temp file try { moduleTempFileStream.close(); } catch (Exception e) { } } if (moduleTempFile != null) FileDeletor.delete(moduleTempFile); } } return hotBeanModuleInfo; }
From source file:com.dhcc.framework.web.context.DhccContextLoader.java
/** * Initialize Spring's web application context for the given servlet context, * using the application context provided at construction time, or creating a new one * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params. * @param servletContext current servlet context * @return the new WebApplicationContext * @see #ContextLoader(WebApplicationContext) * @see #CONTEXT_CLASS_PARAM// w w w. ja v a 2 s . co m * @see #CONFIG_LOCATION_PARAM */ public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(DhccContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == DhccContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }