Friday, September 9, 2016

How TO done Sample uploaded to lms



Question 3:Consider the following SQL snipped used to create three tables.


a.       Write an SQL query to list all the courses.

b.      Write select * from coursesan SQL query to list all the students who are registered for a course with CourseId 4.

My Answer:


1)SELECT * FROM courses;
2)SELECT s.StudentId,s.FirstName,s.LastName FROM courses c INNER JOIN coursemembership cm ON c.CourseId=cm.CourseId INNER JOIN students s ON cm.StudentId=s.StudentId WHERE c.CourseId=4;



Question 4: Write a program with the following aspects: [30 marks]
a. Implement the following logic:
If the lighting level is dark, and power is off, turn the emergency lamp on.

If the lighting level is bright, or the power is on, the emergency lamp off.


public class LigtingLevel {

   public static String ligtingLevel = "Dark";
   public static   String mypower = "Off";
    public static void main(String[] args) {
         if (("Dark".equals(ligtingLevel))&&("Off".equals(mypower))) {
             System.out.println("Power ON");
            
         } else if(("Bright".equals(ligtingLevel))||("On".equals(mypower))) {
             System.out.println("Power Off");
         }
       
    }
  
  

}


b. Implement the following formula:
Root finding formula


public class RootFinder {

    public static void main(String[] args) {
        double a = 10;
        double b = -4;
        double c = 4;
        double delta = b * b - 4 * a * c;

        if (delta >= 0) {
            double rootDelta = Math.sqrt(delta);
            double root1 = (-b + rootDelta) / (2 * a);
            double root2 = (-b - rootDelta) / (2 * a);
            System.out.println("Root 1:" + root1);
            System.out.println("Root 2:" + root2);

        } else {
            double absDelta = Math.abs(delta);
            double rootDelta = Math.sqrt(absDelta);
            System.out.println("Real1:" + (-b) / (2 * a) + " Imeginary1:" + rootDelta / (2 * a) + "i");
            System.out.println("Real2:" + (-b) / (2 * a) + " Imeginary2:" + rootDelta / (2 * a) + "i");
        }

    }

}

c. Sum of the integers in an array. Assume that the length of the array is available.


public class SumArray {
    public static void main(String[] args) {
        int arr[]={1,2,3,4,5,6};
        int sum=0;
        for (int i = 0; i < arr.length; i++) {
           
            sum=sum+arr[i];
            
        }
        System.out.println(sum);
    }
   
}

d. Find the largest element in an array. You may not use a system sort function.


public class LargestElement {

    static int arr[] = {2, 51, 1, 7, 13, 9};
    public static int num1;
    public static int num2;
    public static int lager = 2;

    public static void main(String[] args) {

        for (int i = 0; i < arr.length; i++) {

            if (lager < arr[i]) {
                lager = arr[i];
            }

        }
        System.out.println("larger :" + lager);
    }
}


d. Find the largest element in an array. You may not use a system sort function.

I used bubble sort to sort the integer array.


public class BubbleSort {

    public static void main(String[] args) {
        int arr[] = {6, 4, 3, 9, 7};
        int temp;
        for (int iteration = 0; iteration < arr.length - 1; iteration++) {
            for (int j = 0; j < arr.length - 1 - iteration; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }

        }
        for (int i : arr) {
            System.out.print(i + " ");
        }
        System.out.println("Largest:" + arr[arr.length - 1]);

    }

}

Question 5:
i. Create a class called Point with two doubles for the coordinate and
.
ii. Provide a constructor for this class.
iii. Add a method to print the point on console.
iv. Add a method to scale a point by a given factor.
v. Create a point in the main method and display.
vi. Create a class called ColoredPoint by inheriting from this. Add a constructor.
vii. “Print” the objects on console.


public class Point {
    double x;
    double y;

    public Point() {
        x = 2;
        y = 0;

    }
    public static void main(String[] args) {
        Point p = new Point();
        p.printPoint();
        p.scalePoint(5);

    }
    void printPoint() {
        System.out.println("X:" + x);
        System.out.println("Y:" + y);
    }

    void scalePoint(double scale) {
        System.out.println("X:" + x * scale);
        System.out.println("Y:" + y * scale);
    }

}

public class ColoredPoint extends Point {

    public ColoredPoint() {
    }
    public static void main(String[] args) {
        ColoredPoint c = new ColoredPoint();

        c.printPoint();
    }
}


spring-mvc-crud-demo-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />

<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>

    <!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false" />
        <property name="user" value="springstudent" />
        <property name="password" value="springstudent" /> 

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
</bean>  
    <!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
  <props>
     <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
     <prop key="hibernate.show_sql">true</prop>
  </props>
</property>
   </bean>  

    <!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />

</beans>




web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-mvc-crud-demo</display-name>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>



CustomerDAO
package com.luv2code.springdemo.dao;

import java.util.List;

import com.luv2code.springdemo.entity.Customer;

public interface CustomerDAO {

public List<Customer> getCustomers();
}

CustomerDAOImpl
package com.luv2code.springdemo.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.luv2code.springdemo.entity.Customer;

@Repository
public class CustomerDAOImpl implements CustomerDAO {

// need to inject the session factory
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public List<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Customer> theQuery = 
currentSession.createQuery("from Customer", Customer.class);
// execute query and get result list
List<Customer> customers = theQuery.getResultList();
// return the results
return customers;
}

}



Customer
package com.luv2code.springdemo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="customer")
public class Customer {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
public Customer() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}




CustomerController
package com.luv2code.springdemo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.luv2code.springdemo.dao.CustomerDAO;
import com.luv2code.springdemo.entity.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

// need to inject the customer dao
@Autowired
private CustomerDAO customerDAO;
@RequestMapping("/list")
public String listCustomers(Model theModel) {
// get customers from the dao
List<Customer> theCustomers = customerDAO.getCustomers();
// add the customers to the model
theModel.addAttribute("customers", theCustomers);
return "list-customers";
}
}


commons-logging-1.2
javax.servlet.jsp.jstl-1.2.1
javax.servlet.jsp.jstl-api-1.2.1
mysql-connector-java-5.1.39-bin

No comments:

Post a Comment