top-image

OLDER ARTICLES

Hello,

Today, I propose a very simple fake SMTP server designed for unit and system testing applications that send email messages. The class is a ServerSocket (Runnable) which responds to the standard SMTP commands but does not deliver messages to the user. The messages are printed in the full SMTP server log containing all the information exchanged between the SMTP server & the clients.

This ServerSocket could be executed in standalone in a Runnable or in a WEB project via a ContextServletListener configured in the web.xml:

	public static void main(String[] args) {
		try {
			FakeSMTPServer srv = new FakeSMTPServer();
			while (true) {
				Thread.sleep(10000);
			} // end-while
		} catch (Exception e) {
			e.printStackTrace();
		} // end-try
	}

The classes in attachment need the junit-4.1.jar, mail-1.3.2.jar and spring-2.5.5.jar to be used.
FakeSMTPServer.zip

Note: There is other products like SMTP4DEV usable directly without installation.
smtp4dev.zip

For the needs of a project, I have had the opportunity to use the Apache Commons Compress libary in order to archive and compress files in ZIP, TAR, GZIP.

Here, a brief presentation of this library from Apache:
Apache Commons Compress software defines an API for working with compression and archive formats. These include: bzip2, gzip, pack200 and ar, cpio, jar, tar, zip, dump. This is a Java API for working with tar, zip, gz, jar, cpio and bzip2 files. The code has origins in other Apache projects like Excalibur, Ant, Commons-IO and jRPM.
The compress component is split into compressors and archivers. While compressors (un)compress streams that usually store a single entry, archivers deal with archives that contain structured content represented by ArchiveEntry instances which in turn usually correspond to single files or directories. Currently the bzip2 and gzip formats are supported as compressors where gzip support is provided by the java.util.zip package of the Java class library. The ar, cpio, tar and zip formats are supported as archivers where the zip implementation provides capabilities that go beyond the features found in java.util.zip. The compress component provides abstract base classes for compressors and archivers together with factories that can be used to choose implementations by algorithm name.
In the case of input streams the factories can also be used to guess the format and provide the matching implementation.

A note concerning the differences between GZIP and ZIP:
+ GZIP files (the Gnu format) are not archives and compress only one file. GZIP is essentially a one file subset of the Zip format.
+ GZIP compresses only one file and does not have a header. ZIP contains header information about what files are contained in the file.
+ ZIP is an archive file format, popularized on PCs, that contains multiple compressed files.

In the attachments files, you could find a project using commons-compress-1.0.jar with the classes:
CompressArchiveUtil: tool allowing the manipulations of tar or tar.gz documents;
ZipUtil: Utility to Zip and Unzip nested directories recursively

The outputs/files are created in test_compress1\bin\jUnitResources folder.

test_compress1.zip

Source: Apache Commons Compress

During my self-training on GWT (Google Web Toolkit) and GAE (Google App Engine) which will be the topic of several next posts (presentation GWT and GEA, creation of new application with 2 interfaces JSP and GWT, securised by Spring security and the persistence with JPA/App Engine datastore, deployment on GEA..), I have encountered a deficiency or missing method in the FlexTable component of GWT.
This component has not a method to show/hide columns in Flextables at 1 line.

There is a method to hide a row:

    compFlextable.getRowFormatter().setVisible(arg0, arg1); 

But there is not method to hide a specific column:

    compFlextable.getColumnFormatter().setVisible(arg0, arg1); 

Here, a simple method which allows the hiding and showing of a column in a Flextable by the hiding of the column’s cell on each row:

	private void setColumnVisible(FlexTable table, int Col, boolean b) {
		for (int i = 0; i < table.getRowCount(); i++) {
			table.getCellFormatter().setVisible(i, Col, b);
		}
	}

Hi,

I will expose you a solution implemented in order to:
– filter imports/resource loading in a spring context of general applicationContext.xml,
– filter resources in imports or even overloading of beans,
– test the environment and conditionally add path locations,

For our example, in an web application with a root context definition applicationContext.xml:

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:file1.properties</value>
				<value>classpath:file2.properties</value>
				<value>classpath:file3.properties</value>
			</list>
		</property>
	</bean>
	
	<import resource="classpath:huo-spring-business-services.xml" />
	<import resource="classpath:huo-spring-datasource.xml" />
	<import resource="classpath:huo-spring-security-config.xml" />
	<import resource="classpath:huo-spring-security-access.xml" />
	<import resource="classpath:huo-spring-wf.xml" />

This context is loaded in the web.xml file of web application:

	<context-param>
		<param-name>contextClass</param-name>
		<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
	</context-param>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>

In our example, we want to filter the last import in the root context:

<import resource="classpath:huo-spring-wf.xml" />

in terms of a properties in the “huo.config.wf.enable” in the properties file “file3.properties”:

huo.config.wf.enable=false

So, we have create a new class ConditionalConfigurationXmlWebApplicationContext extending the Spring standard XmlWebApplicationContext. This new class can override the “refresh()”, “getConfigLocations()” or “getResources()” methods, where it will test its environment and possibly modify the “configLocations”.

Important note: To be catched by our above class, we nedd to add “classpath:” in all imports like ‘import resource=”classpath:spring-except.xml” ‘.

For our example and needs, it would do something like:

	/**
	 * Map containing the resources do not load
	 */
	private Map<String, Boolean> locationPatternRessourceNOLoad = new HashMap<String, Boolean>();
	public ConditionalConfigurationXmlWebApplicationContext() {
		super();
		// Exemple de filtrage wf
		{
	        InputStream in = null;
			try{
				String name = "file3.properties";
		        Properties result = null;
		        ClassLoader  loader = this.getClassLoader();
		        if (loader == null){
		        	loader = ClassLoader.getSystemClassLoader ();
		        }
	            in = loader.getResourceAsStream (name);
	            if (in != null){
                    result = new Properties ();
					result.load(in); // Can throw IOException
	            }
	            //for (Iterator iterator = result.keySet().iterator(); iterator.hasNext();) {
	            //	Object key = iterator.next();
				//	Object value = result.get(key);
				//	System.out.println(key+"="+value);
	            //}
	        
	            Object val = result.get("huo.config.wf.enable");
	            if(val != null){
           			locationPatternRessourceNOLoad.put("classpath:huo-spring-wf.xml", Boolean.parseBoolean(val.toString()));
	            }

			}catch (Throwable ignore){
	        }finally{
	            if (in != null) try { in.close (); } catch (Throwable ignore) {}
	        }
		}
	}
	/**
	 * Resolve the given location pattern into Resource objects. 
	 */
	@Override
	public Resource[] getResources(String locationPattern) throws IOException{
		{
			Boolean toLoad = true;
			if(locationPatternRessourceNOLoad.containsKey(locationPattern)){
				toLoad = locationPatternRessourceNOLoad.get(locationPattern);
			}
			if(toLoad.booleanValue()){ // LOAD
				return super.getResources(locationPattern);
			}else{ // NO LOAD
				return new Resource[]{};
			}
		}		
	}
	/**
	 * Méthode appellée et retournant les fichiers paramétrés dans le paramètre "contextConfigLocation" du fichier web.xml 
	 */
	/*@Override
	public String[] getConfigLocations() {
		//locations = append(locations, "classpath*:/META-INF/config/service-module-test-only.xml");
		//setConfigLocations(locations);
		return super.getConfigLocations();
	}*/

So, I have this in my web.xml:

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextClass</param-name>
		<!-- <param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value> -->
		<param-value>huo.ConditionalConfigurationXmlWebApplicationContext</param-value>
	</context-param>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>

ConditionalConfigurationXmlWebApplicationContext.zip

Source: XmlWebApplicationContext

Best regards,

Huseyin

Page 52 of 53:« First« 49 50 51 52 53 »
bottom-img
Copyright ® 2012 Huseyin Ozveren. No reproduction, even partial, can be used from this site and all its contents including text, documents, images, etc.. without the express permission of the author.