working on it ...


Explore Public Snippets

Sort by

Found 3,638 snippets matching: apache

    public by cghersi  468620  7  8  2

    Load a SOAP endpoint with Apache CXF using JMS transport provided by Apache ActiveMQ

    This is an example on how to load a SOAP web service in order to be able to invoke its methods via JMS transport
    private JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    public MyInterface loadEndPoint() {
    	//try to load from local, if available:
    	boolean loadOK = false;
    	MyInterface result = null;
    	try {
    		Class<?> c = Class.forName("MyImplClass");
    		Method fact = c.getMethod("get");
    		result = (MyInterface) fact.invoke(null);
    		loadOK = true;
    	} catch (ClassNotFoundException e) {"Cannot find MyImplClass, redirecting to  remote access...", e);		
    	} catch (Exception e) {
    		log.warn("Error searching MyImplClass, , redirecting to remote access. Exception is " + e, e);
    	//load remote endpoint:
    	if (!loadOK) {
    		//detect transport protocol for web services:
    		String brokerAddr = ""; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
 "Connecting to " + address);
    		String connString = "tcp://" + brokerAddr + ":61616";
    		ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory("Myusername", "Mypassword", connString);
    		SoapBindingConfiguration conf = new SoapBindingConfiguration();
    		//MTOM not supported! .net does not interoperate with cxf mtom impl.
    //		conf.setMtomEnabled(true);
    		factory.getFeatures().add(new WSAddressingFeature());
    		factory.getFeatures().add(getJMSConfigFeature(queueName, connFactory, 10000)));
    		Object resObj = factory.create();
    		if ((resObj != null) && (resObj instanceof MyInterface))
    			result = (MyInterface) resObj;
    		return result;
    public static JMSConfigFeature getJMSConfigFeature(String queueName, ActiveMQConnectionFactory connectionFactory, Long receiveTimeout) {
    	JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
    	JMSConfiguration jmsConfig = new JMSConfiguration();
    	if (receiveTimeout != null)
    	return jmsConfigFeature;

    public by sukhjinderkahlon  326302  7  5  0

    How to Work with Excel Files Using Apache POI

    This code will work as a utility to read and write excel files using Apache POI Library. 3.13
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    public class ExcelUtils {
    	private static HSSFSheet ExcelWSheet;
    	private static HSSFWorkbook ExcelWBook;
    	private static HSSFCell Cell;
    	private static HSSFRow Row;
    	private static String filePath;
    	public static void setExcelFile(String Path,String SheetName) throws Exception {
    			try {
       			// Open the Excel file
    			FileInputStream ExcelFile = new FileInputStream(Path);
    			// Access the required test data sheet
    			ExcelWBook = new HSSFWorkbook(ExcelFile);
    			ExcelWSheet = ExcelWBook.getSheet(SheetName);
    			} catch (Exception e){
    				throw (e);
    	//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
        public static String getCellData(int RowNum, int ColNum) throws Exception{
      			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
      			String CellData = Cell.getStringCellValue();
      			return CellData;
      			}catch (Exception e){
      //This method is to write in the Excel cell, Row num and Col num are the parameters
    	public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception	{
      			Row  = ExcelWSheet.getRow(RowNum);
    			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    			if (Cell == null) {
    				Cell = Row.createCell(ColNum);
    				} else {
      // Constant variables Test Data path and Test Data file name
      				FileOutputStream fileOut = new FileOutputStream(filePath);
    				}catch(Exception e){
    					throw (e);

    public by cghersi  179395  5  7  0

    Apache Cayenne: how to select with Joins

    This is how to create simple queries that use JOIN among several tables. Such tables must be modelled as related in Cayenne modeler. In the example, we have 4 classes in JOIN chain. We want to retrieve all the objects of the 4th class that match the join with the object of the first class with the given id.
    ObjectContext context = getMyContext();
    int id = ...; //the pk of the FirstClass table
    FirstClass n = Cayenne.objectForPK(context, FirstClass.class, id);
    Expression qualifier = ExpressionFactory.matchExp(FourthClass.THIRD_CLASS_PROPERTY + "." + 
    					ThirdClass.SECOND_CLASS_PROPERTY + "." + SecondClass.FIRST_CLASS_PROPERTY, n);
    SelectQuery select = new SelectQuery(FourthClass.class, qualifier);
    List<FourthClass> result = context.performQuery(select);

    public by bkozora  644  0  3  0

    Apache - Wildcard Subdomains

    Apache - Wildcard Subdomains: vhosts.conf
    DocumentRoot "/var/www/vhosts"
    <Directory "/var/www/vhosts">
        Options Indexes FollowSymLinks ExecCGI
        AllowOverride All
        Order allow,deny 
        Allow from all
        #Require all granted 
    <VirtualHost *:80>
        VirtualDocumentRoot /var/www/vhosts/%1/www/
        ServerAlias *

    public by cghersi  2394  0  7  0

    Apache Cayenne: How to select only PKs

    This is how to perform a query that retrieves just the PKs of a table, possibily filtering by fk field...
    public List<Integer> GetIDs(int fk) {
    		ServerRuntime runtime = new ServerRuntime("cayenne-MyDomain.xml");
    		ObjectContext context = runtime.getContext();
    		SQLTemplate select = new SQLTemplate(MyClass.class, 
    				"SELECT #result('" + MyClass.ID_PK_COLUMN + "' 'int') FROM MyClass WHERE MyFK=" + fk);
    		return context.performQuery(select);

    public by cghersi @ Apache Cayenne DEV  3645  0  7  0

    Use Apache Cayenne under OSGi environment

    This class presents the minimal behavior to show how to use Apache Cayenne framework in an OSGi container. The class is the activator of the OSGi Bundle and publishes a minimal set of CRUD methods for an example MyDBBean table. It implies the existence of a MyDBBean class, maybe generated with Cayenne Modeler; in the example MyDBBean class is in
    package osgicayennemanager;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    import javax.sql.DataSource;
    import org.apache.cayenne.Cayenne;
    import org.apache.cayenne.CayenneRuntimeException;
    import org.apache.cayenne.ObjectContext;
    import org.apache.cayenne.ObjectId;
    import org.apache.cayenne.configuration.server.ServerRuntime;
    import org.apache.cayenne.di.spi.ClassRegistry;
    import org.apache.cayenne.exp.Expression;
    import org.apache.cayenne.exp.ExpressionFactory;
    import org.apache.cayenne.query.ObjectIdQuery;
    import org.apache.cayenne.query.Ordering;
    import org.apache.cayenne.query.QueryCacheStrategy;
    import org.apache.cayenne.query.SelectQuery;
    import org.apache.cayenne.query.SortOrder;
    import org.osgi.framework.Bundle;
    import org.osgi.framework.BundleActivator;
    import org.osgi.framework.BundleContext;
    import org.osgi.framework.FrameworkUtil;
    import org.osgi.framework.wiring.BundleWiring;
    public class Activator implements BundleActivator {
    	private static ServerRuntime dbRuntime;
    	//this is useful if you want to directly get the connection to the DB
    	private static DataSource dbDS;
    	/// OSGI BundleActivator implementation
    	public void start(BundleContext bundleContext) throws Exception {
    		initDBConnection(); 		//initialize internal structures
    		//now you are ready to perform CRUD operations...
    	public void stop(BundleContext bundleContext) throws Exception {
    		//nothing to do here...
    	/// END OSGI BundleActivator implementation
    	/// CRUD Operations
    	 * Create a new record in MyDBBean table
    	 * @param field1
    	 * @param field2
    	 * @return the created record
    	public MyDBBean addMyDBBean(String field1, String field2) {	
    		//MyBean is a class generated via CayenneModeler that maps a table in the DB
    		ObjectContext context = getDbContext();
    		MyDBBean obj = createNewObj(context, MyDBBean.class);
    		return obj;
    	 * Deletes the given record from MyDBBean table
    	 * @param id PK of the record
    	public void deleteMyDBBean(int id) {
    		ObjectContext context = getDbContext();
    		MyDBBean o = getByPK(context, id, MyDBBean.ID_PK_COLUMN, MyDBBean.class);
    		deleteObject(context, o);
    	 * Updates field1 for the given record
    	 * @param id PK of the record to change
    	 * @param newField1 new value for field1
    	public void updateMyDBBean(int id, String newField1) {
    		ObjectContext context = getDbContext();
    		MyDBBean o = getByPK(context, id, MyDBBean.ID_PK_COLUMN, MyDBBean.class);
    		if (o == null)
    	 * Retrieves the record identified by the given PK
    	 * @param id PK of the record to return
    	 * @return null if not found
    	public MyDBBean getMyDBBeanByPK(int id) {
    		ObjectContext context = getDbContext(); 
    		return getByPK(context, id, MyDBBean.ID_PK_COLUMN, MyDBBean.class);
    	 * Retrieves the record(s) identified by the given value of field1
    	 * @param field1 filter of the query
    	 * @return the list of retrieved records, null if not found
    	public List<MyDBBean> getMyDBBeanByField1(String field1) {
    		Ordering[] ordering = new Ordering[] {new Ordering(MyDBBean.ID_PK_COLUMN, SortOrder.ASCENDING)};
    		Expression qualifier = ExpressionFactory.matchExp(MyDBBean.FIELD1_PROPERTY, field1);
    		return query(getDbContext(), qualifier, null, 0, ordering, MyDBBean.class, false, true);
    	/// END CRUD Operations
    	/// Internal Utilities
    	private static void initDBConnection() {
    		//stores the objects that can be useful in the life of the bundle
    		dbRuntime = new ServerRuntime("cayenne-MyDomain.xml");
    		dbDS = dbRuntime.getDataSource("MyNode");
    		//loads the classes that maps the DB tables in a OSGI-friendly manner.
    		//"osgicayennemanager" is the package which these classes belong to 
    		List<Class<?>> classes = getClassesOfPackage(FrameworkUtil.getBundle(Activator.class), "osgicayennemanager");
    		for (Class<?> cl : classes) {
    		for (Class<?> cl : classes) {
    	private static List<Class<?>> getClassesOfPackage(Bundle b, String packageName) {
    		BundleWiring wiring = b.adapt(BundleWiring.class);
    		Collection<String> classNames = wiring.listResources(packageName.replace('.', '/'), null, 
    		List<Class<?>> result = new ArrayList<Class<?>>();
    		for (String cName : classNames) {
    			Class<?> c = null;
    			try {
    				c = b.loadClass(cName.replace(".class", "").replace('/', '.'));
    			} catch (ClassNotFoundException e) {
    			if (c != null)
    		return result;
    	protected static Connection getConnection() throws SQLException {
    		return dbDS.getConnection();
    	private static ObjectContext getDbContext() {
    		return dbRuntime.getContext();
    	private <E> E createNewObj(ObjectContext context, Class<E> clazz) {
    		return context.newObject(clazz);
    	private boolean commitObjects(ObjectContext context) {
    		try {
    			return true;
    		} catch(CayenneRuntimeException e){
    			manageCayenneException(e, context);
    			return false;
    		} catch (Exception e) {
    			manageCayenneException(e, context);
    			return false;
    	protected void deleteObject(ObjectContext context, Object o) {
    		if (o == null) 
    		try {
    		} catch(CayenneRuntimeException e){
    			manageCayenneException(e, context);
    		} catch (Exception e) {
    			manageCayenneException(e, context);
    	private <E> List<E> query(ObjectContext context, Expression qualifier, Integer maxResult, Integer offset, 
    			Ordering[] ordering, Class<E> clazz, boolean setDistinct, boolean enableCache) {
    		SelectQuery select = new SelectQuery(clazz, qualifier);
    		if (enableCache) {
    		if (ordering != null) {
    			for (int i = 0; i < ordering.length; i++) {
    				if (ordering[i] != null)
    		if (maxResult != null && maxResult > 0)
    		if (offset != null && offset.intValue() > 0)
    		if (setDistinct)
    		return context.performQuery(select);
    	private <E> E getByPK(ObjectContext context, int pkID, String key, Class<E> clazz) {
    		ObjectId id = new ObjectId(clazz.getSimpleName(), key, pkID);
    		ObjectIdQuery query = new ObjectIdQuery(id, false, ObjectIdQuery.CACHE_REFRESH);
    		return (E)Cayenne.objectForQuery(context, query);
    	private static void manageCayenneException(Exception e, ObjectContext context) {
    		System.err.println("Error while commmitting changes due to " + e);
    		} catch(Exception e1){
    			System.err.println("Error while rollback changes due to " + e1);
    	/// END Internal Utilities

    public by cghersi @ Abodata DEV Team  3319  1  5  0

    Apache Cayenne: correctly load classes under OSGI environment

    This step is required to correctly use Cayenne framework under OSGi environment. Simply adjust the class-loading issues that can arise in OSGi.
    private void initCayenneClasses() {
    	String packageName = "myPackage.with.cayenne.autogenerated.classes";
    	List<Class<?>> classes = getClassesOfPackage(FrameworkUtil.getBundle(this.getClass()), packageName);
    	for (Class<?> cl : classes) {
    	for (Class<?> cl : classes) {

    public by cghersi  3128  0  7  1

    Expose an Apache CXF Server in Java

    Apache CXF make VERY simple the exposure of a basic web service. Then, a lot of other feature may be added, like security, REST-ification, re-routing, etc.
    import javax.jws.WebService;
    @WebService(targetNamespace = "http://com.snip2code.api")
    public interface IMyAPI {
    	public boolean save(String values);
    	public String getStringVal();
    @WebService(serviceName="MyAPIService", portName="apiName")
    public class MyAPI implements IMyAPI {
    	public boolean save(String values) {
    		//do stuff here...
    	public String getStringVal() {
    		return "Hello world";

    public by cghersi  2880  2  7  1

    Enable HTTPS on Tomcat

    How to make the apps running on Tomcat able to publish over https
    // 1. Export certificate request with keytool
    // 1.1 Generate the keytool command with the form at this URL:
    // 1.2 The result will be a pair of file mydomain.jks and mydomain.csr
    // 2. Ask the certificate to the cert authority
    // 2.1 The result will be a pair of file mydomain.pem and mydomain.p7b
    // 3. Import mydomain.pem into mydomain.jks (assuming your alias is "server")
    keytool -import -v -trustcacerts -alias server -file mydomain.pem -keystore iot_bissell_com.jks -storepass <secret_psw>
    // 4. Edit conf/server.xml in the deployment of Tomcat, add this line 
    // (under the element <Service name="Catalina">):
    <Connector SSLEnabled="true" 
     clientAuth="false" keyAlias="server" 
     keystorePass="<secret_psw>" maxThreads="150" port="8080" 
     protocol="HTTP/1.1" scheme="https" secure="true" sslProtocol="TLS"/>            

    public by cghersi  3166  1  7  0

    Consume a web service using Apache CXF client library

    Apache CXF may also be used to consume a web service. Obviously, the match of client and server both with CXF make the development very simple, as the same IMyAPI interface may be used as a contract between server and client.
    public class CxfClientImpl {
        private static final QName SERVICE_NAME = new QName("http://com.snip2code.api", "MyAPIService");
        private static final QName PORT_NAME_DB = new QName("http://com.snip2code.api", "apiName");
    	private IMyAPI portAPI;
    	public CxfClientImpl() {
    		//initialize web service utilities:
    		URL wsdlURL = null;
    		String location = "";
    		try {
    			wsdlURL = new URL(location);
    		} catch (MalformedURLException e) {
    			log.error("Malformed Url:" + location + ", due to:" + e.getMessage());
            Service service = Service.create(SERVICE_NAME);
            service.addPort(SERVICE_NAME, SOAPBinding.SOAP11HTTP_BINDING, wsdlURL.toString());
            portAPI = service.getPort(PORT_NAME, IMyAPI.class); 
    • Public Snippets
    • Channels Snippets