working on it ...

Filters

Explore Public Snippets

Sort by

Found 42k snippets matching: language=java

    public by cghersi modified Aug 20, 2013  468142  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) {
    		log.info("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 = "127.0.0.1"; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
    
    		log.info("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);
    		conf.setVersion(Soap12.getInstance());
    		factory.setBindingConfig(conf);
    
    		factory.setServiceClass(MyInterface.class);
    		factory.setAddress(address);
    		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();
    	jmsConfig.setUseJms11(true);
    	jmsConfig.setTargetDestination(queueName);
    	jmsConfig.setConnectionFactory(connectionFactory);
    	if (receiveTimeout != null)
    		jmsConfig.setReceiveTimeout(receiveTimeout);
    	jmsConfigFeature.setJmsConfig(jmsConfig);
    	return jmsConfigFeature;
    }

    public by lbottaro modified Mar 24, 2014  406050  1  7  9

    Simple CORBA java server

    This code shows an example of simple corba server in java. A CORBA server needs a local ORB object. The server instantiates an ORB and registers its servant objects so that the ORB can find the server when it receives an invocation for it. the server is a process that instantiates one or more servant objects. Each servant implements the
    // The package containing our stubs.
    import HelloApp.*;
    
    // HelloServer will use the naming service.
    import org.omg.CosNaming.*;
    
    // The package containing special exceptions thrown by the name service.
    import org.omg.CosNaming.NamingContextPackage.*;
    
    // All CORBA applications need these classes.
    import org.omg.CORBA.*;
    
    public class HelloServer 
    {
      public static void main(String args[])
      {
        try{
           // Create and initialize the ORB
          ORB orb = ORB.init(args, null);
          
          // Create the servant and register it with the ORB
          HelloServant helloRef = new HelloServant();
          orb.connect(helloRef);
          
          // Get the root naming context
        org.omg.CORBA.Object objRef = 
    orb.resolve_initial_references("NameService");
          NamingContext ncRef = NamingContextHelper.narrow(objRef);
          
          // Bind the object reference in naming
          NameComponent nc = new NameComponent("Hello", "");
          NameComponent path[] = {nc};
          ncRef.rebind(path, helloRef);
          
          // Wait for invocations from clients
          java.lang.Object sync = new java.lang.Object();
          synchronized(sync){
            sync.wait();
          }
              } catch(Exception e) {
            System.err.println("ERROR: " + e);
            e.printStackTrace(System.out);
          }  
      }
    }
    
    class HelloServant extends _HelloImplBase
    {
      public String sayHello()
      {
        return "\nHello world!!\n";
        }
    }
        

    public by przodownikR1 modified Jul 21, 2015  394512  0  3  0

    example create datasource in javaConfig with full desc and params

    example create datasource in javaConfig with full desc and params: db_config_full.java
    @Bean
      public DataSource dataSource() {
        final DataSource dataSource = new DataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        dataSource.setTestOnBorrow(true);
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnReturn(false);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setValidationInterval(30000);
        dataSource.setTimeBetweenEvictionRunsMillis(5000);
        dataSource.setMaxActive(100);
        dataSource.setMinIdle(10);
        dataSource.setMaxWait(10000);
        dataSource.setInitialSize(10);
        dataSource.setRemoveAbandonedTimeout(3600);
        dataSource.setRemoveAbandoned(true);
        dataSource.setLogAbandoned(true);
        dataSource.setMinEvictableIdleTimeMillis(30000);
        return dataSource;
      }
    
    

    public by Derek Pauley modified Sep 29, 2015  381076  17  3  1

    SVNKit export from Subversion example

    SVNKit export from Subversion example: SvnExportExample.java
    import java.io.File;
    
    import org.tmatesoft.svn.core.SVNDepth;
    import org.tmatesoft.svn.core.SVNException;
    import org.tmatesoft.svn.core.SVNURL;
    import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
    import org.tmatesoft.svn.core.io.SVNRepository;
    import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
    import org.tmatesoft.svn.core.wc.SVNClientManager;
    import org.tmatesoft.svn.core.wc.SVNRevision;
    import org.tmatesoft.svn.core.wc.SVNUpdateClient;
    import org.tmatesoft.svn.core.wc.SVNWCUtil;
    
    
    public class SvnExportExample {
    
    	public static void main(String... args){
    		final String url = "svn://cavcops01.global.local/skunkworks";
    		final String destPath = "c:/temp/svntest";
    		
    		SVNRepository repository = null;
    		
    		try{
    			//initiate the reporitory from the url
    			repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
    			//create authentication data
    			ISVNAuthenticationManager authManager = 
    					SVNWCUtil.createDefaultAuthenticationManager("cliff.darling", "svnuser");
    			repository.setAuthenticationManager(authManager);
    			//output some data to verify connection
    			System.out.println( "Repository Root: " + repository.getRepositoryRoot( true ) );
    			System.out.println(  "Repository UUID: " + repository.getRepositoryUUID( true ) );
    			//need to identify latest revision
    			long latestRevision = repository.getLatestRevision();
    			System.out.println(  "Repository Latest Revision: " + latestRevision);
    			
    			//create client manager and set authentication
    			SVNClientManager ourClientManager = SVNClientManager.newInstance();
    			ourClientManager.setAuthenticationManager(authManager);
    			//use SVNUpdateClient to do the export
    			SVNUpdateClient updateClient = ourClientManager.getUpdateClient( );
    			updateClient.setIgnoreExternals( false );
    			updateClient.doExport( repository.getLocation(), new File(destPath), 
    					SVNRevision.create(latestRevision), SVNRevision.create(latestRevision), 
    					null, true, SVNDepth.INFINITY);
    			
    		} catch (SVNException e) {
    			e.printStackTrace();
    		}finally {
    			System.out.println("Done");
    		}
    	}
    }
    
    
    

    public by alaindresse modified Feb 22, 2013  370568  3  6  0

    Gist to demonstrate ajax request on checkbox

    Gist to demonstrate ajax request on checkbox: ajax-checkbox.tag ajaxCheckbox.java main.js view.jsp
    // Tagfile to be placed in WEB-INF/tags/ui
    
    <%@tag import="com.liferay.portal.kernel.util.HtmlUtil"%>
    <%@tag import="com.liferay.portal.kernel.language.LanguageUtil"%>
    <%@tag import="com.liferay.portal.kernel.util.StringPool"%>
    <%@tag import="com.liferay.portal.util.PortalUtil"%>
    <%@ attribute 
    	name="resourceUrl"
    	description="URL to process the ajax call. ServeResource parameter: newValue (0 or 1 for unchecked, checked). responseData is not used. An alert is open on failure."
    	type="String" 
    	required="true" %>
    <%@ attribute
    	name="name"
    	description="Checkbox name. A random name is set if this is not provided."
    	type="String"%>
    <%@ attribute
    	name="label"
    	description="Checkbox label"
    	type="String"
    	required="true" %>
    <%@ attribute
    	name="initialValue"
    	description="Initial value of checkbox"
    	type="Boolean"
    	required="true" %>
    <%@ attribute
    	name="successCallback"
    	description="ajax callback on success. Parameters are: checkbox node, response data."
    	type="String" %>
    <%@ attribute
    	name="failureCallback"
    	description="Callback on failure. Parameter is checkbox name."
    	type="String" %>
    	
    <%@ taglib uri="http://liferay.com/tld/theme" prefix="theme" %>
    <%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
    <%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
    <portlet:defineObjects />
    <theme:defineObjects />
    
    <%
    if (name == null){
    	name = PortalUtil.generateRandomKey(request, "ajaxToggleKey");
    }
    String onclick = "bb_ajaxCheckbox('" + resourceUrl  + "', this, " + successCallback + "," + failureCallback + ")";
    %>
    <aui:input type="checkbox" onClick="<%=onclick%>" value="<%=initialValue%>" name="<%=name%>" label="<%=label%>" /> 
    
    
    	@Override
    	public void serveResource(ResourceRequest resourceRequest,
    			ResourceResponse resourceResponse) throws IOException,
    			PortletException {
    		
    		_log.info("processing resource");
    		Map<String, String[]> parameters = resourceRequest.getParameterMap();
    		for (String key : parameters.keySet()){
    			_log.info(key + ":[" + StringUtil.merge(parameters.get(key)) + "]");
    		}
    
    
    		String resourceId = resourceRequest.getResourceID();
    		if (Validator.isNotNull(resourceId)) {
    			String cmd = resourceRequest.getResourceID();
    			if (cmd.equals("testToggle")) {
    				try {
    					boolean newValue = ParamUtil.getBoolean(resourceRequest,"newValue");
    					_log.info(String.valueOf(newValue));
    					if (!newValue){
    						throw new IOException("simulate failure");
    					} else {
    						resourceResponse.setContentType("text/plain");
    						resourceResponse.getWriter().write("this is the response data");
    					}
    				} catch(Exception e){
    					throw new IOException(e);
    				}
    			}
    		}
    		super.serveResource(resourceRequest, resourceResponse);
    	}
    
    
    Liferay.provide(
    	window, 
    	"bb_ajaxCheckbox",
    	function(resourceUrl, checkbox, success, failure){
    		var A = AUI();
    		var checked = false;
    		var checkbox = A.one(checkbox);
    		var label = null;
    		if (checkbox) {
    			checked = checkbox.attr('checked');
    			var labelSelector = 'label[for="' + checkbox.attr("name") + '"]';
    			if (labelSelector) label = A.one(labelSelector);
    		}
    		var ajaxCallbacks = {
    			success: function(){
    				if (label) label.removeClass("ajax-loading");
    				if (success) success(checkbox, this.get('responseData'));
    			},
    			failure: function(){
    				if (failure) failure(checkbox);
    			}
    		};
    		if (label) label.addClass("ajax-loading");
    		A.io.request(resourceUrl, {
    			method: 'GET',
    			data: {newValue: checked,},
    			on : ajaxCallbacks,
    		});
    	}, [ 'aui-io-request' ]
    );
    
    <%@ taglib tagdir="/WEB-INF/tags/ui" prefix="bamboost-ui"%>
    <%@ include file="/html/init.jsp"%>
    
    <portlet:resourceURL id="testToggle" var="testToggleURl"/>
    <bamboost-ui:ajax-checkbox
    	name="myname" 
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="no callback"/>
    <bamboost-ui:ajax-checkbox
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="testSuccess"
    	successCallback="testSuccess"/>
    <bamboost-ui:ajax-checkbox
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="testFailure"
    	failureCallback="testFailure"/>
    	
    	<script>
    	function testSuccess(checkbox, responseData) {
    		alert(checkbox.attr("name") + "\n" + responseData);
    	};
    	function testFailure() {alert("failure");};
    	</script>
    
    

    public by lbottaro modified Mar 31, 2014  355645  0  7  3

    Vendor class - Java example for marshalling/unmarshalling, using JAX-B XmlID annotation

    This is the Vendor class, where the XmlElement annotation sets the vendorID attribute as XmlID. Such key will match the reference set in Card class, using annotation XmlIDREF.
    package com.test.jaxb;
    
    import java.io.Serializable;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlID;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Vendor implements Serializable {
    	
    	 @XmlElement(name = "vendor-ID")
    	 @XmlID
    	private String vendorID;
    	 @XmlElement(name = "vendor-Name")
    	private String vendorName;
    	/**
    	 * @param vendorID
    	 * @param vendorName
    	 */
    	public Vendor(String vendorID, String vendorName) {
    		super();
    		this.vendorID = vendorID;
    		this.vendorName = vendorName;
    	}
    	/**
    	 * 
    	 */
    	public Vendor() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    	/**
    	 * @return the vendorID
    	 */
    	public String getVendorID() {
    		return vendorID;
    	}
    	/**
    	 * @param vendorID the vendorID to set
    	 */
    	public void setVendorID(String vendorID) {
    		this.vendorID = vendorID;
    	}
    	/**
    	 * @return the vendorName
    	 */
    	public String getVendorName() {
    		return vendorName;
    	}
    	/**
    	 * @param vendorName the vendorName to set
    	 */
    	public void setVendorName(String vendorName) {
    		this.vendorName = vendorName;
    	}
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Vendor [vendorID=" + vendorID + ", vendorName=" + vendorName
    				+ "]";
    	}
    }
    

    public by sukhjinderkahlon modified Mar 9, 2016  325946  6  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 java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    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
    				filePath=Path;
    
    			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{
    
    			try{
    
      			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
    
      			String CellData = Cell.getStringCellValue();
    
      			return CellData;
    
      			}catch (Exception e){
    
    				return"";
    
      			}
    
        }
    
    
        
      //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	{
    
    			try{
    
      			Row  = ExcelWSheet.getRow(RowNum);
    
    			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    
    			if (Cell == null) {
    
    				Cell = Row.createCell(ColNum);
    
    				Cell.setCellValue(Result);
    
    				} else {
    
    					Cell.setCellValue(Result);
    
    				}
    
      // Constant variables Test Data path and Test Data file name
    
      				FileOutputStream fileOut = new FileOutputStream(filePath);
    
      				ExcelWBook.write(fileOut);
    
      				fileOut.flush();
    
    					fileOut.close();
    
    				}catch(Exception e){
    
    					throw (e);
    
    			}
    
    		}
    
    	
    }
              

    public by PLAT.ONE @ PLAT.ONE modified Sep 18, 2015  324004  2  6  0

    How to save a custom property on PLAT.ONE, aka to enhance the data model of a device

    Custom properties are key-value pairs associated to an entity in PLAT.ONE. You can attach at runtime those new properties
    import java.util.ArrayList;
    import java.util.List;
    
    import com.abodata.plat1.nodeInfo.WSNNodeType;
    import com.abodata.plat1.system.ICredentialUtils;
    import com.abodata.plat1.utils.APIFilter;
    import com.abodata.plat1.velocity.client.IPlatoneAPI;
    import com.abodata.plat1.ws.velocity.IProxyCustomProperty;
    import com.abodata.plat1.ws.velocity.IProxyPhysicalNode;
    import com.abodata.plat1.ws.velocity.IProxyPlatUser;
    import com.abodata.plat1.ws.velocityInfo.ProxyObjType;
    import com.abodata.plat1.properties.CPAllowable;
    
    public class AddCustomPropertyExample {
    
    	public void addProperty() throws Exception {
    		
    		IPlatoneAPI apiMan = YourServiceActivator.getApiMan();
    		ICredentialUtils creds = YourServiceActivator.getCredentialUtils();
    		
    		//let's retrieve the first available camera:
    		List<APIFilter> filters = new ArrayList<APIFilter>();
    		filters.add(new APIFilter("type", new String[] { WSNNodeType.ENDPOINT.getType() + "", WSNNodeType.ROUTER.getType() + "" }));
    		List<IProxyPhysicalNode> cameras = apiMan.DB_GetVisiblePhysicalNode(null, filters, true, 0, 1);
    		IProxyPhysicalNode camera =	cameras.get(0);
    		
    		//get the current user:
    		IProxyPlatUser curUser = apiMan.DB_GetPlatUser(creds.getUserName(), creds.getPsw());
    		
    		//add a property to the camera:
    		IProxyCustomProperty p = apiMan.DB_AddCustomProperty(creds.getAppGardenId(), "resolution", false, "1280x768", 
    				ProxyObjType.customProperty, curUser.getId(), camera.getId(), ProxyObjType.physNode, CPAllowable.all, 
    				CPAllowable.all);
    		if (p != null)
    			System.out.println("Property added!");
    		else
    			System.out.println("Something wrong...");
    	}
    }
    

    public by cghersi @ Thotpot alumni modified May 4, 2013  302873  0  5  0

    Java: generate hprof during runtime

    To generate hprof may be interesting for debug purpose, most of all before an OutOfMemory occurs on production applications! This .ini option halps to create an hprof to be analyzed before the occurrence of memory errors. See http://docs.oracle.com/javase/7/docs/technotes/samples/hprof.html for further details
    java -Xrunhprof:heap=sites,depth=10,thread=y,doe=y ...other jvm options in ini file...

    public by lbottaro modified Mar 23, 2014  293969  1  6  3

    Simple RMI Java client

    This is a simple RMI client implementation. Here the client program obtains a stub for the registry on the server's host, then looks up the remote object's stub by name in the registry. Finally invokes the sayHello method on the remote object using the stub. Here the client invokes the method exposes by Hello remote interface. Note that if no
    package example.hello;
    
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;
    
    public class Client {
    
        private Client() {}
    
        public static void main(String[] args) {
    
    	String host = (args.length < 1) ? null : args[0];
    	try {
    	    Registry registry = LocateRegistry.getRegistry(host);
    	    Hello stub = (Hello) registry.lookup("Hello");
    	    String response = stub.sayHello();
    	    System.out.println("response: " + response);
    	} catch (Exception e) {
    	    System.err.println("Client exception: " + e.toString());
    	    e.printStackTrace();
    	}
        }
    }    
    • Public Snippets
    • Channels Snippets