wtorek, 5 maja 2015

Codility solutions - lesson1, exercise: FrogJmp

Content of Codility excercise:


A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y.
The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

Write a function:

class Solution { public int solution(int X, int Y, int D); }

that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

  X = 10
  Y = 85
  D = 30
the function should return 3, because the frog will be positioned as follows:

after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:

X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
Complexity:

expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).

Solution:


    public int solution(int X, int Y, int D) {
        if ((Y-X)%D == 0){
            return (Y-X)/D;
        }else {
            return (Y-X)/D + 1;
        }
    }

poniedziałek, 13 kwietnia 2015

Remote debug Windows-based Tomcat service

To enable remote debugging in a Windows-based Tomcat service. Please follow the following steps to add debug settings to a Tomcat service.


  1. From the command line(run as administrator) call the following command

    %TOMCAT_HOME%/bin/tomcat6w.exe //ES//<ServiceName>

    where <ServiceName> is actual windows service name
    *A properties dialog box pops out.
  2. Navigate to the Java tab and add the following entries in the Java Options section

    -Xdebug
    -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=n

After restarting the service you'll be able to run remote debug on port 5005.



czwartek, 13 czerwca 2013

Hibernate relation: many to many (unidirectional)

1. Database schema

...

2. Entity class:

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "Country")
public class Country {

   @Id
   @GeneratedValue
   private Long id;

   @Column
   private String name;

   @Column
   private String code;

   @ManyToMany(cascade = {CascadeType.ALL})
   @JoinTable(name = "Jt_Country_Currency",
           joinColumns = {@JoinColumn(name = "CountryId")},
           inverseJoinColumns = {@JoinColumn(name = "CurrencyId")})
   private Set<Currency> currencies;


   public Country(){
   }
    //getters and setters

}

import javax.persistence.*;

@Entity
@Table(name = "Currency")
public class Currency {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    @Column
    private String code;

    @Column
    private String symbol;

    public Currency() {
    }
//getters and setters

}

3. Hibernate configuration file

Put annotated classes User.java and UserAdditionalInfo.java in to hibernate configuration file and mysql connection details:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.Country"/>
        <mapping class="net.hibernateApp.packt.maven.domain.Currency>"/>

    </session-factory>
</hibernate-configuration>

4. Run

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.domain.Product;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public class Main {

    public static void main(String[] args) {

        Country country1 = new Country();
        country1.setName("Poland");
        country1.setCode("22");

        Currency currency1 = new Currency();
        currency1.setName("EURO");
        currency1.setSymbol("E");

        Currency currency2 = new Currency();
        currency2.setName("Zloty");
        currency2.setSymbol("PLN");

        Set<Currency> currencySet = new HashSet<Currency>();
        currencySet.add(currency1);
        currencySet.add(currency2);

        country1.setCurrencies(currencySet);

        saveCounty(country1);
    }

    private static void saveCounty(Country country){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(country);
        session.getTransaction().commit();
        session.close();
    }

}

Output: 1

Class net.hibernateApp.packt.maven.hibernate.HibernateUtils is described here:
 Using Hibernate persistence with Maven

Hibernate relation: many to many (bidirectional)

1. Database schema

...

2. Entity class:

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "Country")
public class Country {

   @Id
   @GeneratedValue
   private Long id;

   @Column
   private String name;

   @Column
   private String code;

   @ManyToMany(cascade = {CascadeType.ALL})
   @JoinTable(name = "Jt_Country_Currency",
           joinColumns = {@JoinColumn(name = "CountryId")},
           inverseJoinColumns = {@JoinColumn(name = "CurrencyId")})
   private Set<Currency> currencies;


   public Country(){
   } 
    //getters and setters

}

import javax.persistence.*;
import java.util.Collection;

@Entity
@Table(name = "Currency")
public class Currency {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    @Column
    private String code;

    @Column
    private String symbol;

    @ManyToMany(mappedBy = "currencies")
    private Collection<Country> countries;


    public Currency() {
    }
//getters and setters

}

3. Hibernate configuration file

Put annotated classes User.java and UserAdditionalInfo.java in to hibernate configuration file and mysql connection details:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.Country"/>
        <mapping class="net.hibernateApp.packt.maven.domain.Currency>"/>

    </session-factory>
</hibernate-configuration>

4. Run

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.domain.Product;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public class Main {

    public static void main(String[] args) {

        Country country1 = new Country();
        country1.setName("Poland");
        country1.setCode("22");

        Currency currency1 = new Currency();
        currency1.setName("EURO");
        currency1.setSymbol("E");

        Currency currency2 = new Currency();
        currency2.setName("Zloty");
        currency2.setSymbol("PLN");

        Set<Currency> currencySet = new HashSet<Currency>();
        currencySet.add(currency1);
        currencySet.add(currency2);

        country1.setCurrencies(currencySet);

        saveCounty(country1);
    }

    private static void saveCounty(Country country){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(country);
        session.getTransaction().commit();
        session.close();
    }

}

Output: 1

Class net.hibernateApp.packt.maven.hibernate.HibernateUtils is described here:
 Using Hibernate persistence with Maven

Hibernate relation: one to many (bidirectional)

1. Database schema

...

2. Entity class:

@Entity
@Table(name = "Shop")
public class Shop {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String name;

    @Column
    private  String urlAddress;

    @OneToMany(mappedBy = "shop", cascade = {CascadeType.ALL})
    private Collection<Provider> providers;

    public Shop() {
    }//getters and setters

}

import javax.persistence.*;

@Entity
@Table(name = "Provider")
public class Provider {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String name;

    @ManyToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "shopId")
    private Shop shop;
 

    public Provider() {
    }


//getters and setters

}

3. Hibernate configuration file

Put annotated classes User.java and UserAdditionalInfo.java in to hibernate configuration file and mysql connection details:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.Shop"/>
        <mapping class="net.hibernateApp.packt.maven.domain.Provider>"/>

    </session-factory>
</hibernate-configuration>

4. Run

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.domain.Product;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public class Main {

    public static void main(String[] args) {

        Shop shop = new Shop();
        shop.setName("Free Market");
        shop.setUrlAddress("http://...");

        Provider provider1 = new Provider();
        provider1.setName("google");
        provider1.setShop(shop);

        Provider provider2 = new Provider();
        provider2.setName("samsung");
        provider2.setShop(shop);

        List<Provider> providers = new ArrayList<Provider>();
        providers.add(provider1);
        providers.add(provider2);

        shop.setProviders(providers);
        saveShop(shop);

//        OR
//        saveProvider(provider1);
//        saveProvider(provider2);

    }
  
    private static void saveShop(Shop shop){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(shop);
        session.getTransaction().commit();
        session.close();
    }
 
    private static void saveProvider(Provider provider){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(provider);
        session.getTransaction().commit();
        session.close();
    }

}

Output: 1

Class net.hibernateApp.packt.maven.hibernate.HibernateUtils is described here:
 Using Hibernate persistence with Maven

Hibernate ralation: many to one(unidirectional)

1. Database schema

...

2. Entity class:

@Entity
@Table(name = "Shop")
public class Shop {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String name;

    @Column
    private  String urlAddress;

    public Shop() {
    }


//getters and setters

}

import javax.persistence.*;

@Entity
@Table(name = "Provider")
public class Provider {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String name;

    @ManyToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "shopId")
    private Shop shop;

    public Provider() {
    }


//getters and setters

}

3. Hibernate configuration file

Put annotated classes User.java and UserAdditionalInfo.java in to hibernate configuration file and mysql connection details:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.Shop"/>
        <mapping class="net.hibernateApp.packt.maven.domain.Provider>"/>

    </session-factory>
</hibernate-configuration>

4. Run

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.domain.Product;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public class Main {

    public static void main(String[] args) {

        Shop shop = new Shop();
        shop.setName("Free Market");
        shop.setUrlAddress("http://...");

        Provider provider1 = new Provider();
        provider1.setName("google");
        provider1.setShop(shop);

        Provider provider2 = new Provider();
        provider2.setName("samsung");
        provider2.setShop(shop);

        saveProvider(provider1);
        saveProvider(provider2);

        List<Shop> shops = list("Shop");
        System.out.println(shops.size());
    }

 private static List list(String sourceTable) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        List objects = session.createQuery("from "+sourceTable).list();
        session.close();
        return objects;
    }

    private static void saveProvider(Provider provider){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(provider);
        session.getTransaction().commit();
        session.close();
    }

}

Output: 1

Class net.hibernateApp.packt.maven.hibernate.HibernateUtils is described here:
 Using Hibernate persistence with Maven

środa, 12 czerwca 2013

Hibernate ralation: one to many (unidirectional)

1. Database schema

...

2. Entity class:

import javax.persistence.*;
import java.sql.Date;

@Entity
@Table(name = "User")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "firstName")
    private  String firstName;

    @Column(name = "surName")
    private  String surName;

    @Column(name = "birthDate")
    private Date birthDate;

    @Column (name = "address")
    private  String emailAddress;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "userId")
    private Collection<Product> products;

    public User() {
    }

//getters and setters

}

import javax.persistence.*;

@Entity
@Table(name = "Product")
public class Product {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String name;

    @Column
    private String type;

    @Column
    private double price;

    public Product() {
    }
//getters and setters

}

3. Hibernate configuration file

Put annotated classes User.java and UserAdditionalInfo.java in to hibernate configuration file and mysql connection details:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.User"/>
        <mapping class="net.hibernateApp.packt.maven.domain.Product>"/>

    </session-factory>
</hibernate-configuration>

4. Run

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.domain.Product;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public class Main {

    public static void main(String[] args) {

        User user = new User();
        user.setFirstName("Christopher");
        user.setSurName("Stepniak");
        List<Product> products = new ArrayList<Product>();
        products.add(new Product("axe", "weapon", 0.99));
        products.add(new Product("sword", "weapon", 1.99));
        products.add(new Product("apple", "food", 0.49));
        user.setProducts(products);
        user = saveUser(user);


        List<Product> products1 = listProduct(user.getId());
        System.out.println(products1.size());
    }

 private static User saveUser(User user){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        Long id = (Long) session.save(user);
        user.setId(id);
        session.getTransaction().commit();
        session.close();
        return user;
    }

    private static List listProduct(Long userId) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();
        List objects = session.createQuery("from Product where userId= "+ userId).list();
        session.close();
        return objects;
    }

}

Output: 3

Class net.hibernateApp.packt.maven.hibernate.HibernateUtils is described here:
 Using Hibernate persistence with Maven