List of usage examples for java.lang NoClassDefFoundError getMessage
public String getMessage()
From source file:com.xpn.xwiki.render.macro.rss.RSSMacro.java
/** * Transform the input parameters into <code>RSSMacroParameters</code> object. * /*from w w w . ja va 2s . c o m*/ * @param parameter the parameters as prepared by the Radeox system. * @throws java.lang.IllegalArgumentException if the 'feed' named parameter is missing, or is a malformed URL, or if * any of the other parameter values are not of the correct types. Note that unknown parameters will * simply be ignored, and all parameters must be passed using names. * @return a parameters helper object * @see RSSMacroParameters */ private RSSMacroParameters processParameters(MacroParameter parameter) throws java.lang.IllegalArgumentException { Map<String, String> paramMap = new HashMap<String, String>(); RSSMacroParameters paramObj = new RSSMacroParameters(); String feedURLString = parameter.get("feed"); if (feedURLString == null) { throw new IllegalArgumentException( "Requires at least one named parameter,'feed', a URL of an RSS feed."); } try { paramObj.setFeed(feedURLString); } catch (MalformedURLException ex) { Logger.warn("Invalid feed URL: " + feedURLString); throw new IllegalArgumentException("Invalid feed URL: " + feedURLString); } for (int i = 0; i < PARAM_NAMES.length; i++) { String paramName = parameter.get(PARAM_NAMES[i]); if (paramName != null) { paramMap.put(PARAM_NAMES[i], paramName); } } try { BeanUtils.populate(paramObj, paramMap); } catch (NoClassDefFoundError e) { throw new IllegalStateException("Some libraries are not installed: " + e.getMessage()); } catch (Exception ex) { throw new IllegalArgumentException("Error processing arguments: " + ex.getMessage()); } return paramObj; }
From source file:de.jwic.base.JWicRuntime.java
/** * Setup the JWicRuntime from the jwic-setup.xml file. The setup * defines the available renderer and global settings. * @param in/*from www .j a va 2 s . c o m*/ */ public void setupRuntime(InputStream stream) { try { SAXReader reader = new SAXReader(); reader.setEntityResolver(new DTDEntityResolver(DTD_PUBLICID, DTD_SYSTEMID, DTD_RESOURCEPATH)); reader.setIncludeExternalDTDDeclarations(false); Document document = reader.read(stream); readDocument(document); sessionManager = new SessionManager(getSavePath()); sessionManager.setStoreTime(sessionStoreTime); } catch (NoClassDefFoundError ncdfe) { if (ncdfe.getMessage().indexOf("dom4j") != -1) { log.error("Can not read jwic-setup.xml: the dom4j library is not in the classpath."); throw new RuntimeException( "Can not read jwic-setup.xml: the dom4j library is not in the classpath.", ncdfe); } log.error("Error reading jwic-setup.xml.", ncdfe); throw new RuntimeException("Error reading jwic-setup.xml: " + ncdfe, ncdfe); } catch (Exception e) { throw new RuntimeException("Error reading jwic-setup.xml: " + e, e); } }
From source file:org.exoplatform.services.cms.scripts.impl.ScriptServiceImpl.java
/** * {@inheritDoc}//from w ww . ja v a 2 s. c o m */ @Override public synchronized CmsScript getScript(String scriptName) throws Exception { CmsScript scriptObject = resourceCache_.get(scriptName); if (scriptObject != null) return scriptObject; ExoContainer container = ExoContainerContext.getCurrentContainer(); try { scriptObject = (CmsScript) container.getComponentInstance(scriptName); if (scriptObject != null) { resourceCache_.put(scriptName, scriptObject); return scriptObject; } } catch (NoClassDefFoundError e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } groovyClassLoader_ = createGroovyClassLoader(); Class scriptClass = groovyClassLoader_.loadClass(scriptName); container.registerComponentImplementation(scriptName, scriptClass); scriptObject = (CmsScript) container.getComponentInstance(scriptName); resourceCache_.put(scriptName, scriptObject); return scriptObject; }
From source file:org.apache.axis.client.HappyClient.java
/** * probe for a class, print an error message is missing * @param category text like "warning" or "error" * @param classname class to look for/*from www .j a va2s .c om*/ * @param jarFile where this class comes from * @param errorText extra error text * @param homePage where to d/l the library * @return the number of missing classes * @throws java.io.IOException */ int probeClass(String category, String classname, String jarFile, String description, String errorText, String homePage) throws IOException { String url = ""; if (homePage != null) { url = Messages.getMessage("happyClientHomepage", homePage); } String errorLine = ""; if (errorText != null) { errorLine = Messages.getMessage(errorText); } try { Class clazz = classExists(classname); if (clazz == null) { String text; text = Messages.getMessage("happyClientMissingClass", category, classname, jarFile); out.println(text); out.println(url); return 1; } else { String location = getLocation(clazz); String text; if (location == null) { text = Messages.getMessage("happyClientFoundDescriptionClass", description, classname); } else { text = Messages.getMessage("happyClientFoundDescriptionClassLocation", description, classname, location); } out.println(text); return 0; } } catch (NoClassDefFoundError ncdfe) { out.println(Messages.getMessage("happyClientNoDependency", category, classname, jarFile)); out.println(errorLine); out.println(url); out.println(ncdfe.getMessage()); return 1; } }
From source file:com.chiorichan.event.EventBus.java
public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener, final EventCreator plugin) { Validate.notNull(plugin, "Creator can not be null"); Validate.notNull(listener, "Listener can not be null"); Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>(); Set<Method> methods; try {/*ww w. j a va 2s .com*/ Method[] publicMethods = listener.getClass().getMethods(); methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE); for (Method method : publicMethods) { methods.add(method); } for (Method method : listener.getClass().getDeclaredMethods()) { methods.add(method); } } catch (NoClassDefFoundError e) { Loader.getLogger() .severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist."); return ret; } for (final Method method : methods) { final EventHandler eh = method.getAnnotation(EventHandler.class); if (eh == null) continue; final Class<?> checkClass; if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) { Loader.getLogger() .severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass()); continue; } final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class); method.setAccessible(true); Set<RegisteredListener> eventSet = ret.get(eventClass); if (eventSet == null) { eventSet = new HashSet<RegisteredListener>(); ret.put(eventClass, eventSet); } for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { // This loop checks for extending deprecated events if (clazz.getAnnotation(Deprecated.class) != null) { Warning warning = clazz.getAnnotation(Warning.class); WarningState warningState = Loader.getInstance().getWarningState(); if (!warningState.printFor(warning)) { break; } Loader.getLogger().log(Level.WARNING, String.format( "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." + " \"%s\"; please notify the authors %s.", plugin.getDescription().getFullName(), clazz.getName(), method.toGenericString(), (warning != null && warning.reason().length() != 0) ? warning.reason() : "Server performance will be affected", Arrays.toString(plugin.getDescription().getAuthors().toArray())), warningState == WarningState.ON ? new AuthorNagException(null) : null); break; } } EventExecutor executor = new EventExecutor() { public void execute(Listener listener, Event event) throws EventException { try { if (!eventClass.isAssignableFrom(event.getClass())) { return; } method.invoke(listener, event); } catch (InvocationTargetException ex) { throw new EventException(ex.getCause()); } catch (Throwable t) { throw new EventException(t); } } }; if (useTimings) { eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); } else { eventSet.add( new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); } } return ret; }
From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java
public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener, final Plugin plugin) { Validate.notNull(plugin, "Plugin can not be null"); Validate.notNull(listener, "Listener can not be null"); boolean useTimings = Loader.getEventBus().useTimings(); Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>(); Set<Method> methods; try {/*ww w .jav a 2 s. c o m*/ Method[] publicMethods = listener.getClass().getMethods(); methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE); for (Method method : publicMethods) { methods.add(method); } for (Method method : listener.getClass().getDeclaredMethods()) { methods.add(method); } } catch (NoClassDefFoundError e) { PluginManager.getLogger() .severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist."); return ret; } for (final Method method : methods) { final EventHandler eh = method.getAnnotation(EventHandler.class); if (eh == null) continue; final Class<?> checkClass; if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) { PluginManager.getLogger() .severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass()); continue; } final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class); method.setAccessible(true); Set<RegisteredListener> eventSet = ret.get(eventClass); if (eventSet == null) { eventSet = new HashSet<RegisteredListener>(); ret.put(eventClass, eventSet); } for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { // This loop checks for extending deprecated events if (clazz.getAnnotation(Deprecated.class) != null) { Warning warning = clazz.getAnnotation(Warning.class); WarningState warningState = Loader.getInstance().getWarningState(); if (!warningState.printFor(warning)) { break; } PluginManager.getLogger().log(Level.WARNING, String.format( "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." + " \"%s\"; please notify the authors %s.", plugin.getDescription().getFullName(), clazz.getName(), method.toGenericString(), (warning != null && warning.reason().length() != 0) ? warning.reason() : "Server performance will be affected", Arrays.toString(plugin.getDescription().getAuthors().toArray())), warningState == WarningState.ON ? new AuthorNagException(null) : null); break; } } EventExecutor executor = new EventExecutor() { public void execute(Listener listener, Event event) throws EventException { try { if (!eventClass.isAssignableFrom(event.getClass())) { return; } method.invoke(listener, event); } catch (InvocationTargetException ex) { throw new EventException(ex.getCause()); } catch (Throwable t) { throw new EventException(t); } } }; if (useTimings) { eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); } else { eventSet.add( new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); } } return ret; }
From source file:com.seer.datacruncher.services.ServiceScheduledJob.java
@Override protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException { long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); JobsEntity jobEntity = jobsDao.find(jobId); if (!jobEntity.isWorking()) { if (jobsDao.setWorkStatus(jobId, true)) { try { long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null ? -1l// w w w . j av a2s. c o m : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId")); if (eventTriggerId > 0) { EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId); String className = entity.getName(); try { String sourceCode = entity.getCode(); EventTrigger eventTrigger; String response; eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className, "com.seer.datacruncher.eventtrigger.EventTrigger", EventTrigger.class, sourceCode); assert eventTrigger != null; response = eventTrigger.trigger(); log.info("Response From EventTrigger(" + className + ") :" + response); } catch (Exception e) { e.printStackTrace(); log.error("EventTrigger(" + className + ") :" + e.getMessage(), e); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage()); } catch (NoClassDefFoundError err) { log.error("EventTrigger(" + className + ") :" + err.getMessage(), err); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage()); } return; } int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day")); int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month")); if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) { return; } StandardFileSystemManager fsManager = new StandardFileSystemManager(); boolean isDataStream = true; try { fsManager.init(); long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId"); long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId"); //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId"); String datastream = ""; int idSchemaType = schemasDao.find(schemaId).getIdSchemaType(); TasksEntity taskEntity = tasksDao.find(schedulerId); //JobsEntity jobEntity = jobsDao.find(jobId); if (taskEntity.getIsOneShoot()) { jobEntity.setIsActive(0); jobsDao.update(jobEntity); } if (idSchemaType == SchemaType.GENERATION) { StreamGenerationUtils sgu = new StreamGenerationUtils(); datastream = sgu.getStream(schemaId); log.debug("Content stream: " + schemaId); if (datastream.trim().length() > 0) { log.debug("Datastream to validate: " + datastream); DatastreamsInput datastreamsInput = new DatastreamsInput(); String result = datastreamsInput.datastreamsInput(datastream, schemaId, null); log.debug("Validation result: " + result); } else { isDataStream = false; log.debug("No datastream create"); } } if (connectionId != 0) { int serviceId = Integer .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId")); String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp"); String port = arg0.getJobDetail().getJobDataMap().getString("port"); String userName = arg0.getJobDetail().getJobDataMap().getString("userName"); String password = arg0.getJobDetail().getJobDataMap().getString("password"); String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory"); String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName"); ConnectionsEntity conn; conn = connectionsDao.find(connectionId); if (inputDirectory == null || inputDirectory.trim().length() == 0) { inputDirectory = fileName; } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn && serviceId == Servers.HTTP.getDbCode())) { inputDirectory = inputDirectory + "/" + fileName; } log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName + "]."); String url = ""; if (serviceId == Servers.SAMBA.getDbCode()) { if (!fsManager.hasProvider("smb")) { fsManager.addProvider("smb", new SmbFileProvider()); } url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.HTTP.getDbCode()) { if (!fsManager.hasProvider("http")) { fsManager.addProvider("http", new HttpFileProvider()); } url = "http://" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.FTP.getDbCode()) { if (!fsManager.hasProvider("ftp")) { fsManager.addProvider("ftp", new FtpFileProvider()); } url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } log.info("url:" + url); final FileObject fileObject = fsManager.resolveFile(url); if (conn.getIdConnType() == GenericType.DownloadTypeConn) { if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject .getContent().getLastModifiedTime()) { log.info("There is no New or Updated '" + fileName + "' file on server to validate. Returning ..."); return; } else { log.info("There is New or Updated '" + fileName + "' file on server to validate. Validating ..."); ConnectionsEntity connection = connectionsDao.find(connectionId); connection.setFileDateTime( new Date(fileObject.getContent().getLastModifiedTime())); ApplicationContext ctx = AppContext.getApplicationContext(); ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class)); if (connDao != null) { connDao.update(connection); } Map<String, byte[]> resultMap = new HashMap<String, byte[]>(); byte data[] = new byte[(int) fileObject.getContent().getSize()]; fileObject.getContent().getInputStream().read(data); resultMap.put(fileObject.getName().getBaseName(), data); Set<String> keySet = resultMap.keySet(); Iterator<String> itr = keySet.iterator(); while (itr.hasNext()) { String strFileName = itr.next(); String result = ""; try { Long longSchemaId = schemaId; SchemaEntity schemaEntity = schemasDao.find(longSchemaId); if (schemaEntity == null) { result = "No schema found in database with Id [" + longSchemaId + "]"; log.error(result); logDao.setErrorLogMessage(result); } else { if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try { inStream = new ZipInputStream( new ByteArrayInputStream(resultMap.get(fileName))); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput .setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); result += datastreamsInput.datastreamsInput( new String(byteInput), longSchemaId, byteInput); } inStream.closeEntry(); } log.debug(result); } catch (IOException ex) { result = "Error occured during fetch records from ZIP file."; log.error(result); logDao.setErrorLogMessage(result); } finally { if (inStream != null) inStream.close(); } } else { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(strFileName); result = datastreamsInput.datastreamsInput( new String(resultMap.get(strFileName)), longSchemaId, resultMap.get(strFileName)); log.debug(result); } } } catch (Exception ex) { ex.printStackTrace(); result = "Exception occured during process the message for xml file " + strFileName + " Error - " + ex.getMessage(); log.error(result); logDao.setErrorLogMessage(result); } } } } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) { File uploadFile = File.createTempFile(fileName, ".tmp"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile)); bw.write(datastream); bw.flush(); bw.close(); } catch (IOException ioex) { log.error("Datastream file can't be created"); logDao.setErrorLogMessage("Datastream file can't be created"); return; } if (serviceId == Servers.HTTP.getDbCode()) { try { HttpClient httpclient = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Part[] parts = new Part[] { new FilePart("file", uploadFile.getName(), uploadFile) }; method.setRequestEntity( new MultipartRequestEntity(parts, method.getParams())); method.setDoAuthentication(true); int statusCode = httpclient.executeMethod(method); String responseBody = new String(method.getResponseBody()); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusLine().toString()); } else { System.out.println(responseBody); } method.releaseConnection(); } catch (Exception ex) { log.error("Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); } } else { try { FileObject localFileObject = fsManager .resolveFile(uploadFile.getAbsolutePath()); fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF); System.out.println("File uploaded at : " + new Date()); if (uploadFile.exists()) { uploadFile.delete(); } } catch (Exception ex) { log.error( "Exception occurred during uploading of file: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file: " + ex.getMessage()); } } } } } catch (Exception ex) { log.error("Error " + ": " + ex.getMessage()); } finally { fsManager.close(); } } finally { jobsDao.setWorkStatus(jobId, false); } } else { log.error("Can not set " + jobEntity.getName() + "working."); } } else { log.debug("Job " + jobEntity.getName() + " is working."); } }
From source file:it.openprj.jValidator.services.ServiceScheduledJob.java
@Override protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException { long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); JobsEntity jobEntity = jobsDao.find(jobId); if (!jobEntity.isWorking()) { if (jobsDao.setWorkStatus(jobId, true)) { try { long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null ? -1l/*from www .j a v a2 s.co m*/ : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId")); if (eventTriggerId > 0) { EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId); String className = entity.getName(); try { String sourceCode = entity.getCode(); EventTrigger eventTrigger; String response; eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className, "it.openprj.jValidator.eventtrigger.EventTrigger", EventTrigger.class, sourceCode); assert eventTrigger != null; response = eventTrigger.trigger(); log.info("Response From EventTrigger(" + className + ") :" + response); } catch (Exception e) { e.printStackTrace(); log.error("EventTrigger(" + className + ") :" + e.getMessage(), e); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage()); } catch (NoClassDefFoundError err) { log.error("EventTrigger(" + className + ") :" + err.getMessage(), err); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage()); } return; } int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day")); int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month")); if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) { return; } StandardFileSystemManager fsManager = new StandardFileSystemManager(); boolean isDataStream = true; try { fsManager.init(); long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId"); long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId"); //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId"); String datastream = ""; int idSchemaType = schemasDao.find(schemaId).getIdSchemaType(); TasksEntity taskEntity = tasksDao.find(schedulerId); //JobsEntity jobEntity = jobsDao.find(jobId); if (taskEntity.getIsOneShoot()) { jobEntity.setIsActive(0); jobsDao.update(jobEntity); } if (idSchemaType == SchemaType.GENERATION) { StreamGenerationUtils sgu = new StreamGenerationUtils(); datastream = sgu.getStream(schemaId); log.debug("Content stream: " + schemaId); if (datastream.trim().length() > 0) { log.debug("Datastream to validate: " + datastream); DatastreamsInput datastreamsInput = new DatastreamsInput(); String result = datastreamsInput.datastreamsInput(datastream, schemaId, null); log.debug("Validation result: " + result); } else { isDataStream = false; log.debug("No datastream create"); } } if (connectionId != 0) { int serviceId = Integer .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId")); String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp"); String port = arg0.getJobDetail().getJobDataMap().getString("port"); String userName = arg0.getJobDetail().getJobDataMap().getString("userName"); String password = arg0.getJobDetail().getJobDataMap().getString("password"); String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory"); String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName"); ConnectionsEntity conn; conn = connectionsDao.find(connectionId); if (inputDirectory == null || inputDirectory.trim().length() == 0) { inputDirectory = fileName; } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn && serviceId == Servers.HTTP.getDbCode())) { inputDirectory = inputDirectory + "/" + fileName; } log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName + "]."); String url = ""; if (serviceId == Servers.SAMBA.getDbCode()) { if (!fsManager.hasProvider("smb")) { fsManager.addProvider("smb", new SmbFileProvider()); } url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.HTTP.getDbCode()) { if (!fsManager.hasProvider("http")) { fsManager.addProvider("http", new HttpFileProvider()); } url = "http://" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.FTP.getDbCode()) { if (!fsManager.hasProvider("ftp")) { fsManager.addProvider("ftp", new FtpFileProvider()); } url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } log.info("url:" + url); final FileObject fileObject = fsManager.resolveFile(url); if (conn.getIdConnType() == GenericType.DownloadTypeConn) { if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject .getContent().getLastModifiedTime()) { log.info("There is no New or Updated '" + fileName + "' file on server to validate. Returning ..."); return; } else { log.info("There is New or Updated '" + fileName + "' file on server to validate. Validating ..."); ConnectionsEntity connection = connectionsDao.find(connectionId); connection.setFileDateTime( new Date(fileObject.getContent().getLastModifiedTime())); ApplicationContext ctx = AppContext.getApplicationContext(); ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class)); if (connDao != null) { connDao.update(connection); } Map<String, byte[]> resultMap = new HashMap<String, byte[]>(); byte data[] = new byte[(int) fileObject.getContent().getSize()]; fileObject.getContent().getInputStream().read(data); resultMap.put(fileObject.getName().getBaseName(), data); Set<String> keySet = resultMap.keySet(); Iterator<String> itr = keySet.iterator(); while (itr.hasNext()) { String strFileName = itr.next(); String result = ""; try { Long longSchemaId = schemaId; SchemaEntity schemaEntity = schemasDao.find(longSchemaId); if (schemaEntity == null) { result = "No schema found in database with Id [" + longSchemaId + "]"; log.error(result); logDao.setErrorLogMessage(result); } else { if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try { inStream = new ZipInputStream( new ByteArrayInputStream(resultMap.get(fileName))); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput .setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); result += datastreamsInput.datastreamsInput( new String(byteInput), longSchemaId, byteInput); } inStream.closeEntry(); } log.debug(result); } catch (IOException ex) { result = "Error occured during fetch records from ZIP file."; log.error(result); logDao.setErrorLogMessage(result); } finally { if (inStream != null) inStream.close(); } } else { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(strFileName); result = datastreamsInput.datastreamsInput( new String(resultMap.get(strFileName)), longSchemaId, resultMap.get(strFileName)); log.debug(result); } } } catch (Exception ex) { ex.printStackTrace(); result = "Exception occured during process the message for xml file " + strFileName + " Error - " + ex.getMessage(); log.error(result); logDao.setErrorLogMessage(result); } } } } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) { File uploadFile = File.createTempFile(fileName, ".tmp"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile)); bw.write(datastream); bw.flush(); bw.close(); } catch (IOException ioex) { log.error("Datastream file can't be created"); logDao.setErrorLogMessage("Datastream file can't be created"); return; } if (serviceId == Servers.HTTP.getDbCode()) { try { HttpClient httpclient = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Part[] parts = new Part[] { new FilePart("file", uploadFile.getName(), uploadFile) }; method.setRequestEntity( new MultipartRequestEntity(parts, method.getParams())); method.setDoAuthentication(true); int statusCode = httpclient.executeMethod(method); String responseBody = new String(method.getResponseBody()); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusLine().toString()); } else { System.out.println(responseBody); } method.releaseConnection(); } catch (Exception ex) { log.error("Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); } } else { try { FileObject localFileObject = fsManager .resolveFile(uploadFile.getAbsolutePath()); fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF); System.out.println("File uploaded at : " + new Date()); if (uploadFile.exists()) { uploadFile.delete(); } } catch (Exception ex) { log.error( "Exception occurred during uploading of file: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file: " + ex.getMessage()); } } } } } catch (Exception ex) { log.error("Error " + ": " + ex.getMessage()); } finally { fsManager.close(); } } finally { jobsDao.setWorkStatus(jobId, false); } } else { log.error("Can not set " + jobEntity.getName() + "working."); } } else { log.debug("Job " + jobEntity.getName() + " is working."); } }
From source file:org.jboss.web.tomcat.tc5.TomcatDeployer.java
protected void performDeployInternal(String hostName, WebApplication appInfo, String warUrl, AbstractWebContainer.WebDescriptorParser webAppParser) throws Exception { WebMetaData metaData = appInfo.getMetaData(); String ctxPath = metaData.getContextRoot(); if (ctxPath.equals("/") || ctxPath.equals("/ROOT") || ctxPath.equals("")) { log.debug("deploy root context=" + ctxPath); ctxPath = "/"; metaData.setContextRoot(ctxPath); }//from w w w . ja v a 2 s .c o m log.info("deploy, ctxPath=" + ctxPath + ", warUrl=" + shortWarUrlFromServerHome(warUrl)); URL url = new URL(warUrl); ClassLoader loader = Thread.currentThread().getContextClassLoader(); /* If we are using the jboss class loader we need to augment its path to include the WEB-INF/{lib,classes} dirs or else scoped class loading does not see the war level overrides. The call to setWarURL adds these paths to the deployment UCL. */ Loader webLoader = null; if (config.isUseJBossWebLoader()) { WebCtxLoader jbossLoader = new WebCtxLoader(loader); jbossLoader.setWarURL(url); webLoader = jbossLoader; } else { String[] pkgs = config.getFilteredPackages(); WebAppLoader jbossLoader = new WebAppLoader(loader, pkgs); jbossLoader.setDelegate(getJava2ClassLoadingCompliance()); webLoader = jbossLoader; } // We need to establish the JNDI ENC prior to the start // of the web container so that init on startup servlets are able // to interact with their ENC. We hook into the context lifecycle // events to be notified of the start of the // context as this occurs before the servlets are started. if (appInfo.getAppData() == null) webAppParser.parseWebAppDescriptors(loader, appInfo.getMetaData()); appInfo.setName(url.getPath()); appInfo.setClassLoader(loader); appInfo.setURL(url); String objectNameS = config.getCatalinaDomain() + ":j2eeType=WebModule,name=//" + ((hostName == null) ? "localhost" : hostName) + ctxPath + ",J2EEApplication=none,J2EEServer=none"; ObjectName objectName = new ObjectName(objectNameS); if (server.isRegistered(objectName)) { log.debug("Already exists, destroying " + objectName); server.invoke(objectName, "destroy", new Object[] {}, new String[] {}); } server.createMBean("org.apache.commons.modeler.BaseModelMBean", objectName, new Object[] { config.getContextClassName() }, new String[] { "java.lang.String" }); // Find and set config file on the context // If WAR is packed, expand config file to temp folder String ctxConfig = null; try { ctxConfig = findConfig(url); } catch (IOException e) { log.debug("No " + CONTEXT_CONFIG_FILE + " in " + url, e); } server.setAttribute(objectName, new Attribute("docBase", url.getFile())); server.setAttribute(objectName, new Attribute("configFile", ctxConfig)); server.setAttribute(objectName, new Attribute("defaultContextXml", "context.xml")); server.setAttribute(objectName, new Attribute("defaultWebXml", "conf/web.xml")); server.setAttribute(objectName, new Attribute("javaVMs", javaVMs)); server.setAttribute(objectName, new Attribute("server", serverName)); server.setAttribute(objectName, new Attribute("saveConfig", Boolean.FALSE)); if (webLoader != null) { server.setAttribute(objectName, new Attribute("loader", webLoader)); } else { server.setAttribute(objectName, new Attribute("parentClassLoader", loader)); } server.setAttribute(objectName, new Attribute("delegate", new Boolean(getJava2ClassLoadingCompliance()))); String[] jspCP = getCompileClasspath(loader); StringBuffer classpath = new StringBuffer(); for (int u = 0; u < jspCP.length; u++) { String repository = jspCP[u]; if (repository == null) continue; if (repository.startsWith("file://")) repository = repository.substring(7); else if (repository.startsWith("file:")) repository = repository.substring(5); else continue; if (repository == null) continue; // ok it is a file. Make sure that is is a directory or jar file File fp = new File(repository); if (!fp.isDirectory()) { // if it is not a directory, try to open it as a zipfile. try { // avoid opening .xml files if (fp.getName().toLowerCase().endsWith(".xml")) continue; ZipFile zip = new ZipFile(fp); zip.close(); } catch (IOException e) { continue; } } if (u > 0) classpath.append(File.pathSeparator); classpath.append(repository); } server.setAttribute(objectName, new Attribute("compilerClasspath", classpath.toString())); // Set the session cookies flag according to metadata switch (metaData.getSessionCookies()) { case WebMetaData.SESSION_COOKIES_ENABLED: server.setAttribute(objectName, new Attribute("cookies", new Boolean(true))); log.debug("Enabling session cookies"); break; case WebMetaData.SESSION_COOKIES_DISABLED: server.setAttribute(objectName, new Attribute("cookies", new Boolean(false))); log.debug("Disabling session cookies"); break; default: log.debug("Using session cookies default setting"); } // Add a valve to estalish the JACC context before authorization valves Certificate[] certs = null; CodeSource cs = new CodeSource(url, certs); JaccContextValve jaccValve = new JaccContextValve(metaData.getJaccContextID(), cs); server.invoke(objectName, "addValve", new Object[] { jaccValve }, new String[] { "org.apache.catalina.Valve" }); // Pass the metadata to the RunAsListener via a thread local RunAsListener.metaDataLocal.set(metaData); try { // Init the container; this will also start it server.invoke(objectName, "init", new Object[] {}, new String[] {}); } finally { RunAsListener.metaDataLocal.set(null); } // make the context class loader known to the WebMetaData, ws4ee needs it // to instanciate service endpoint pojos that live in this webapp Loader ctxLoader = (Loader) server.getAttribute(objectName, "loader"); metaData.setContextLoader(ctxLoader.getClassLoader()); // Clustering if (metaData.getDistributable()) { // Try to initate clustering, fallback to standard if no clustering is available try { AbstractJBossManager manager = null; String managerClassName = config.getManagerClass(); Class managerClass = Thread.currentThread().getContextClassLoader().loadClass(managerClassName); manager = (AbstractJBossManager) managerClass.newInstance(); if (manager instanceof JBossCacheManager) { // TODO either deprecate snapshot mode or move its config // into jboss-web.xml. String snapshotMode = config.getSnapshotMode(); int snapshotInterval = config.getSnapshotInterval(); JBossCacheManager jbcm = (JBossCacheManager) manager; jbcm.setSnapshotMode(snapshotMode); jbcm.setSnapshotInterval(snapshotInterval); } String name = "//" + ((hostName == null) ? "localhost" : hostName) + ctxPath; manager.init(name, metaData, config.isUseJK(), config.isUseLocalCache()); // Don't assign the manager to the context until all config // is done, or else the manager will be started without the config server.setAttribute(objectName, new Attribute("manager", manager)); log.debug("Enabled clustering support for ctxPath=" + ctxPath); } catch (ClusteringNotSupportedException e) { // JBAS-3513 Just log a WARN, not an ERROR log.warn("Failed to setup clustering, clustering disabled. ClusteringNotSupportedException: " + e.getMessage()); } catch (NoClassDefFoundError ncdf) { // JBAS-3513 Just log a WARN, not an ERROR log.debug("Classes needed for clustered webapp unavailable", ncdf); log.warn("Failed to setup clustering, clustering disabled. NoClassDefFoundError: " + ncdf.getMessage()); } catch (Throwable t) { // TODO consider letting this through and fail the deployment log.error("Failed to setup clustering, clustering disabled. Exception: ", t); } } /* Add security association valve after the authorization valves so that the authenticated user may be associated with the request thread/session. */ SecurityAssociationValve valve = new SecurityAssociationValve(metaData, config.getSecurityManagerService()); valve.setSubjectAttributeName(config.getSubjectAttributeName()); server.invoke(objectName, "addValve", new Object[] { valve }, new String[] { "org.apache.catalina.Valve" }); // Retrieve the state, and throw an exception in case of a failure Integer state = (Integer) server.getAttribute(objectName, "state"); if (state.intValue() != 1) { throw new DeploymentException("URL " + warUrl + " deployment failed"); } appInfo.setAppData(objectName); // Create mbeans for the servlets DeploymentInfo di = webAppParser.getDeploymentInfo(); di.deployedObject = objectName; ObjectName servletQuery = new ObjectName(config.getCatalinaDomain() + ":j2eeType=Servlet,WebModule=" + objectName.getKeyProperty("name") + ",*"); Iterator iterator = server.queryMBeans(servletQuery, null).iterator(); while (iterator.hasNext()) { di.mbeans.add(((ObjectInstance) iterator.next()).getObjectName()); } log.debug("Initialized: " + appInfo + " " + objectName); }
From source file:org.apache.felix.webconsole.internal.servlet.OsgiManager.java
public OsgiManager(BundleContext bundleContext) { this.bundleContext = bundleContext; this.holder = new PluginHolder(bundleContext); // setup the included plugins ClassLoader classLoader = getClass().getClassLoader(); for (int i = 0; i < PLUGIN_CLASSES.length; i++) { String pluginClassName = PLUGIN_CLASSES[i]; try {/*from w w w.ja v a2s.co m*/ Class pluginClass = classLoader.loadClass(pluginClassName); Object plugin = pluginClass.newInstance(); // check whether enabled by configuration if (isPluginDisabled(pluginClassName, plugin)) { log(LogService.LOG_INFO, "Ignoring plugin " + pluginClassName + ": Disabled by configuration"); continue; } if (plugin instanceof OsgiManagerPlugin) { ((OsgiManagerPlugin) plugin).activate(bundleContext); osgiManagerPlugins.add(plugin); } if (plugin instanceof AbstractWebConsolePlugin) { holder.addOsgiManagerPlugin((AbstractWebConsolePlugin) plugin); } else if (plugin instanceof BrandingPlugin) { AbstractWebConsolePlugin.setBrandingPlugin((BrandingPlugin) plugin); } } catch (NoClassDefFoundError ncdfe) { String message = ncdfe.getMessage(); if (message == null) { // no message, construct it message = "Class definition not found (NoClassDefFoundError)"; } else if (message.indexOf(' ') < 0) { // message is just a class name, try to be more descriptive message = "Class " + message + " missing"; } log(LogService.LOG_INFO, pluginClassName + " not enabled. Reason: " + message); } catch (Throwable t) { log(LogService.LOG_INFO, "Failed to instantiate plugin " + pluginClassName + ". Reason: " + t); } } // the resource bundle manager resourceBundleManager = new ResourceBundleManager(getBundleContext()); // start the configuration render, providing the resource bundle manager ConfigurationRender cr = new ConfigurationRender(resourceBundleManager); cr.activate(bundleContext); osgiManagerPlugins.add(cr); holder.addOsgiManagerPlugin(cr); // start tracking external plugins after setting up our own plugins holder.open(); // accept new console branding service brandingTracker = new BrandingServiceTracker(this); brandingTracker.open(); // add support for pluggable security securityProviderTracker = new ServiceTracker(bundleContext, WebConsoleSecurityProvider.class.getName(), null); securityProviderTracker.open(); // configure and start listening for configuration updateConfiguration(null); try { this.configurationListener = ConfigurationListener2.create(this); } catch (Throwable t2) { // might be caused by Metatype API not available // try without MetaTypeProvider try { this.configurationListener = ConfigurationListener.create(this); } catch (Throwable t) { // might be caused by CM API not available } } }