Rodando o tomcat 6 de dentro da aplicação web (Tomcat Embedded)

22 05 2009

- Primeiramente, é necessário que você tenha o tomcat em mãos, caso não tenha pode baixar aqui:

A versão utilizada para este exemplo foi a 6.0.18.

- Crie um projeto java com o nome “tomcat6-embedded”.
- Extraia o arquivo para a pasta raiz do projeto e renomeie para tomcat6, ficando assim: “tomcat6-embedded /tomcat6”.
- Pelo eclipse, entre na pasta lib dentro de tomcat6, e adicione todos os jars no classpath.

Alem das libs do tomcat ainda precisamos de mais algums jars:

commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-logging-1.0.4.jar
commons-modeler-2.0.1.jar
commons-net-1.4.1.jar
juli-6.0.13.jar
log4j-1.2.14.jar

- Crie uma pasta lib dentro da pasta raiz do projeto, e coloque estes jars dentro dela, ficando assim: “tomcat6-embedded /lib” e adicione todos no classpath.

Caso não encontre estas bibliotecas, elas estarão junto com o arquivo do projeto que será disponibilizado para download.

Agora crie os pacotes e as classes de acordo com a imagem abaixo:

Com essa parte configurada, vamos para o código:

Arquivo Tomcat6.java

package br.com.server.embedded.service;

import java.net.InetAddress;

import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.realm.MemoryRealm;
import org.apache.catalina.startup.Embedded;
import org.apache.tomcat.util.IntrospectionUtils;

public class Tomcat6 {

	private String path = null;
	private Embedded embedded = null;
	private Host host = null;
	private Context rootcontext;
	private String welcomeFile;
	private String contextName;
	private String contextPath;

	public Tomcat6() {
		org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
	}

	/**
	 * Set Session scope variable
	 *
	 * @param name Session variable name
	 * @param obj Session variable value
	 */
	public void setRootContextSessionAttribute(String name, Object obj) {
		try {
			Session sessions[] = this.rootcontext.getManager().findSessions();

			for (int i = 0, size = sessions.length; i < size; i++) {
				sessions[i].getSession().setAttribute(name, obj);
			}
		} catch (Exception x) {
		}
	}

	/**
	 * Get Application scope variable
	 *
	 * @param name Application variable name
	 * @return Application variable value
	 */
	public Object getRootContextAttribute(String name) {
		return this.rootcontext.getServletContext().getAttribute(name);
	}

	/**
	 * Set Application scope variable
	 *
	 * @param name Application variable name
	 * @param obj Application variable value
	 */
	public void setRootContextAttribute(String name, Object obj) {
		this.rootcontext.getServletContext().setAttribute(name, obj);
	}

	/**
	 * Remove Application scope variable
	 *
	 * @param name Application variable name
	 */
	public void removeRootContextAttribute(String name) {
		this.rootcontext.getServletContext().removeAttribute(name);
	}

	/**
	 * Basic Accessor setting the value of the context path
	 *
	 * @param path - the path
	 */
	public void setPath(String path) {
		this.path = path;
	}

	/**
	 * Basic Accessor returning the value of the context path
	 *
	 * @return - the context path
	 */
	public String getPath() {
		return this.path;
	}

	@SuppressWarnings("unused")
	/**
	 * This method Starts the Tomcat server.
	 */
	public void start() {
		try {
			Engine engine = null;

			// Create an embedded server
			this.embedded = new Embedded();
			this.embedded.setCatalinaHome(getPath());

			// set the memory realm
			MemoryRealm memRealm = new MemoryRealm();
			this.embedded.setRealm(memRealm);

			// Create an engine
			engine = this.embedded.createEngine();
			engine.setDefaultHost("localhost");

			// Create a default virtual host
			this.host = this.embedded.createHost("localhost", getPath()+ "/webapps");
			engine.addChild(this.host);

			// Create the ROOT context
			this.rootcontext = this.embedded.createContext("", getPath() + "/webapps/ROOT");
			this.rootcontext.setReloadable(false);
			this.rootcontext.addWelcomeFile(getWelcomeFile());
			this.host.addChild(this.rootcontext);

			// create another application Context
			Context appCtx = this.embedded.createContext("/"+getContextName(), getContextPath());
			appCtx.setPrivileged(true);
			this.host.addChild(appCtx); // add context to host

			// Install the assembled container hierarchy
			this.embedded.addEngine(engine);

			int port = 8080;
			String addr = null;
			Connector connector = null;// this.embedded.createConnector(addr, port,
										// false);
			/*
			 * embedded.createConnector(...) seems to be broken.. it always returns
			 * a null connector. see work around below
			 */
			InetAddress address = null;
			try {
				connector = new Connector();
				// httpConnector.setScheme("http");
				connector.setSecure(false);
				address = InetAddress.getLocalHost();
				if (address != null) {
					IntrospectionUtils.setProperty(connector, "address", ""	+ address);
				}
				IntrospectionUtils.setProperty(connector, "port", "" + port);

			} catch (Exception ex) {
				ex.printStackTrace();
			}
			connector.setEnableLookups(false);

			this.embedded.addConnector(connector);
			// Start the embedded server
			this.embedded.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Refresh ROOT context
	 *
	 */
	public void reloadRoot() {
		this.rootcontext.reload();
	}

	/**
	 * Remove ROOT context
	 *
	 */
	public void removeRoot() {
		this.host.removeChild(this.rootcontext);
	}

	/**
	 * Add ROOT context
	 *
	 */
	public void addRoot() {
		this.host.addChild(this.rootcontext);
	}

	/**
	 * This method Stops the Tomcat server.
	 */
	public void stop() throws Exception {
		this.embedded.stop();
	}

	/**
	 * Registers a WAR with the container.
	 *
	 * @param contextPath - the context path under which the application will be registered
	 * @param warFile - the URL of the WAR to be registered.
	 */
	public void registerWAR(String contextPath, String absolutePath) throws Exception {
		Context context = this.embedded.createContext(contextPath, absolutePath);
		context.setReloadable(false);
		this.host.addChild(context);
	}

	/**
	 * Unregisters a WAR from the web server.
	 *
	 * @param contextPath
	 *            - the context path to be removed
	 */
	public void unregisterWAR(String contextPath) throws Exception {

		Context context = this.host.map(contextPath);
		if (context != null) {
			this.embedded.removeContext(context);
		} else {
			throw new Exception("Context does not exist for named path : " + contextPath);
		}
	}

	public String getWelcomeFile() {
		return welcomeFile;
	}

	public void setWelcomeFile(String welcomeFile) {
		this.welcomeFile = welcomeFile;
	}

	public String getContextName() {
		return contextName;
	}

	public void setContextName(String contextName) {
		this.contextName = contextName;
	}

	public String getContextPath() {
		return contextPath;
	}

	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}
}

Arquivo Main.java

package br.com.server.embedded.main;

import java.io.File;

import br.com.server.embedded.service.Tomcat6;

public class Main {

	@SuppressWarnings("static-access")
	public static void main(String[] args) {

		Tomcat6 service = new Tomcat6();

		// Seta o WelcomeFile
		service.setWelcomeFile("index.jsp");

		// Seta o nome do contexto do projeto
		service.setContextName("wap");

		// Seta o caminho do projeto
		service.setContextPath("C:/wap");

		// Seta o caminho do container web
		service.setPath(new File("tomcat6").getAbsolutePath());

		// Chama o método para iniciar o servidor web
		service.start();

		// Mantem a thread rodando por 24 horas
		try {
			Thread.currentThread().sleep(60 * 1000 * 60 * 24);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

Bom, é isso ai.. qualquer dúvida estou a disposição.

Até+!





Customizando a função Alert no Flex

22 05 2009

Buenas!!

Bom, na empresa que trabalho fui convocado para entrar num projeto FLEX+JAVA, a notícia foi um pouco triste pra mim, primeiro porque nunca trabalhei com flex e segundo porque detesto trabalhar com layout.. enfim não tenho saída a não ser me dedicar pra sair algo :D !

Neste post vou mostrar como customizar a função:

Alert.show()

que é muito usada no sistema.

Segue abaixo trechos do código usado na programação:

Atributos:

/**
* Opções para os botões;
* */
public static var OK_BUTTON : String = 'OK';
public static var CANCEL_BUTTON : String = 'CANCEL';
public static var OK_CANCEL_BUTTON : String = 'OK_CANCEL';
public static var YES_NO_BUTTON : String = 'YES_NO';		

/**
* Opções para os ícones;
* */
public static var CHECK_ICON : String = "CHECK_ICON";
public static var DEL_ICON : String = "DEL_ICON";
public static var ERROR_ICON : String = "ERROR_ICON";
public static var HELP_ICON : String = "HELP_ICON";
public static var INFORMATION_ICON : String = "INFORMATION_ICON";
public static var RESTRICTED_ICON : String = "RESTRICTED_ICON";

/**
* Source dos ícones;
* */
[Embed(source="imgs/Symbol-Check.png")]
private static var _CHECK_ICON : Class;
[Embed(source="imgs/Symbol-Deleted.png")]
private static var _DEL_ICON : Class;
[Embed(source="imgs/Symbol-Error.png")]
private static var _ERROR_ICON : Class;
[Embed(source="imgs/Symbol-Help.png")]
private static var _HELP_ICON : Class;
[Embed(source="imgs/Symbol-Information.png")]
private static var _INFORMATION_ICON : Class;
[Embed(source="imgs/Symbol-Restricted.png")]
private static var _RESTRICTED_ICON : Class;

/**
* Atributos dinâmicos da Dialog;
* */
private static var _textAlert : String = "";
private static var _titleAlert : String = "";
private static var _backgroundColor : String = "13421772";
private static var _borderColor : String = "6710886";
private static var _backgroundAlpha : String = "0.9";
private static var _borderAlpha : String = "0.9";
private static var _color : String = "0";
private static var _buttonFlagsDialog : String = OK_BUTTON;
private static var _iconClassDialog : String = INFORMATION_ICON;

Métodos:

/**
 * Configura a dialog de acordo com os parâmetros;
 * */
public static function open(... parameters) : Alert {

	/**
	 * Seta a configuração padrão para a dialog;
	 * */
	var text : String = textAlert;
	var title : String = titleAlert;
	var iconClass : String = iconClassDialog;
	var buttonFlags : String = buttonFlagsDialog;
	var modal : Boolean = true;

	/**
	 * Pega os parametros da dialog;
	 * */
	switch (parameters.length) {
		case 0:
			return null;
		case 1:
			text = parameters[0];
			break;
		case 2:
			text = parameters[0];
			title = parameters[1];
			break;
		case 3:
			text = parameters[0];
			title = parameters[1];
			iconClass = parameters[2];
			break;
		case 4:
			text = parameters[0];
			title = parameters[1];
			iconClass = parameters[2];
			buttonFlags = parameters[3];
			break;

	}

	return showAlert(text, title, iconClass, buttonFlags);
}

/**
 * Abre a dialog para o usuário;
 * */
private static function showAlert(text : String, title : String, iconClass : String, buttonFlags : String) : Alert {

	var alert : Alert = new Alert();
	var closeAlert : Function = closeAlert;

	alert.text = text;
	alert.title = title;
	alert.setStyle("backgroundColor", backgroundColor);
	alert.setStyle("borderColor", borderColor);
	alert.setStyle("backgroundAlpha", backgroundAlpha);
	alert.setStyle("borderAlpha", borderAlpha);
	alert.setStyle("color", color);
	alert.defaultButtonFlag = Alert.OK;

	switch(iconClass) {
		case CHECK_ICON:
			alert.iconClass=_CHECK_ICON;
		break;
		case DEL_ICON:
			alert.iconClass=_DEL_ICON;
		break;
		case ERROR_ICON:
			alert.iconClass=_ERROR_ICON;
		break;
		case HELP_ICON:
			alert.iconClass=_HELP_ICON;
		break;
		case INFORMATION_ICON:
			alert.iconClass=_INFORMATION_ICON;
		break;
		case RESTRICTED_ICON:
			alert.iconClass=_RESTRICTED_ICON;
		break;
	}

	switch(buttonFlags) {
		case "OK":
			alert.buttonFlags=Alert.OK;
		break;

		case "CANCEL":
			alert.buttonFlags=Alert.CANCEL;
		break;

		case "OK_CANCEL":
			alert.buttonFlags=Alert.OK + Alert.CANCEL;
		break;

		case "YES_NO":
			alert.buttonFlags=Alert.YES + Alert.NO;
		break;
	}

	alert.styleName;

	var parent : Object = Sprite(Application.application);

	if (parent is UIComponent)
	alert.moduleFactory = UIComponent(parent).moduleFactory;	

	PopUpManager.addPopUp(alert, Sprite(parent), true);
	alert.setActualSize(alert.getExplicitOrMeasuredWidth(), alert.getExplicitOrMeasuredHeight());

	return alert;
}

Getters and Setters:

public static function set color(_color:String) : void {
	_color = _color;
}

public static function get color() : String {
	return _color;
}

public static function set borderAlpha(_borderAlpha:String) : void {
	_borderAlpha = _borderAlpha;
}

public static function get borderAlpha() : String {
	return _borderAlpha;
}

public static function set backgroundAlpha(_backgroundAlpha:String) : void {
	_backgroundAlpha = _backgroundAlpha;
}

public static function get backgroundAlpha() : String {
	return _backgroundAlpha;
}

public static function set borderColor(_borderColor:String) : void {
	_borderColor = _borderColor;
}

public static function get borderColor() : String {
	return _borderColor;
}

public static function set backgroundColor(_backgroundColor:String) : void {
	_backgroundColor = _backgroundColor;
}

public static function get backgroundColor() : String {
	return _backgroundColor;
}

public static function set titleAlert(_titleAlert:String) : void {
	_titleAlert = _titleAlert;
}

public static function get titleAlert() : String {
	return _titleAlert;
}

public static function set textAlert(_textAlert:String) : void {
	_textAlert = _textAlert;
}

public static function get textAlert() : String {
	return _textAlert;
}

public static function set iconClassDialog(_iconClass:String) : void {
	_iconClass = _iconClass;
}

public static function get iconClassDialog() : String {
	return _iconClassDialog;
}

public static function set buttonFlagsDialog(_buttonFlags:String) : void {
	_buttonFlagsDialog = _buttonFlags;
}

public static function get buttonFlagsDialog() : String {
	return _buttonFlagsDialog;
}

Bom pessoal, a classe é simples, basta importar o código acima no projeto, e para chamar:

Dialog.open('Mensagem');
Dialog.open('Mensagem', 'Titulo');
Dialog.open('Mensagem', 'Titulo', Dialog.ERROR_ICON);
Dialog.open('Mensagem', 'Titulo', Dialog.ERROR_ICON, Dialog.OK_BUTTON);

Pessoal, coloquei os arquivos dentro de um rar, porém o wordpress não deixa eu upar arquivos.rar, somente .jpg..
então alterei a extensão do arquivo para .jpg, após baixar (clieque com o direito e depois em salvar como), altere para .rar ou abra o mesmo com o winrar.
Link dos arquivos

Bom, é isso ai, se alguém achar erro ou uma forma melhor de fazer post nos comments que atualizo, como falei anteriormente, tenho poucos dias de expiriência com flex e expero que seja útil para mais alguém!!

Fonte:
Lembrando que usei o google para pesquisar, como tenho pouco conhecimento com flex, usei alguns sites de tutoriais
para construir esta classe que não me lembro mais o endereço…