marți, 29 martie 2016

PostgreSQL: currval: Return the value of the most recently id generated

--Create table
create table geoipv4.geoipsv4def(
 -- use BIGSERIAL to have an auto-incremented key
 geoipsv4id BIGSERIAL,
 ipStart text, ipEnd text,
 ipNumberStart decimal,ipNumberEnd decimal,
 countryCode text,
 countryName text);



-- Insert a row into the newly created table
INSERT INTO geoipv4.geoipsv4def
   (ipStart,ipEnd, ipNumberStart, ipNumberEnd,
   countryCode,countryName)
VALUES
   ('41.207.0.0','41.207.31.255','701431808','701439999','CI','Cote D''Ivoire');

-- Select the last generated id
SELECT currval('geoipv4.geoipsv4def_geoipsv4id_seq');

-- Select the last inserted row
Select * from geoipv4.geoipsv4def
where geoipsv4id in
  (SELECT currval('geoipv4.geoipsv4def_geoipsv4id_seq'));


HTML: Simple sample of how to add a search form/control only for a specific site



The code for the search control is below:

<form action="http://www.google.com/search" method="get" name="search">
    <label>Search my blog for:</label>
    <input name="q" />
    <input name="site" type="hidden" value="georgelache.blogspot.com" />
    <input name="sitesearch" type="hidden" value="georgelache.blogspot.com" />
    <input name="sitesearch2" type="hidden" value="georgelache.blogspot.com" />
    <input alt="Search" border="0" height="22" name="search-image" src="images/search.gif" type="image" width="22" />
</form>

luni, 28 martie 2016

Java: URL.getContent() Sample

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class ContentGetter {
 void printContentType(String url) {
  // Open the URL for reading
  try {
   URL u = new URL(url);
   Object o = u.getContent();
   System.out.println("I got a " + o.getClass().getName());
  } catch (MalformedURLException ex) {
   System.err.println(url + " is not a parseable URL");
  } catch (IOException ex) {
   System.err.println(ex);
  }
 }
}


import org.junit.Test;
import junit.framework.TestCase;
public class Test_ContentGetter extends TestCase{

 @Test
 public void test_printContentType() {
  ContentGetter contentG = new ContentGetter(); 
  contentG.printContentType("https://lh3.googleusercontent.com/"
    + "--Oiu2RWjYnY/VqtIQuFdYCI/AAAAAAAAkCU/"
    + "QuuYvZsHqjgWVSMIBqTYMgvlTMAiZ2GAQCCo/"
    + "s1280-Ic42/20160122_193915.jpg");
  contentG.printContentType("http://georgelache.blogspot.ro"
    + "/2015/06/java-making-remote-service.html");
 }
}
Output:
I got a sun.awt.image.URLImageSource
I got a sun.net.www.protocol.http.HttpURLConnection$HttpInputStream


vineri, 25 martie 2016

Java: InetAddress Sample

package testinetaddress;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestByName {
 public static void main(String[] args) {
  try {
   InetAddress address = InetAddress.getByName("www.georgelache.blogspot.com");
   System.out.println(address.getHostName());
   System.out.println(address);

   InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
   for (InetAddress addr : addresses) {
    System.out.println(addr);
   }
   
   InetAddress me = InetAddress.getLocalHost();
   System.out.println(me);
   
   // This method can create 
   // addresses for hosts that do not exist or cannot be resolved:
   byte[] addressB = {10, (byte)205, 20, 69};
   InetAddress thatsme = InetAddress.getByAddress(addressB);
   System.out.println(thatsme);
   
   InetAddress thatsmeWithname = InetAddress.getByAddress("thatsme.com", addressB);
   System.out.println(thatsmeWithname);
   
  } catch (UnknownHostException ex) {
   System.out.println("Error!");
  }
 }
}
www.georgelache.blogspot.com
www.georgelache.blogspot.com/172.217.19.97
www.google.com/216.58.209.196
robuc-glache-d/10.205.20.69
/10.205.20.69
thatsme.com/10.205.20.69

marți, 8 martie 2016

BPS 8.0: REST API C# Console Test Program


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace BPSConsoleTest
{
    public class RequestInfo 
    {   
        public string ApiToCall { get; set; }
        public string Method {get; set; }
        public string Body { get; set; }
        public CookieContainer CookieContainer { get; set; }
    }

    public class LoginResponse
    {
        public string apiKey { get; set; }
        public string sessionName { get; set; }
        public string sessionId { get; set; }
        public string userAccountUrl { get; set; }
    }

    public class Session
    {
        public string ServerAddress { get; set; }
        private LoginResponse loginInfo;
        private CookieContainer cookieContainer;

        public Session(String server = "10.215.118.38")
        {
            this.ServerAddress = server;
        }


        public void Login()
        {
            RequestInfo requestInfo = new RequestInfo
            {
                Method = "POST",
                ApiToCall = "v1/auth/session",
                Body = "{\"username\":\"admin\", \"password\":\"admin\"}"
            };

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate,
               X509Chain chain, SslPolicyErrors sslPolicyErrors)
            { return true; };

            Request requestLogin = new Request(requestInfo);
            string response = requestLogin.ExecuteRequest(ServerAddress);
            cookieContainer = requestInfo.CookieContainer;
            loginInfo = JsonConvert.DeserializeObject<LoginResponse>(response);
        }

        public string ExecuteApi(RequestInfo requestInfo) 
        {
            requestInfo.CookieContainer = this.cookieContainer;
            Request request = new Request(requestInfo);
            string response = request.ExecuteRequest(ServerAddress);
            return response;
        }

        public LoginResponse getLoginInfo()
        {
            return loginInfo;
        }
    }

    class Request 
    {
        RequestInfo requestInfo;
        
        internal Request(RequestInfo requestInfo)
        {
            this.requestInfo = requestInfo;
        }

         internal string ExecuteRequest(string serverAddress)
         {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("https://{0}/api/{1}", serverAddress, requestInfo.ApiToCall));
            request.UserAgent = ".NET Framework Example Client";
            request.ContentType = "application/json";
            request.Accept = "application/json;q=0.9";
            
            this.requestInfo.CookieContainer =  this.requestInfo.CookieContainer ?? new CookieContainer();
            request.CookieContainer = this.requestInfo.CookieContainer;

            request.Method = requestInfo.Method;
            
            byte[] originalStream = Encoding.UTF8.GetBytes(requestInfo.Body);
            request.ContentLength = originalStream.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(originalStream, 0, originalStream.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
                       
            
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            
            Console.WriteLine(responseFromServer);
            //Console.ReadLine();
            
            return responseFromServer;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Session newSession = new Session("10.215.118.38");
            newSession.Login();

            //reserve ports
            RequestInfo request = new RequestInfo
            {
                Method = "POST",
                ApiToCall = "v1/bps/ports/operations/reserve",
                Body = "{\"slot\":\"3\", \"portList\":[0,1], \"group\":\"1\", \"force\":\"true\"}"
            };
            newSession.ExecuteApi(request);

            //start a test
            request = new RequestInfo
            {
                Method = "POST",
                ApiToCall = "v1/bps/tests/operations/start",
                Body = "{\"modelname\":\"AppSim\", \"group\":\"1\", \"neighborhood\":\"BreakingPoint Routing\"}"
            };
            newSession.ExecuteApi(request);

            Console.WriteLine("Press ENTER to exit!");
            Console.ReadLine();
        }
    }
}

marți, 23 februarie 2016

Java: Hibernate: HelloWorld Sample Using Annotations and Programmatic Configuration

package helloworld;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Message {
 @Id
 @GeneratedValue
 private Long id;
 private String text;

 public String getText() {
  return text;
 }

 public void setText(String text) {
  this.text = text;
 }
}
package helloworld;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;

public class HelloWorldHibernate {
 @Test
 public void testHelloWorld() {
  
  /*
   * SessionFactory sessionFactory = new MetadataSources( new
   *   StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build())
   *   .buildMetadata().buildSessionFactory();
   */


  StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
  serviceRegistryBuilder
    //.applySetting("hibernate.connection.datasource", "books")
    .applySetting("hibernate.connection.url", "jdbc:mysql://localhost:3306/test")
    .applySetting("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
    .applySetting("hibernate.connection.user", "root")
    .applySetting("hibernate.connection.password", "****")
    .applySetting("hibernate.format_sql", "true")
    .applySetting("hibernate.use_sql_comments", "true")
    .applySetting("hibernate.hbm2ddl.auto", "create-drop");
  ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();

  // The MetadataSources API has many methods for adding mapping sources;
  MetadataSources metadataSources = new MetadataSources(serviceRegistry);
  
  metadataSources.addAnnotatedClass(helloworld.Message.class);
  MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
  Metadata metadata = metadataBuilder.build();

  assertEquals(metadata.getEntityBindings().size(), 1);

  SessionFactory sessionFactory = metadata.buildSessionFactory();

  // Whenever you call getCurrentSession() in the same thread, you get the
  // same org.hibernate.Session
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  Message message = new Message();
  message.setText("Hello World!");
  session.persist(message);
  session.getTransaction().commit();
  session.close();
  
  session = sessionFactory.openSession();
  session.beginTransaction();
  List<Message> messages = session.createCriteria(Message.class).list();
  // SELECT * from MESSAGE
  assertEquals(messages.size(), 1);
  assertEquals(messages.get(0).getText(), "Hello World!");
  session.getTransaction().commit();
  session.close();
 }
}

luni, 25 ianuarie 2016

Programming: Writing methods -- Best Practices

Writing methods -- best practices:

  • Use meaningful names for methods and their arguments
  • Try to keep the number of arguments as low as possible (to be less than 6)
  • Methods should be short (adhere to single responsibility principle)
  • Document public methods
  • Perform argument validation
  • Try to avoid returning null 
  • Use visibility and accessibility rules 
  • Java: Use annotation to mark "special" methods (@SafeVarargs or @Override)