working on it ...

Filters

Explore Public Snippets

Sort by

Found 874 snippets matching: invoke

    public by lbottaro  901781  60  8  1

    How to remove all checked out files in clearcase

    This cleartool command lists all the checkout files (both from the current directory and from the entire view) searching in each directory or vob path. For each element found, it invokes the command to remove the checkout.
    # Remove ALL checked out files from view in the entire vobs
    cleartool lsco -cview -me -avobs -short | xargs cleartool unco -rm 
    
    # Remove ALL checked out files from the current directory on only
    cleartool lsco -cview -me -rec -short | xargs cleartool unco -rm 

    public by cghersi  468732  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  406586  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 lbottaro  294425  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 by dave83  223941  8  7  0

    How to run methods in class marked with specific Java annotation

    The snippet shows how to invoke only methods of a class marked with specific annotation. The list of methods class (MyTest) is returned using reflection. Annotations are returned via getAnnotation() method. The method is executed via invoke() method.
    import java.lang.reflect.Method;
    
    public class MyTest {
    
        @MyAnnotation
        public void method1() {
          System.out.println("method1");
        }
    
        public void method2() {
          System.out.println("method2");
        }
        
        @MyAnnotation
        public void method3() {
          System.out.println("method3");
        }
        
        public static void main(String[] args) {
    
            MyTest runner = new MyTest();
            Method[] methods = runner.getClass().getMethods();
    
            for (Method method : methods) {
                MyAnnotation annos = method.getAnnotation(MyAnnotation.class);
                if (annos != null) {
                    try {
                        method.invoke(runner);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    } 
                            

    public by cghersi @ MailUp API DEV  84199  21  6  0

    Base class to setup the secure communication towards MailUp REST API

    This is how to setup a secure connection towards MailUP RESTful API. This base class can be extended with methods that directly call those web methods
    public class BaseAPIInvoker
    { 
        #region App Credentials
    
        protected static String ClientId = "take from your console";
        protected static String ClientSecret = "take from your console"; 
        protected static String UserName = "mxxx@number"; 
    	protected static String Password = "pswsupersecret"; 
        protected static String bypassToken = String.Empty;
    
        #endregion
    
        #region Endpoints
    
        protected static String OAuthAuthorization = "https://services.mailup.com/Authorization/OAuth/Authorization";
        protected static String OAuthToken = "https://services.mailup.com/Authorization/OAuth/Token";
        protected static String BaseEndpoint = "https://services.mailup.com/API/v1/Rest/ConsoleService.svc";
    
        #endregion
    
        public OAuth2Client client;
    
        public BaseAPIInvoker()
        {
            client = new OAuth2Client(OAuthToken, OAuthAuthorization);
            
            client.ClientId = ClientId;
            client.ClientSecret = ClientSecret;
            client.Username = UserName;
            client.Password = Password;
    
            client.ForceToken = bypassToken;
            
            client.GetToken();
        }
    }

    public by lbottaro  3637  3  6  3

    How to invoke the EJB remote interface - Java client application

    The codes shows how to remotely invoke the methods exposed by EJB remote interface. The client app will invoke the remote methods using a JNDI lookup. The appName and beanName refer to the remote application and ejb names to be referenced by the client app. Notice the usage of InitialContext, setting variables INITIAL_CONTEXT_FACTORY and PROVIDE
    package com.test.ejbclient;
    
    import java.util.List;
    import java.util.Properties;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    
    import com.test.example.interfaces.IPerson;
    import com.test.example.person.*;
    
    public class Ejbclient {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		
    		IPerson person = doLookup();
    		Person p = person.getPerson(4);
    		System.out.println(p.toString());
    		
    		List<Person> pList = person.getPersonList();
    		for (Person person2 : pList) {
    			System.out.println(person2.toString());
    		}
    
    	}
    	
    	private static IPerson doLookup() {
    		IPerson bean = null;
    		try {
    			bean = lookupRemoteStatelessPersonEJB();
    		} catch (NamingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return bean;
    	}
    
    	private static String getLookupName() {
    	
    		//The app name
            final String appName = "PersonWebAppEJB_Final";
            
            // The EJB name which by default is the simple class name of the bean implementation class
            final String beanName = "PersonEJB";
            
            // the remote view fully qualified class name
            final String viewClassName = IPerson.class.getName();
            
            // let's do the lookup
            String url = appName + "/" +beanName + "!" + viewClassName;
            System.out.println("URL: " + url);
    		
    		return url;
    	}
    	
    	private static IPerson lookupRemoteStatelessPersonEJB() throws NamingException {
    		Properties env = new Properties(); 
    
    		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
    		env.put(Context.PROVIDER_URL, "remote://10.0.2.15:4447/");
    		
    		String userName = "user";
    		String password = "password";
    		env.put(Context.SECURITY_PRINCIPAL, userName);
    		env.put(Context.SECURITY_CREDENTIALS, password);
    		env.put("jboss.naming.client.ejb.context", true);
    		
    		InitialContext context = new InitialContext(env); 
    		
            // let's do the lookup
            String url = getLookupName();
    
            return (IPerson) context.lookup(url);
        }
    
    }
    

    public by cghersi  2720  1  6  4

    Safely Manage Asynchronous Invoke in Winforms

    When dealing with multithreading in WinForms one of the worst issues you encounter are the management of Invoke() method on controls. Instead of spreading the code of blocks if (control.InvokeRequired) { controlInvoke(...); } else { ... } this is a little method that can elegantly solve your issues!
    private delegate object SafeInvokeCallback(Control control, Delegate method, params object[] parameters);
    public static object SafeInvoke(this Control control, Delegate method, params object[] parameters)
    {
        if (control == null)
            throw new ArgumentNullException("control");
        if (control.InvokeRequired)
        {
            log.DebugFormat("Calling with BeginInvoke: {0}", method.Method.Name);
            IAsyncResult result = null;
            try { result = control.BeginInvoke(new SafeInvokeCallback(SafeInvoke), control, method, parameters); }
            catch (InvalidOperationException) { /* This control has not been created or was already (more likely) closed. */ }
            if (result != null)
                return control.EndInvoke(result);
        }
        else
        {
            log.DebugFormat("Calling sync: {0}", method.Method.Name);
            if (!control.IsDisposed)
                return method.DynamicInvoke(parameters);
        }
        return null;
    }
    

    public by cghersi @ MailUp API DEV  911  17  5  1

    Import a list of recipients through MailUp REST API

    This is an example on how to consume the API related to the import of recipients. The composed uri can be augmented with querystring parameters to better refine the criteria of import.
    public class ImportInvoker : BaseAPIInvoker
    {
    	public int ImportRecipientsIntoList(int idList)
    	{
    	    String Uri = String.Format("{0}/Console/List/{1}/Recipients", BaseEndpoint, idList);
    		
    		//Uri += "?ConfirmEmail=true"; add querystring to refine import criteria 
    		
    		var listRecipients = PrepareRecipientsForImport(10);
    		Object response = client.RequestResource<Int32>(Uri, HttpMethod.Post, listRecipients, null, null, null, null);
    		Int32 idImport = Convert.ToInt32(response);
    		return idImport;
    	}
    	
    	protected Object PrepareRecipientsForImport(int numOfRecipients)
        {
        	var listRecipients = new List<Object>();
        
        	for (int i = 0; i < numOfRecipients; i++)
            {
    	        var newRecipient = new Dictionary<String, Object>();
    	        var newFields = new List<Object>();
    	        newFields.Add(new Dictionary<String, Object>() { 
    	                                                             {"Id",1},
    	                                                             {"Value",String.Format("name-{0}", i)}  
    	                                                           });
    	        newFields.Add(new Dictionary<String, Object>() { 
    	                                                             {"Id",2},
    	                                                             {"Value",String.Format("lastname-{0}", i)}  
    	                                                           });
    	
    	        newRecipient.Add("Name", String.Format("TestRecipient_{0}", i));
    	        newRecipient.Add("Fields", newFields);
    	
    	        if (i % 2 == 0)
    	            newRecipient.Add("Email", String.Format("UnitTestRecipient{0}@even.test", i));
    	        else
    	            newRecipient.Add("Email", String.Format("UnitTestRecipient{0}@odd.test", i));
    	
    	        if (i % 2 == 0)
    	            newRecipient.Add("MobilePrefix", "+39");
    	        else
    	            newRecipient.Add("MobilePrefix", "+42");
    	
    	        newRecipient.Add("MobileNumber", String.Format("3390123456{0}", i));
    	
    			listRecipients.Add(newRecipient);
            }
    
            return listRecipients;
        }
    }
    

    public by cghersi  2579  0  7  0

    How to create a new SqlCommand to invoke a Stored Procedure

    This method creates a new SqlCommand for a stored procedure invocation. It sets all the relevant information for a stored procedure that can be then executed in ADO.NET environment
    static public SqlCommand CreateStoredProc(SqlConnection connection, string name)
    {
         SqlCommand newSPCmd = new SqlCommand();
         newSPCmd.CommandType = CommandType.StoredProcedure;
         newSPCmd.Connection = connection;
         newSPCmd.CommandText = name;
         newSPCmd.CommandTimeout = WebConfig.Current.DBConnectionTimeout;   //default timeout for snip2code
         return newSPCmd;
    }
    • Public Snippets
    • Channels Snippets