working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,906 snippets matching: methods

    public by cghersi  468664  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 micheleaiello  263153  0  6  1

    Mark methods as deprecated

    Mark a method (or a whole class) as deprecated. Works in Xcode v4.2 and higher.
    __attribute((deprecated("Use xxx: instead")))
    
    examples:
    
    @interface MyClass : NSObject
      - (void)myOldMethod:(id)param __attribute__((deprecated));
    @end
    
    __attribute__((deprecated))
    @interface MyOldClass : NSObject
    @end
    
    __attribute__((deprecated))
    void myOldFunction(...) {
    }

    public by dave83  223923  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 HeathDernovich  179062  0  4  0

    extend, toggleClass, and equals methods

    extend, toggleClass, and equals methods: objProtaddl.js
    // functional additions to the Object prototype
    
    Object.prototype.extend = function() {
      if (arguments.length === 0)
        return this;
     
      for (var i = 0; i < arguments.length; i++) {
        for (var property in arguments[i]) {
          if (arguments[i].hasOwnProperty(property))
            this[property] = arguments[i][property];
        }
      }
      return this;
    };
    
    
    Object.prototype.equals = function(x) {
      var p;
      for(p in this) {
        if (typeof(x[p]) == "undefined")
          return false;
      }
      
      for(p in this) {
        if (this[p]) {
          switch(typeof(this[p])) {
            case "object":
              if (!this[p].equals(x[p])) {
                return false;
              }
              break;
            case "function":
              if (typeof(x[p]) == "undefined" ||(p != "equals" && this[p].toString() != x[p].toString())) {
                return false;
              }
              break;
            default:
              if (this[p] != x[p]) {
                return false;
              }
          }
        }
        else {
          if (x[p]) {
            return false;
          }
        }
      }
      
      for(p in x) {
        if(typeof(this[p])=="undefined") {
          return false;
        }
      }
      
      return true;
    };
    
    
    Array.prototype.inArray = function (value) {
      for (var i = 0; i < this.length; i++) {
        if (typeof value === "object") {
        
          // If both are objects, uses the equals function
          if (typeof this[i] === "object" && value.equals(this[i])) {
              return i;
          }
        }
        else if (this[i] === value) {
          return i;
        }
      }
      
      return false;
    };
    
    
    function toggleClass(id, className) {
      var element = document.getElementById(id);
      var classes = element.className.split(/s+/);
      var length = classes.length;
      var found = classes.inArray(className);
      
      if (found !== false) {
        classes.splice(found, 1);
      }
        
      // The className is not found
      if (length === classes.length) {
        classes.push(className);
      }
        
      element.className = classes.join(" ");
    };
    
    
    
    

    public by cghersi @ MailUp API DEV  206862  8  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by lbottaro  170295  0  6  0

    Simple RMI Java interface

    A simple RMI interface example. A remote interface extends the interface java.rmi.Remote and declares a set of remote methods. Each remote method must declare java.rmi.RemoteException (or a superclass of RemoteException) in its throws clause, in addition to any application-specific exceptions. This interface declares just one method, sayHello, w
    package example.hello;
    
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    
    public interface Hello extends Remote {
        String sayHello() throws RemoteException;
    } 

    public by cghersi @ MailUp API DEV  113014  11  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by mporru  15745  221  8  2

    Trim, TrimStart, TrimEnd methods in java

    public static String TrimEnd(String input, String charsToTrim)
    	{
    		return input.replaceAll("[" + charsToTrim + "]+$", "");		
    	}	
    	
    	public static String TrimStart(String input, String charsToTrim)
    	{
    		return input.replaceAll("^[" + charsToTrim + "]+", "");	
    	}
    
    	public static String Trim(String input, String charsToTrim)
    	{
    		return input.replaceAll("^[" + charsToTrim + "]+|[" + charsToTrim + "]+$", "");	
    	}

    public by cghersi @ MailUp API DEV  84187  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  3589  3  6  0

    C# background worker main methods

    Here the basic implementation of the c# thread background worker methods. In this case the thread starts once user clicks on a button. 1) DoWork() method is executed till ends. 2) During execution, you can update the progress execution status invoking ReportProgress() method. This handles the percentage of progress and a message string to b
    /// <summary>
    /// Launch thread
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void m_button_generateTestList_Click(object sender, EventArgs e)
    {
    	if (m_backgroundWorker.IsBusy != true)
    	{
    		m_backgroundWorker.RunWorkerAsync();
    	}
    	else
    	{
    		MessageBox.Show("Thread is busy, please wait...");
    		return;
    	}
    }
    
    /////////////
    #region BACKGROUND WORKER METHODS
    /// <summary>
    /// DoWork
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void m_backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
    	//some method to execute here;
    
      //update progress info
      m_backgroundWorker.ReportProgress(0, "");
    }
    
    /// <summary>
    /// ProgressChanged
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void m_backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    	m_panel_progress.Visible = true;
    	m_label_progress.Text = e.UserState.ToString();
    }
    
    /// <summary>
    /// RunWorkerCompleted
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void m_backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    	m_label_progress.Text = "Operation completed!";
    }
    
    
    #endregion
    /////////////
    
    
    • Public Snippets
    • Channels Snippets