text:
<repo_name>dharmendra-mali/ScrumBoard<file_sep>/scrum_board/models/Task.java
package com.tavant.scrum_board.models;

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

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@JsonIgnoreProperties({ "hibernateLazyIntitializer", "handler" })
public class Task {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int taskid;

	private String notes;

	private String taskStatus;

	public Task() {

	}

	public String getNotes() {
		return notes;
	}

	public int getTaskid() {
		return taskid;
	}

	public void setTaskid(int taskid) {
		this.taskid = taskid;
	}

	public void setNotes(String notes) {
		this.notes = notes;
	}

	public String getTaskStatus() {
		return taskStatus;
	}

	public void setTaskStatus(String taskStatus) {
		this.taskStatus = taskStatus;
	}

}
<file_sep>/app/models/team.model.ts
import { User } from './user.model';

export class Team{

    constructor(public teamName : string,
                public teamUsers : User []) {}
}<file_sep>/app/admin/teams/team/team.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { UserService } from 'src/app/users/user.service';
import { User } from 'src/app/models/user.model';
import { TeamService } from '../team.service';
import { TeamRepository } from 'src/app/repository/teamRepository';
import { Team } from 'src/app/models/team.model';
import { Logs } from 'selenium-webdriver';

@Component({
  selector: 'app-team',
  templateUrl: './team.component.html',
  styleUrls: ['./team.component.css']
})
export class TeamComponent implements OnInit {

  users : User [];
  selectedUsers : User[]=[];
  teamName : string;
  constructor(private route: ActivatedRoute,
              private userServie: UserService,
              private teamService : TeamService,
              private router : Router,
              private teamRepository : TeamRepository) { }

  ngOnInit() {
    this.users = this.userServie.users;
    this.route.params.subscribe(
      (params : Params) => { this.teamName = params['teamName']}
      );
      this.selectedUsers = [];
  }

  addToTeam(user: User){
    user.userTeamName = this.teamName;

    for(let team of this.teamService.teams){
      if(team.teamName === this.teamName){
        team.teamUsers.push(user);
      }
    }
    this.teamRepository.addTeamUser(new Team(this.teamName , [user]));
  }

  reamovFromTeam(user: User){
    user.userTeamName = 'NONE'

    for(let team of this.teamService.teams){
      if(team.teamName === this.teamName){
        for(let i=0; i< team.teamUsers.length ; i++){
          if(user.userId === team.teamUsers[i].userId){
            team.teamUsers.splice(i,1);
          }
        }
      }
    }
    this.teamRepository.delete_user(new Team(this.teamName , [user]));
  }
}
<file_sep>/app/users/user.service.ts
import { User } from '../models/user.model';
import { OnInit, Injectable } from '@angular/core';
import { UserRepository } from '../repository/user.repository';

@Injectable()
export class UserService implements OnInit{

    duplicateIdStatus : boolean = false;
    duplicateEmailStatus : boolean = false;

    constructor(private userRepository : UserRepository){}
    // users : User[] = [ new User("PT0848","VIKRAM", "KUMAR", "VIKRAM.KUMAR","PROJECT TRAINEE", "NONE"),
    // new User("PT084","VIKRAM", "KUMAR", "VIKRAM.KUMAR","PROJECT TRAINEE", "NONE"),
    // new User("PT088","VIKRAM", "KUMAR", "VIKRAM.KUMAR","PROJECT TRAINEE", "NONE"),
    // new User("PT048","VIKRAM", "KUMAR", "VIKRAMng s.KUMAR","PROJECT TRAINEE", "NONE")];
    users: User[] =[];

    ngOnInit(){
    }

    initializeData() {

        console.log("getting all data")
        return this.userRepository.getAllUser()
    }

    addUser(user : User) : void{
        this.users.push(user);
    }

    removeUser(id : string) : void {
        for(var i = 0; i < this.users.length; i++){
            if(this.users[i].userId === id){
                this.users[i].userTeamName = 'NONE'
                console.log(this.users[i]);
                this.users.splice(i, 1);
                break;
            }
        }
    }

    checkDuplicateUser(userId : string) : boolean {
        for(let i=0; i< this.users.length; i++){
            if(this.users[i].userId === userId){
                this.duplicateIdStatus = true;
                break;
            }
        }
        return this.duplicateIdStatus;
    }

    checkDuplicateEmail(userEmail : string){
        for(let i=0; i< this.users.length; i++){
            if(this.users[i].userEmail === userEmail){
                this.duplicateEmailStatus = true;
                break;
            }
        }
        return this.duplicateEmailStatus;
    }

}<file_sep>/app/admin/add-user/add-user.component.ts
import { Component, OnInit, ViewChild, OnChanges } from '@angular/core';
import { User } from 'src/app/models/user.model';
import { UserService } from 'src/app/users/user.service';
import { NgForm } from '@angular/forms';
import { TeamService } from '../teams/team.service';
import { Team } from 'src/app/models/team.model';
import { UserRepository } from 'src/app/repository/user.repository';
import { ToDoRepository } from 'src/app/repository/toDoRepository';
import { ToDo } from 'src/app/models/toDo.model';

@Component({
  selector: 'app-add-user',
  templateUrl: './add-user.component.html',
  styleUrls: ['./add-user.component.css']
})
export class AddUserComponent implements OnInit {

  @ViewChild('userForm') enteredUserData : NgForm;
  users : User[];
  newUser : User;
  teams : Team[];
  defaultDesignation = "SOFTWARE ENGINNER";
  defaultTeam ="NONE"
  showStatus : string = '';
  constructor(private userService : UserService,
              private teamService : TeamService,
              private userRepository : UserRepository,
              private toDoRepository : ToDoRepository) { }

  ngOnInit(){
    this.users = this.userService.users;
      this.teams = this.teamService.teams;

  }

  submitForm(){

    this.newUser = this.enteredUserData.value;
    this.newUser.password = "123";
    if(this.userService.checkDuplicateUser(this.newUser.userId)){

      this.showStatus = "PLEASE CHOOSE ANOTHER USER ID";
      this.userService.duplicateIdStatus = false;
    }else if(this.userService.checkDuplicateEmail(this.newUser.userEmail)){

      this.showStatus = "PLEASE CHOOSE ANOTHER EMAIL";
      this.userService.duplicateEmailStatus = false;
    } else {

      this.userService.addUser(this.newUser);
      for(let i=0;i<this.teams.length; i++){
        if(this.teams[i].teamName === this.newUser.userTeamName){
          this.teams[i].teamUsers.push(this.newUser);
        }
      }
      // this.teams.push(new Team(this.newUser.userTeamName , [this.newUser]))
      this.showStatus = 'USER CREATED';
      //submitting the form to database
      this.userRepository.createUser(this.newUser);
    }
    this.toDoRepository.createToDo(new ToDo(this.newUser.userId,[]));
    this.enteredUserData.reset();
  }

  deleteCurrentUser(user : User) : void{
    this.userService.removeUser(user.userId);
     this.userRepository.deleteUser(user.userId);

  }
}
<file_sep>/app/users/user/user.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/models/user.model';
import { UserService } from '../user.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ScrumService } from 'src/app/admin/scrums/scrum.service';
import { Scrum } from 'src/app/models/scrum.model';
import { ToDo } from 'src/app/models/toDo.model';
import { ToDoService } from '../toDo.service';
import { Tasks } from 'src/app/models/tasks.model';
import { ToDoRepository } from 'src/app/repository/toDoRepository';
import { TaskRepository } from 'src/app/repository/task.repository';
import { ToDoHelper } from 'src/app/models/toDoHelper.model';
import { ScrumRepository } from 'src/app/repository/scrum.repository';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  users : User[];
  userId : string;
  currentUser : User;
  currentTeam : string;
  scrums : Scrum[]
  userStoryFromScrum : Tasks[];
  toDoList : ToDo [];
  toDo : ToDo;
  userTeamScrum : Scrum;
  iterableToDo : ToDo;
  // story : string[];
  constructor(private userService : UserService,
              private router: Router,
              private route : ActivatedRoute,
              private scrumService : ScrumService,
              private toDoService : ToDoService,
              private toDoRepository : ToDoRepository,
              private taskRepository : TaskRepository,
              private scrumRepository : ScrumRepository) { }

  ngOnInit() {

    this.scrums = this.scrumService.scrum;
    this.users = this.userService.users;
    this.toDoList = this.toDoService.toDo;

    this.route.params.subscribe((params : Params) => {this.userId = params['id']});
    for(let i=0; i<this.users.length; i++){
        if(this.users[i].userId===this.userId){
          this.currentUser = this.users[i];
          break;
        }
    }
    this.currentTeam = this.currentUser.userTeamName;
    for(let i=0; i<this.scrums.length; i++){
      if(this.scrums[i].team.teamName === this.currentTeam){
        this.userStoryFromScrum = this.scrums[i].tasks;
        this.userTeamScrum = this.scrums[i];
      }
    }
  }

  addToUser(story : string){

    console.log(story);

      for(let list of this.toDoList){

        if(list.userId === this.currentUser.userId){
          list.toDoHelper.push(new ToDoHelper(story,'TO DO'));
          console.log(story);

          this.toDoRepository.updateToDo(list);
           this.taskRepository.updateStatus(story, this.userTeamScrum.scrumName , list.userId);
        }
      }

      for(let toDo of this.userStoryFromScrum){
        if(toDo.notes === story){
          toDo.taskStatus = this.currentUser.userId;
        }
      }
  }

  addToProgress(str : string, story :string){
    if(str==='remove'){

      for(let toDo of this.userStoryFromScrum){
        if(toDo.notes === story){
          toDo.taskStatus = 'NONE';
          this.taskRepository.removeStatus(story, this.userTeamScrum.scrumName);
          this.toDoRepository.updateToDoTask(story, this.currentUser.userId);
          }
        }
        for(let j=0; j<this.toDoList.length; j++){
          for( let i=0 ; i<this.toDoList[j].toDoHelper.length; i++){
            if(this.toDoList[j].toDoHelper[i].story === story){
            this.toDoList[j].toDoHelper.splice(i , 1);
          }
          }
      }
    } else {
          for(let j=0; j<this.toDoList.length; j++){
            for( let i=0 ; i<this.toDoList[j].toDoHelper.length; i++){
                if(this.toDoList[j].toDoHelper[i].story === story){
                  this.toDoList[j].toDoHelper[i].status = 'PROGRESS';
                  this.toDoRepository.updateToDo(this.toDoList[j]);
                 }
            }
          }
      }
  }

  addToDone(str : string, story :string){
          for(let j=0; j<this.toDoList.length; j++){
            for( let i=0 ; i<this.toDoList[j].toDoHelper.length; i++){
                if(this.toDoList[j].toDoHelper[i].story === story){
                  this.toDoList[j].toDoHelper[i].status = 'DONE';
                  this.toDoRepository.updateToDo(this.toDoList[j]);
                 }
            }
          }

  }

}
<file_sep>/app/header/header.component.ts
import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login/login.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  dispalayLogout = false;
  constructor(private loginService : LoginService,
              private router : Router) { }

  ngOnInit() {
   this.loginService.logOut$.subscribe(dispalayLogout => this.dispalayLogout =dispalayLogout)
  //  this.loginService.adddispalayLogout(true);
    //this.dispalayLogout = true;
    console.log(this.dispalayLogout);
  }

  logout(){
    this.loginService.adddispalayLogout(false);
    // this.loginService.dispalayLogout = false;
    this.router.navigate(['/login']);
  }
}
<file_sep>/app/models/toDoHelper.model.ts
export class ToDoHelper{

    constructor( public story : string,
        public status : string) {}
}<file_sep>/app/models/toDo.model.ts
import { ToDoHelper } from './toDoHelper.model';

export class ToDo {

    constructor(public userId : string,
                public toDoHelper : ToDoHelper[]) {}
}<file_sep>/app/admin/teams/team.service.ts
import { User } from 'src/app/models/user.model';
import { Team } from 'src/app/models/team.model';

export class TeamService{

    sendDuplicateTeamsStatus : boolean = false;
    //users : User[] = [];
    // [ new User("PT848","VIKRAM",'KUMAR','VIKRAM.KUMAR','SOFTWARE ENGINNER','TEAM-I'),
    //                   new User("PT748","VIKRAM",'KUMAR','VIKRAM.KUMAR','SOFTWARE ENGINNER','TEAM-I'),
    //                   new User("PT048","VIKRAM",'KUMAR','VIKRAM.KUMAR','SOFTWARE ENGINNER','TEAM-I')];

    teams : Team[] = [];
    // [new Team("team1", this.users),
    //                   new Team("team2", this.users) ];

    createTeam(team : Team){
        this.teams.push(team);
    }

    checkDuplicateTeam(teamName : string) : boolean{
        for(let i = 0; i< this.teams.length ; i++){
            if(this.teams[i].teamName === teamName){
                this.sendDuplicateTeamsStatus = true;
            }
        }
        return this.sendDuplicateTeamsStatus;
    }

    removeTeam(teamName : string){
        for( let i=0; i<this.teams.length; i++){
            if(this.teams[i].teamName == teamName){
                for(let j=0; j<this.teams[i].teamUsers.length ; j++){
                    this.teams[i].teamUsers[j].userTeamName='NONE';
                }
                this.teams.splice(i, 1);
                break;
            }
        }
    }
}<file_sep>/app/admin/teams/teams.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Team } from 'src/app/models/team.model';
import { TeamService } from './team.service';
import { NgForm } from '@angular/forms';
import { User } from 'src/app/models/user.model';
import { TeamRepository } from 'src/app/repository/teamRepository';

@Component({
  selector: 'app-teams',
  templateUrl: './teams.component.html',
  styleUrls: ['./teams.component.css']
})
export class TeamsComponent implements OnInit {

  @ViewChild('teamName') teamName : NgForm;
  teams : Team[];
  nullUser : User=new User("","","","","","NONE","");
  duplicateTeam =''
  constructor(private teamService : TeamService,
              private teamRepository : TeamRepository) { }

  ngOnInit() {
    this.teams = this.teamService.teams;
  }

  submitTeamName(){
    if(this.teamService.checkDuplicateTeam(this.teamName.value.teamName)){

      this.teamService.sendDuplicateTeamsStatus = false;
      this.duplicateTeam = "Team Already Exists";
    } else {
      let team = new Team(this.teamName.value.teamName,[this.nullUser]);
      team.teamUsers.pop()
      this.teamService.createTeam(team);

      this.teamRepository.createTeam(team);
      this.duplicateTeam = "Team Created";
    }
  }

  deleteTeam(teamName : string){
    this.teamService.removeTeam(teamName);
    //call services teamName
    this.teamRepository.deleteTeam(teamName);
  }

}
<file_sep>/scrum_board/controller/ScrumRestController.java
package com.tavant.scrum_board.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.tavant.scrum_board.models.Scrum;
import com.tavant.scrum_board.service.ScrumService;

@RestController
@RequestMapping("/scrum_api")
@CrossOrigin
public class ScrumRestController {

	@Autowired
	private ScrumService scrumService;

	@GetMapping("/scrum")
	private List<Scrum> getScrum() {
		List<Scrum> list=null;
		try {
		list = scrumService.scrumList();
		}catch(Exception e) {
			System.err.println("getting exception while retriving data");
		}
		return list;
	}

	@PostMapping("/save")
	@ResponseStatus(HttpStatus.OK)
	public void createtScrum(@RequestBody Scrum scrum) {

		scrumService.createtScrum(scrum);
	}

	@GetMapping("/scrum/{scrumname}")
	public Scrum getTeam(@PathVariable("scrumname") String scrumName) {

		return scrumService.getTeam(scrumName);

	}

	@DeleteMapping("/delete/{scrumname}")
    public void deleteTeam(@PathVariable("scrumname") String scrumName) {
        scrumService.deleteTeam(scrumName);
    }

	@PutMapping("update_scrum")
	public void updateScrum(@RequestBody Scrum tempScrum) {

		scrumService.updateScrum(tempScrum);
	}

	@PutMapping("/release/{story}/{scrumName}")
	public void deAssignTask(@PathVariable String story, @PathVariable String scrumName) {

		scrumService.deAssignTask(story, scrumName);
	}

}
<file_sep>/app/users/users.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from '../models/user.model';
import { UserService } from './user.service';
import { UserRepository } from '../repository/user.repository';
import { ToDoRepository } from '../repository/toDoRepository';
import { ToDoService } from './toDo.service';
import { ScrumRepository } from '../repository/scrum.repository';
import { ScrumService } from '../admin/scrums/scrum.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  users : User[];
  constructor(private userService : UserService,
              private toDoRepository : ToDoRepository,
              private toDoService : ToDoService,
              private scrumRepository : ScrumRepository,
              private scrumService : ScrumService ) { }

  ngOnInit() {
    this.userService.initializeData();
    this.toDoRepository.initialize().subscribe(
      toDo => {this.toDoService.toDo = toDo;}
    );
    this.users = this.userService.users
    this.scrumRepository.getAllScrum().subscribe(
      scrum => this.scrumService.scrum = scrum
    )
  }
}
<file_sep>/scrum_board/repositories/UserRepositories.java
package com.tavant.scrum_board.repositories;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.tavant.scrum_board.models.User;

@Repository
public interface UserRepositories extends JpaRepository<User, String> {

	public User findByUserId(String userId);

	@Modifying(clearAutomatically = true)
	@Query(value = "UPDATE user u SET u.user_team_name='NONE' WHERE u.user_id=:id", nativeQuery = true)
	@Transactional
	public void deleteAssignUserId(@Param("id") String userId);

	@Modifying(clearAutomatically = true)
	@Query(value = "UPDATE task t SET t.user_id=0 WHERE t.task_id=:id", nativeQuery = true)
	@Transactional
	public void deleteAssignTaskId(@Param("id") int userId);

//	@Modifying(clearAutomatically = true)
//	@Query(value = "select * from user where user.user_email=:id", nativeQuery = true)
//	@Transactional
//	public User findByEmailId(@Param("id") String email);

	public User findByUserEmail(String email);
}
<file_sep>/app/repository/scrum.repository.ts
import { Injectable } from '@angular/core';
import { Scrum } from '../models/scrum.model';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class ScrumRepository {

    private url = "http://10.130.153.138:8000/scrum_api/";
    private httpHeader = new HttpHeaders({'Content-Type': 'application/json'});
    constructor(private http : HttpClient){}

    crateScrum(scrum : Scrum){
        this.http.post(this.url + "save",scrum, {headers : this.httpHeader}).subscribe();
    }

    getAllScrum() : Observable<Scrum[]> {
        return this.http.get<Scrum[]>(this.url+"scrum",{headers: this.httpHeader})
    }

    deleteScrum(scrumName : string) {
        this.http.delete(this.url + "delete/"+scrumName).subscribe();
    }

    updateScrum(scrum : Scrum){
        this.http.put(this.url+"update_scrum", JSON.stringify(scrum) ,{headers : this.httpHeader}).subscribe();
    }

    removeTask(story : string, scrumName : string){
        this.http.put(this.url+"release/"+story+"/"+scrumName,{headers: this.httpHeader}).subscribe();
    }
}<file_sep>/app/login/login.service.ts
import { BehaviorSubject, Subject } from 'rxjs';

export class LoginService{
    dispalayLogout:Subject<boolean> = new BehaviorSubject<boolean>(false);
   get logOut$(){
        return this.dispalayLogout.asObservable();
    }

    adddispalayLogout( dispalayLogout:boolean){
        this.dispalayLogout.next(dispalayLogout);
    }
}<file_sep>/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from './users/user.service';
import { TeamService } from './admin/teams/team.service';
import { TeamRepository } from './repository/teamRepository';
import { ScrumRepository } from './repository/scrum.repository';
import { ScrumService } from './admin/scrums/scrum.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'newProject1';
  constructor(){ }
  ngOnInit(){

  }
}
<file_sep>/app/repository/teamRepository.ts
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Team } from '../models/team.model';
import { Injectable } from '@angular/core';

@Injectable()
export class TeamRepository{

    private url = "http://10.130.153.138:8000/team_api/"
    private httpHeader = new HttpHeaders({'Content-Type':'application/json'})

    constructor(private http : HttpClient) {}

    getAllTeams() : Observable<Team[]> {
        return this.http.get<Team[]>(this.url+"team")
    }

    createTeam(team : Team){
        this.http.post(this.url+"save",JSON.stringify(team), {headers : this.httpHeader}).subscribe();
    }

    deleteTeam(teamName : string) {
        this.http.delete(this.url+"delete/"+teamName).subscribe();
    }

    addTeamUser(team : Team){
        this.http.put(this.url+"addUserToTeam",team, {headers : this.httpHeader}).subscribe();
    }

    delete_user(team : Team){
        this.http.put(this.url+"delete_user",team, {headers : this.httpHeader}).subscribe();
    }
}<file_sep>/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { UsersComponent } from './users/users.component';
import { UserComponent } from './users/user/user.component';
import { HomeComponent } from './home/home.component';
import { AdminComponent } from './admin/admin.component';
import { TeamsComponent } from './admin/teams/teams.component';
import { TeamComponent } from './admin/teams/team/team.component';
import { UserService } from './users/user.service';
import { TeamService } from './admin/teams/team.service';
import { AddUserComponent } from './admin/add-user/add-user.component';
import { ScrumComponent } from './admin/scrums/scrum/scrum.component';
import { ScrumsComponent } from './admin/scrums/scrums.component';
import { ScrumService } from './admin/scrums/scrum.service';
import { ViewScrumsComponent } from './admin/view-scrums/view-scrums.component';
import { ShowMenuDirective } from './directives/show-menu.directive';
import { ViewScrumComponent } from './admin/view-scrums/view-scrum/view-scrum.component';
import { ToDoService } from './users/toDo.service';
import { HttpClientModule } from '@angular/common/http';
import { UserRepository } from './repository/user.repository';
import { TeamRepository } from './repository/teamRepository';
import { ScrumRepository } from './repository/scrum.repository';
import { ToDoRepository } from './repository/toDoRepository';
import { TaskRepository } from './repository/task.repository';
import { LoginComponent } from './login/login.component';
import { LoginService } from './login/login.service';

const appPath = [
  { path : '', component: LoginComponent},
  { path : 'admin', component : AdminComponent },
  { path : 'users', component : UsersComponent },
  { path : 'users/:id', component : UserComponent },
  { path : 'teams', component : TeamsComponent },
  { path : 'teams/:teamName', component : TeamComponent },
  { path : 'createUser', component : AddUserComponent },
  { path : 'scrums/:scrumName', component : ScrumComponent },
  { path : 'scrums', component : ScrumsComponent },
  { path : 'viewScrums', component : ViewScrumsComponent },
  { path : 'viewScrums/:scrumName', component : ViewScrumComponent },
  { path : 'login', component : LoginComponent},
  { path : '**', redirectTo : ''}
]
@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    UsersComponent,
    UserComponent,
    HomeComponent,
    AdminComponent,
    TeamsComponent,
    TeamComponent,
    AddUserComponent,
    ScrumComponent,
    ScrumsComponent,
    ViewScrumsComponent,
    ShowMenuDirective,
    ViewScrumComponent,
    LoginComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appPath),
    HttpClientModule
  ],
  providers: [UserService,
              TeamService,
              ScrumService,
              ToDoService,
              UserRepository,
              TeamRepository,
              ScrumRepository,
              ToDoRepository,
              TaskRepository,
              ToDoService,
              LoginService],
  bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/scrum_board/controller/ToDoRestController.java
package com.tavant.scrum_board.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.tavant.scrum_board.models.ToDo;
import com.tavant.scrum_board.service.ToDoService;

@RestController
@RequestMapping("/todo_api")
@CrossOrigin
public class ToDoRestController {

	@Autowired
	private ToDoService toDoService;

	@GetMapping("/todo")
	public List<ToDo> taskList() {
		return toDoService.taskList();
	}

	@PostMapping("/save")
	@ResponseStatus(HttpStatus.OK)
	public void createTask(@RequestBody ToDo todo) {
		toDoService.createTask(todo);
	}

	@DeleteMapping("/delete/{userid}")
	public void deleteTask(@PathVariable("userid") String userid) {

		toDoService.deleteTask(userid);
	}

	@PutMapping("/update_todo")
	public void updateToDo(@RequestBody ToDo tempToDo) {

		toDoService.updateToDo(tempToDo);
	}

	@PutMapping("/updat_todo/{story}/{userId}")
	public void removeStory(@PathVariable String story, @PathVariable String userId) {

		toDoService.removeStory(story, userId);
	}
	@GetMapping("/todo/{userId}")
	public ToDo getOnToDo(@PathVariable String userId) {

		return toDoService.getOnToDo(userId);
	}

}
<file_sep>/app/admin/scrums/scrum.service.ts
import { Scrum } from 'src/app/models/scrum.model';
import { Tasks } from 'src/app/models/tasks.model';
import { User } from 'src/app/models/user.model';
import { Team } from 'src/app/models/team.model';

export class ScrumService{

    user = new User("NONE","NONE","","","","","");
    team = new Team("NONE",[this.user]);
    tasks : Tasks []   = [new Tasks('NONE','NONE'),
                          new Tasks('NONE','GOT',)];
    scrum : Scrum[] = [ new Scrum("TEST",this.tasks,this.team),
                        new Scrum("TEST2",this.tasks, this.team)];;
    duplicate = false;

    pushToScrum(scrum : Scrum) : void {
        this.scrum.push(scrum);
    }

    reamoveScrum(scrumName : string){
        for(let i=0; i<this.scrum.length; i++){
            if(this.scrum[i].scrumName === scrumName){
              this.scrum.splice(i , 1);
              break;
            }
          }
    }

    validateDuplicate(scrumName : string) : boolean{
        this.scrum.forEach((scrum : Scrum) => {
             if( scrum.scrumName === scrumName ){
                 this.duplicate = true;
             }
            })
        return this.duplicate;
    }

    removeScrumStory(story : string, scrumName : string){

        for(let i=0; i< this.scrum.length ; i++){
            if(this.scrum[i].scrumName === scrumName){
                for(let j=0; j<this.scrum[i].tasks.length; j++){
                    if(this.scrum[i].tasks[j].notes === story){
                        this.scrum[i].tasks.splice(j , 1);
                    }
                }
            }
        }

    }
}<file_sep>/app/models/tasks.model.ts
import { User } from './user.model';

export class Tasks{

    // constructor(public userId: string,
    //             public notes: string,
    //             public userName: string){}

    constructor(public taskStatus:string,
                public notes: string
                                    ){}
}<file_sep>/app/login/login.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { User } from '../models/user.model';
import { templateSourceUrl } from '@angular/compiler';
import { Router } from '@angular/router';
import { UserRepository } from '../repository/user.repository';
import { UserService } from '../users/user.service';
import { TeamRepository } from '../repository/teamRepository';
import { TeamService } from '../admin/teams/team.service';
import { ScrumRepository } from '../repository/scrum.repository';
import { ScrumService } from '../admin/scrums/scrum.service';
import { LoginService } from './login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  @ViewChild('loginData') loginData: NgForm;
  showMessage = '';
  dispalayLogout:boolean;
  constructor(private router : Router,
              private userRepo : UserRepository,
              private userService : UserService,
              private teamRepsitory : TeamRepository,
              private teamService : TeamService,
              private scrumRepository : ScrumRepository,
              private scrumService : ScrumService,
              private loginService : LoginService) { }

  ngOnInit() {
    this.loginService.logOut$.subscribe(dispalayLogout => this.dispalayLogout =dispalayLogout);
  }

  login(){
    let user : User = new User("","","","","","","");
    user.userEmail = this.loginData.value.email;
    user.password = this.loginData.value.password;

    let tempUser = user;
    this.userRepo.validateUser(user).subscribe(
      users => {
        tempUser = users;
        if(tempUser.userDesignation ==='MANAGER'){
          this.teamRepsitory.getAllTeams().subscribe(
            teams => this.teamService.teams = teams
          );

          this.scrumRepository.getAllScrum().subscribe(
            scrums => {this.scrumService.scrum = scrums;}
          )
          this.userService.initializeData().subscribe(
            user=> this.userService.users = user
          );
          this.loginService.adddispalayLogout(true);
          this.router.navigate(['/admin'])
        } else if(tempUser.userDesignation==='null'){
          this.router.navigate(['/login'])
          this.showMessage = 'Invalid username and password'
        } else {
          this.userService.initializeData().subscribe(
            user=> this.userService.users = user
          );
          this.loginService.adddispalayLogout(true);
          this.router.navigate(['/users', tempUser.userId ])

        }
      }
    );

}
}
<file_sep>/scrum_board/service/UserService.java
package com.tavant.scrum_board.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tavant.scrum_board.models.User;
import com.tavant.scrum_board.repositories.UserRepositories;

@Service
public class UserService {

	@Autowired
	private UserRepositories userRepositories;

	public List<User> userList() {
		return userRepositories.findAll();
	}

	public void createUser(User user) {
		userRepositories.save(user);
	}

	public User getUser(String userId) {

		return userRepositories.findById(userId).get();

	}

	public void deleteuser(String userId) {
		userRepositories.deleteById(userId);

	}

	public void updateUser(User user, String userId) {
		user.setUserId(userId);
		userRepositories.save(user);

	}

	public User checkUser(User user) {

		try {
			System.out.println("gettingdata " +user.getUserEmail());
			User tempUser = userRepositories.findByUserEmail(user.getUserEmail());
			System.out.println(tempUser.getUserDesignation());
			if (tempUser.getUserEmail().equals(user.getUserEmail()) && tempUser.getPassword().equals(user.getPassword())) {

				return tempUser;
			} else {
				User local = new User();
				local.setUserDesignation("null");
				return local;
			}
		} catch(Exception e) {
			User local = new User();
			local.setUserDesignation("null");
			return local;
		}
	}
}
<file_sep>/app/admin/scrums/scrums.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Scrum } from 'src/app/models/scrum.model';
import { ScrumService } from './scrum.service';
import { NgForm } from '@angular/forms';
import { Team } from 'src/app/models/team.model';
import { User } from 'src/app/models/user.model';
import { ScrumRepository } from 'src/app/repository/scrum.repository';

@Component({
  selector: 'app-scrums',
  templateUrl: './scrums.component.html',
  styleUrls: ['./scrums.component.css']
})
export class ScrumsComponent implements OnInit {

  @ViewChild('scrumName') scrumName : NgForm;
  scrums : Scrum[];
  duplicate : boolean = false;
  constructor(private scrumService : ScrumService,
              private scrumRepository : ScrumRepository) { }

  ngOnInit() {
    this.scrums = this.scrumService.scrum;
  }

  getScrumName(){
    const scrumName = this.scrumName.value.teamName;
    let user = [new User("","","","","","","")];
    const team = new Team("NONE", user);
    let newScrum = new Scrum(scrumName,[], team);
    newScrum.tasks.pop();
    // newScrum.team.teamUsers.pop();
    // newScrum.team.teamName.pop();
    team.teamUsers.shift();//CHECK
    if(this.scrumService.validateDuplicate(scrumName)){
      this.scrumService.duplicate = false;
      this.duplicate = true;
    } else {
    this.scrums.push(newScrum);

    //create scrum service newScrum
       this.scrumRepository.crateScrum(newScrum);
      this.duplicate = false;
    }
    this.scrumName.reset();
  }

  deleteScrum(scrumName : string){
    this.scrumService.reamoveScrum(scrumName);
    //services
    this.scrumRepository.deleteScrum(scrumName);
  }

}
<file_sep>/app/repository/toDoRepository.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ToDo } from '../models/toDo.model';

@Injectable()
export class ToDoRepository{
    constructor(private http:HttpClient) { }

    private httpHeader = new HttpHeaders({'Content-Type' : 'application/json'})
    private url = "http://10.130.153.138:8000/todo_api/"
    initialize() : Observable<ToDo[]>{
        return this.http.get<ToDo[]>(this.url+"todo",{headers : this.httpHeader})
    }

    updateToDo(toDo :ToDo){

        this.http.put(this.url+"update_todo", toDo ,{headers: this.httpHeader}).subscribe((data)=>console.log(data),(err)=>console.log(err)

        );
    }

    createToDo(toDo : ToDo){
        this.http.post(this.url+"save",toDo,{headers : this.httpHeader}).subscribe();
    }

    updateToDoTask(story : string , userId : string){
        this.http.put(this.url+"updat_todo/"+story+"/"+userId,{headers : this.httpHeader}).subscribe();
    }
}<file_sep>/app/repository/user.repository.ts

import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Observable } from 'rxjs';
import { User } from '../models/user.model';
import { Injectable } from '@angular/core';

 @Injectable()
export class UserRepository{

    private url = "http://10.130.153.138:8000/user_api/";
    private httpHeader = new HttpHeaders({'Content-Type' : 'application/json'})
    constructor(private http : HttpClient) {}

    createUser(user) : void {

        this.http.post(this.url+"save", JSON.stringify(user), {headers : this.httpHeader}).subscribe();
    }

    getAllUser() : Observable<User[]>{
        return this.http.get<User[]>(this.url+"user",{headers : this.httpHeader});
    }

    deleteUser(userId : string) : void{
        this.http.delete(this.url+"delete/"+userId,{headers : this.httpHeader}).subscribe();
    }

    validateUser(user : User) : Observable<User>{
        return this.http.post<User>(this.url+"validateUser", user, {headers : this.httpHeader});
    }
}<file_sep>/app/admin/view-scrums/view-scrums.component.ts
import { Component, OnInit } from '@angular/core';
import { Scrum } from 'src/app/models/scrum.model';
import { ScrumService } from '../scrums/scrum.service';
import { ScrumRepository } from 'src/app/repository/scrum.repository';

@Component({
  selector: 'app-view-scrums',
  templateUrl: './view-scrums.component.html',
  styleUrls: ['./view-scrums.component.css']
})
export class ViewScrumsComponent implements OnInit {

  isNotEmpty : boolean = true;
  scrums : Scrum[];
  constructor(private scrumScrvice : ScrumService,
              private scrumRepository : ScrumRepository) { }

  ngOnInit() {
    this.scrums = this.scrumScrvice.scrum;
    if(this.scrumScrvice.scrum.length===0){
      this.isNotEmpty = false;
    }
  }

  deleteScrum(scrumName : string){
    this.scrumScrvice.reamoveScrum(scrumName);
    if(this.scrumScrvice.scrum.length===0){
      this.isNotEmpty = false;
    }
    this.scrumRepository.deleteScrum(scrumName);
  }
}
<file_sep>/app/models/user.model.ts
export class User {

    constructor(public userId : string,
                public userFirstName : string,
                public userLastName : string,
                public userEmail : string,
                public userDesignation : string,
                public userTeamName : string,
                public password : string) {}
}<file_sep>/app/admin/scrums/scrum/scrum.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ScrumService } from '../scrum.service';
import { Scrum } from 'src/app/models/scrum.model';

import { Team } from 'src/app/models/team.model';
import { TeamService } from '../../teams/team.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { NgForm } from '@angular/forms';
import { Tasks } from 'src/app/models/tasks.model';
import { refreshDescendantViews } from '@angular/core/src/render3/instructions';
import { User } from 'src/app/models/user.model';
import { ScrumRepository } from 'src/app/repository/scrum.repository';
import { createOfflineCompileUrlResolver } from '@angular/compiler';

@Component({
  selector: 'app-scrum',
  templateUrl: './scrum.component.html',
  styleUrls: ['./scrum.component.css']
})
export class ScrumComponent implements OnInit {

  teamName : string = 'TEMP';
  tasks : string [] = [];
  scrum : Scrum[] ;
  teams : Team[];
  scrumName : string;
  @ViewChild('task') enteredTask : NgForm;
  @ViewChild('teamName') toAssginTeam : ElementRef;
  constructor(private scrumService : ScrumService,
              private teamService : TeamService,
              private router : Router,
              private route : ActivatedRoute,
              private scrumRepository : ScrumRepository) { }

  ngOnInit() {
    this.scrum = this.scrumService.scrum;
    this.teams = this.teamService.teams;
    this.route.params.subscribe( (p : Params)=> { this.scrumName = p['scrumName']} )
    const team = this.toAssginTeam.nativeElement.value;
    for(let i=0; i<this.scrumService.scrum.length ; i++){
      if(this.scrumService.scrum[i].scrumName === this.scrumName){
        for(let j=0; j<this.scrumService.scrum[i].tasks.length ; j++){
          this.tasks.push(this.scrumService.scrum[i].tasks[j].notes);
        }
      }
    }
  }

  addStory(){
    let statues = 1
    if(this.tasks.length===0){
      this.tasks.push(this.enteredTask.value.taskName);
      statues =2;
    } else {
      for(let task of this.tasks){
        if(task === this.enteredTask.value.taskName){
          statues = 2;
          break;
        }
      }
    }
    if(statues===1){
      this.tasks.push(this.enteredTask.value.taskName);
    }
    this.enteredTask.reset();
  }

  assignTeam(){

    for(let i=0; i<this.scrum.length; i++){

      if(this.scrum[i].scrumName === this.scrumName){
        for(let j=0; j<=this.scrum[i].tasks.length ; j++){
          this.scrum[i].tasks.splice(j , 1)
        }
        this.scrum[i].tasks.pop();
      }
    }

    for(let scrum of this.scrum){
      if(scrum.scrumName === this.scrumName){
        for(let task of this.tasks){
          scrum.tasks.push(new Tasks('NONE', task));
          scrum.team.teamName = this.toAssginTeam.nativeElement.value;
        }
        this.scrumRepository.updateScrum(scrum);
      }
    }

    this.tasks.length =0;
    for(let storyTask of this.tasks){
      this.tasks.shift()
    }
    this.tasks.shift();
    this.router.navigate(['/viewScrums']);
  }

  removeTask( task : string) {

    for(let i=0; i<this.tasks.length; i++){
      if(this.tasks[i] === task){
        this.tasks.splice(i , 1);
        break;
      }
    }
  }
}
<file_sep>/app/admin/view-scrums/view-scrum/view-scrum.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { ScrumService } from '../../scrums/scrum.service';
import { Scrum } from 'src/app/models/scrum.model';
import { Tasks } from 'src/app/models/tasks.model';
import { ScrumRepository } from 'src/app/repository/scrum.repository';

@Component({
  selector: 'app-view-scrum',
  templateUrl: './view-scrum.component.html',
  styleUrls: ['./view-scrum.component.css']
})
export class ViewScrumComponent implements OnInit {

  scrum : Scrum ;
  scrumName : string;
  tasks : Tasks[] = [];
  displayConent : boolean = true;
  constructor(private route : ActivatedRoute,
              private scrumService : ScrumService,
              private scrumReapository : ScrumRepository) { }

  ngOnInit() {
    this.route.params.subscribe( (p : Params) => { this.scrumName = p['scrumName']});

    for(let i =0; i< this.scrumService.scrum.length; i++){
      if(this.scrumService.scrum[i].scrumName === this.scrumName){
        this.scrum = this.scrumService.scrum[i];
      }
    }

    this.tasks = this.scrum.tasks;
     this.displayConent = true;
  }

  removeStory(story : string, scrumName : string){
    this.scrumReapository.removeTask(story,scrumName)
    this.scrumService.removeScrumStory(story, scrumName);

  }

  deleteScrum(scrumName : string){
    this.scrumService.reamoveScrum(scrumName);
    this.scrumReapository.deleteScrum(scrumName)
    this.displayConent = false;
  }

}
<file_sep>/scrum_board/repositories/ScrumRepositories.java
package com.tavant.scrum_board.repositories;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.tavant.scrum_board.models.Scrum;

@Repository
public interface ScrumRepositories extends JpaRepository<Scrum, String> {

	public Scrum findByScrumName(String scrumName);

	@Modifying(clearAutomatically = true)
	@Query(value = "delete from scrum where scrum_name=:scrumName", nativeQuery = true)
	@Transactional
	public void deleteByScrumName(String scrumName);

}
<file_sep>/app/models/scrum.model.ts
import { Tasks } from './tasks.model';
import { Team } from './team.model';

export class Scrum {

    constructor(
        public scrumName :  string,
        public tasks : Tasks [],
        public team : Team) {}
}<file_sep>/scrum_board/repositories/ToDoRepositories.java
package com.tavant.scrum_board.repositories;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.tavant.scrum_board.models.ToDo;

@Repository
public interface ToDoRepositories extends JpaRepository<ToDo, String> {

	@Modifying(clearAutomatically = true)
	@Query(value = "delete from  to_do  WHERE to_do.user_id=:userid", nativeQuery = true)
	@Transactional
    public void deleteToDo(@Param("userid") String userid);

	@Modifying(clearAutomatically = true)
	@Query(value = "select t from to_do t WHERE t.user_id=:userid", nativeQuery = true)
	@Transactional
	public void findByDoTO(@Param("userid") String userid);

}
<file_sep>/app/repository/task.repository.ts

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

@Injectable()
export class TaskRepository{

    url = "http://10.130.153.138:8000/task_api/";
    httpHeader = new HttpHeaders({'Content-Type' : 'application/json'});
    constructor(private http: HttpClient){}

    updateStatus(notes : string, scrumName : string, userId : string){
        this.http.put(this.url+"update_status/"+notes+"/"+scrumName+"/"+userId, {headers : this.httpHeader}).subscribe();
    }

    removeStatus(notes : string, scrumName : string){
        this.http.put(this.url+"remove_status/"+notes+"/"+scrumName, {headers : this.httpHeader}).subscribe();
    }
}

languages: Java TypeScript

repo_name: dharmendra-mali/ScrumBoard


text:
<repo_name>nityyyaaaa/concorde_tsp_mac<file_sep>/Text_to_AdjM.py

# coding: utf-8

# In[1]:

import pandas as pd
import numpy as np
import math

# In[2]:

def get_coordinates(df, i):
    parsed = [float(x) for x in df[0][i].split()]
    return((parsed[0], parsed[1]))

# In[15]:

df1 = pd.read_fwf("network1.txt", header = None)
coord1 = []

def make_coord_df(df):
    coord1 = np.empty((len(df),2))
    i = 0
    while i < len(df):
        x = get_coordinates(df,i)[0]
        y = get_coordinates(df,i)[1]
        coord1[i][0] = x
        coord1[i][1] = y
        i += 1
    return coord1

net1_coords = make_coord_df(df1)
pd.DataFrame(net1_coords).to_csv("net1_coords.csv")

# In[16]:

def euclidean(a, b):
    dist = (np.sqrt( math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2)))
    if math.isnan(dist) :
        print (a,b)
    return dist

# In[17]:

def text_to_adjm(txt):
    #Loading df
    df = pd.read_fwf(txt, header=None)
    # Creating an empty n x n matrix
    empty = np.empty((len(df),len(df)))
    # Create Adjacency Matrix
    for i in range(len(df)):
        parsed = [float(x) for x in df[0][i].split()]
        for j in parsed[2:]:
            empty[i][int(j)] = euclidean(get_coordinates(df,i), get_coordinates(df,j))
    for i in range(len(df)):
        for j in range(len(df)):
            if empty[i][j] < 0.00000000000000000001:
                empty[i][j] = 0
    return(empty)

# In[30]:

net1 = text_to_adjm("network1.txt") #100
net2 = text_to_adjm("network2.txt") #500
net3 = text_to_adjm("network3.txt") #1000
net4 = text_to_adjm("network4.txt") #1000
net5 = text_to_adjm("network5.txt") #5000

# In[31]:

pd.DataFrame(net1).to_csv("net1.csv")
pd.DataFrame(net2).to_csv("net2.csv")
pd.DataFrame(net3).to_csv("net3.csv")
pd.DataFrame(net4).to_csv("net4.csv")
pd.DataFrame(net5).to_csv("net5.csv")

# In[29]:

net1[0]

<file_sep>/dm4.R
library("TSP")
concorde_path("/Users/nityasriram/Desktop/dm4/concorde_3/TSP")

# Define functions Infinitise and Symmetrise
infinitise <- function(net){
for (i in 1:nrow(net)) {
  for (j in 1:ncol(net)){
    if (net[i,j] < 0.000000000000001) {net[i,j] = Inf}
  }
}
return(net)
}

symmetrise <- function(net) {
for (i in 1:nrow(net)){
  for (j in 1:i){
    net[j,i] = net[i,j]
  }
}
return(net)
}

ToDist <- function(net){
  result = c()
  for (i in 1:(nrow(net)-1)){
    result = c(result, net[i,(i+1):ncol(net)])
  }
  return(result)
}

# Define a funtion to solve using Concorde code
solve_network <- function(net)
{# Remove indices
  net <- as.matrix(net[,-1])

  # Initialise an arbitrary distance matrix
  net.dist <- dist(net)

  # Fill the distance matrix with the values below the diagonal of net
  net.dist[1:length(net.dist)] <- ToDist(net)

  # Infinitise
  net.dist[net.dist < 0.000000000000001] = Inf

  # TPS-ise
  net.tsp = as.TSP(net.dist)
  net.answer = solve_TSP(net.tsp, method = "concorde")
  return(net.answer)
}

# Load CSVs
net1 <- read.csv("net1.csv")
net2 <- read.csv("net2.csv")
net3 <- read.csv("net3.csv")
net4 <- read.csv("net4.csv")
#net5 <- read.csv("net5.csv")

net1.answer <- solve_network(net1)
net2.answer <- solve_network(net2)
net3.answer <- solve_network(net3)
net4.answer <- solve_network(net4)
#net5.answer <- solve_network(net5)

write_net <- function(net, filename) {
x = as.vector(net)
col1 = x[1:(length(x)-1)]-1
col2 = x[2:length(x)]-1
df = cbind(as.data.frame(col1), as.data.frame(col2))
write.table(df, filename, row.names = FALSE, col.names = FALSE)
}

write_net(net1.answer, "net1answer.txt")
write_net(net2.answer, "net2answer.txt")
write_net(net3.answer, "net3answer.txt")
write_net(net4.answer, "net4answer.txt")
#write_net(net5.answer, "net5answer.txt")

# This is a test run with the US50CA data
concorde_path("/Users/nityasriram/Desktop/dm4/concorde_3/TSP/")
data("USCA50")
this = solve_TSP(USCA50, method = "concorde") # this line generates the error message below

branch_name: refs/heads/master

languages: R Python

repo_language: R


text:
<file_sep>package org.terasoluna.tourreservation.domain.repository.tourinfo

import static org.terasoluna.tourreservation.domain.util.DBUnitUtils.*

import javax.inject.Inject

import org.dbunit.operation.DatabaseOperation
import org.joda.time.DateTime
import org.springframework.data.domain.PageRequest
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ContextConfiguration
import org.springframework.transaction.annotation.Transactional
import org.terasoluna.tourreservation.domain.service.tourinfo.TourInfoService

import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll

@ContextConfiguration(locations = "classpath:test-context.xml")
@Transactional
@Rollback
class TourInfoRepositoryImplSpec extends Specification {

    @Inject
    TourInfoService tourInfoService

    @Inject
    NamedParameterJdbcTemplate jdbcTemplate;

    // 初期設定した上でwhereに使いたい値はここで@Share付きのインスタンス変数で宣言しておく
    @Shared String tourCode

    @Shared DateTime depDay

    @Shared DateTime plannedDay

    @Shared String tourAbs

    @Shared String tourName

    @Shared int basePrice

    def setupSpec() {
        // whereで使いたい値はここで設定する。変数は、@Share付きのインスタンス変数である必要がある。
        tourCode = "8888888888"
        depDay = new DateTime(2014, 2, 2, 0, 0, 0)
        plannedDay = new DateTime(2013, 12, 31, 0, 0, 0)
        tourAbs = "wonderful travel !"
        tourName = "test tour"
        basePrice = 20000
    }

    /**
     * BasePrice and TourDays dont set value Case
     */
    @Unroll
    def "TourInfoの検索でページが #totalPages のテスト" () {
        given: "初期データ投入"
        // DBUnitのデータ投入
        def connection = getConnection(jdbcTemplate)
        def setupDataSet = loadXls(xlsfile, this) // whereパラメータ
        def operation = DatabaseOperation.REFRESH
        operation.execute(connection, setupDataSet)

        // 初期オブジェクトの一部を設定
        // pageableはここで設定し、criteriaは where から設定する。
        def pageable = PageRequest.of(0, 10)

        when: "検索処理が実行された時（テスト対象の実行）"
        def page = tourInfoService.searchTour(criteria, pageable)
        then: "こうなるべき（assert）"
        page.totalPages == totalPages
        page.number == number

        when: "検索が１件以上あれば"
        if (page.totalPages == 0) return

        def tour = page.content.get(0)
        then: "こうなるべき（assert）"
        tour.avaRecMax == avaRecMax
        tour.basePrice == basePrice
        tour.conductor == conductor
        tour.depDay == depDay.toDate()
        tour.plannedDay == plannedDay.toDate()
        tour.tourAbs == tourAbs
        tour.tourCode == tourCode
        tour.tourDays == tourDays
        tour.tourName == tourName
        tour.accommodation.accomCode == accomCode
        tour.accommodation.accomName == accomName
        tour.accommodation.accomTel == accomTel
        tour.departure.depCode == depCode
        tour.departure.depName == depName

        where: "初期値・検索条件パターンと期待値"
        // ここで設定した配列の回数分、テストが繰り返される。
        // Spockの紹介サイトでよく見られるテーブル形式（区切り文字'|')は変数の数が多くなると見にくくなるので
        // 配列形式にしたほうが無難。
        // 注意： この処理はメソッド内で最初に呼ばれる。別の変数を参照する場合、あらかじめ、setupSpec()と@Shareで設定しておく
        //       必要がある。（例）depDay.toDate()
        // 初期値
        // DBUnitを用いてExcelファイルから初期DB値
        xlsfile << [
            "setup_TourInfoRepositoryImplTestDBUnit_1.xlsx" ,
            "setup_TourInfoRepositoryImplTestDBUnit_1.xlsx"
        ]
        // 検索条件パターン
        criteria << [
            new TourInfoSearchCriteria(depDate: depDay.toDate(),
            adultCount:1, arrCode:"01", basePrice:0, childCount:1, depCode:"01", tourDays:0),
            new TourInfoSearchCriteria(depDate: new DateTime(2012, 7, 10, 0, 0, 0).toDate(),
            adultCount:1, arrCode:"01", basePrice:10, childCount:1, depCode:"01", tourDays:2)
        ]
        // ここから期待値
        // ページ数と番号
        totalPages << [1, 0]
        number << [0, 0]
        // 検索結果
        avaRecMax << [2147483647 , _]
        conductor << ["1" , _]
        tourDays << [1 , _]
        accomCode << ["0001" , _]
        accomName << ["TERASOLUNAホテル第一荘" , _]
        accomTel << ["018-123-4567" , _]
        depCode << ["01" , _]
        depName << ["北海道" , _]
    }
}<file_sep>/*
 ReserveRepositoryImplTest.java * Copyright (C) 2013-2018 NTT DATA Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package org.terasoluna.tourreservation.domain.repository.reserve;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.terasoluna.tourreservation.domain.util.DBUnitUtils.*

import javax.inject.Inject

import org.dbunit.operation.DatabaseOperation
import org.joda.time.DateTime
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.terasoluna.tourreservation.domain.model.TourInfo

import spock.lang.Specification
import spock.lang.Unroll

@ContextConfiguration(locations = "classpath:test-context.xml")
@Transactional
@Rollback
class ReserveRepositoryImplSpec extends Specification {

    @Inject
    NamedParameterJdbcTemplate jdbcTemplate;

    @Inject
    ReserveRepository reserveRepository;

    @Unroll
    def testFindWithDetail01() {
        given:
        // DBUnitのデータ投入
        def xls = loadXls('setup_ReserveRepositoryImplSpec_1.xlsx', this)
        def connection = getConnection(jdbcTemplate)
        def operation = DatabaseOperation.REFRESH
        operation.execute(connection, xls)

        def tourCode = "0000000001";
        def reservedDay = new DateTime(2016, 1, 1, 0, 0, 0);
        def tourInfo = new TourInfo();
        tourInfo.setTourCode(tourCode);
        def customerCode = "00000001";
        def reserveNo = "10000000";

        when:
        def reserve = reserveRepository.findOneWithDetail(reserveNo);

        then:
        reserve != null
        reserve.reserveNo == reserveNo
        reserve.reservedDay == reservedDay.toDate()
        reserve.adultCount == 1
        reserve.childCount == 2
        reserve.transfer == "0"
        reserve.sumPrice == 1000
        reserve.remarks == "TEST"
        reserve.customer != null
        reserve.customer.customerCode == customerCode
        reserve.tourInfo != null
        reserve.tourInfo.tourCode == tourCode
    }

}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>terasoluna-tourreservation-domain</artifactId>
  <packaging>jar</packaging>
  <name>TERASOLUNA Server Framework for Java (5.x) - Tour Reservation Application - Domain Layer</name>
  <description>Domain layer of Tour Reservation Application using TERASOLUNA Server Framework for Java (5.x)</description>

  <parent>
    <groupId>org.terasoluna.app</groupId>
    <artifactId>terasoluna-tourreservation</artifactId>
    <version>5.5.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <dependencies>
    <!-- == Begin TERASOLUNA == -->
    <dependency>
      <groupId>org.terasoluna.gfw</groupId>
      <artifactId>terasoluna-gfw-common-dependencies</artifactId>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>org.terasoluna.gfw</groupId>
      <artifactId>terasoluna-gfw-jodatime-dependencies</artifactId>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>org.terasoluna.gfw</groupId>
      <artifactId>terasoluna-gfw-security-core-dependencies</artifactId>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>org.terasoluna.gfw</groupId>
      <artifactId>terasoluna-gfw-mybatis3-dependencies</artifactId>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>org.terasoluna.gfw</groupId>
      <artifactId>terasoluna-gfw-recommended-dependencies</artifactId>
      <type>pom</type>
    </dependency>
    <!-- == End TERASOLUNA == -->

    <!-- == Begin Database == -->
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <scope>runtime</scope>
    </dependency>
    <!-- == End Database == -->

    <!-- == Begin JasperReports == -->
    <dependency>
      <groupId>jasperreports</groupId>
      <artifactId>jasperreports</artifactId>
    </dependency>
    <!-- == End JasperReports == -->

    <!-- == Begin Unit Test == -->
    <!-- == Begin TourReservation == -->
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>terasoluna-tourreservation-env</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- == End TourReservation == -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-el</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- == End Unit Test == -->

    <!-- == Begin Coding Support == -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <scope>provided</scope>
    </dependency>
    <!-- == End Coding Support == -->

    <!-- == Begin DBUnit+Spock Support == -->
    <dependency>
      <groupId>com.github.springtestdbunit</groupId>
      <artifactId>spring-test-dbunit</artifactId>
      <version>1.3.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.dbunit</groupId>
      <artifactId>dbunit</artifactId>
      <version>2.5.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-core</artifactId>
      <version>1.2-groovy-2.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-spring</artifactId>
      <version>1.2-groovy-2.4</version>
    </dependency>
    <!-- == End DBUnit+Spock Support == -->
  </dependencies>

  <properties>
    <project.root.basedir>${project.parent.basedir}</project.root.basedir>
    <surefire.version>2.19.1</surefire.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <!-- see: https://github.com/groovy/groovy-eclipse/wiki/Groovy-Eclipse-Maven-plugin -->
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <compilerId>groovy-eclipse-compiler</compilerId>
          <source>${java-version}</source>
          <target>${java-version}</target>
          <!-- https://stackoverflow.com/questions/8524891/maven-groovy-and-java-lombok -->
          <fork>true</fork>
          <compilerArguments>
            <javaAgentClass>lombok.launch.Agent</javaAgentClass>
          </compilerArguments>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-eclipse-compiler</artifactId>
            <version>2.9.2-01</version>
          </dependency>
          <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-eclipse-batch</artifactId>
            <version>2.4.3-01</version>
          </dependency>
          <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
          </dependency>
        </dependencies>
      </plugin>

      <plugin>
        <!--
        [ How to execute JUnit(=Spock) and TestNG test cases at same time ? ]
        see: http://solidsoft.wordpress.com/2013/03/12/mixing-testng-and-junit-tests-in-one-maven-module-2013-edition/
        -->
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire.version}</version>
        <dependencies>
          <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire-junit47</artifactId>
            <version>${surefire.version}</version>
          </dependency>
        </dependencies>
        <configuration>
          <!-- resolve "Cannot use a threadCount parameter less than 1; 1 > 0" error. -->
          <threadCount>1</threadCount>
          <includes>
            <!-- for JUnit, explicitly add xxxSpec and xxxTest file patterns. -->
            <!-- (mysteriously, ".groovy" dosn't work for Spock's xxxxSpec.groovy, but ".java" work!!) -->
            <include>**/*Spec.java</include>
            <include>**/*Test.java</include>
          </includes>
        </configuration>
      </plugin>
      <!--
        Alternative solution for copying test resources from src/test/java
        https://stackoverflow.com/questions/4221285/maven-surefire-copy-test-resources-from-src-test-java -->
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
          <execution>
            <id>copy-resources</id>
            <phase>validate</phase>
            <!--
            <phase>process-test-resources</phase>
             -->
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.basedir}/target/test-classes</outputDirectory>
              <resources>
                <resource>
                  <directory>${project.basedir}/src/test/java</directory>
                    <includes>
                      <include>**/*.xlsx</include>
                    </includes>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>

    <!-- https://stackoverflow.com/questions/4221285/maven-surefire-copy-test-resources-from-src-test-java -->
    <!-- It does not work properly.
         "mvn test" command works, but JUnit due to Eclipse right click does not work.
    <testResources>
      <testResource>
        <directory>${project.basedir}/src/test/java</directory>
        <includes>
          <include>**/*.xlsx</include>
        </includes>
      </testResource>
      <testResource>
        <directory>${project.basedir}/src/test/resources</directory>
      </testResource>
    </testResources>
     -->
  </build>
</project>
<file_sep>package org.terasoluna.tourreservation.domain.util;

import static org.hamcrest.CoreMatchers.*
import static org.junit.Assert.*
import static org.mockito.Mockito.*
import static org.terasoluna.tourreservation.domain.util.DBUnitUtils.*

import javax.inject.Inject

import org.dbunit.dataset.IDataSet
import org.dbunit.dataset.ITable
import org.dbunit.operation.DatabaseOperation
import org.joda.time.DateTime
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ContextConfiguration
import org.springframework.transaction.annotation.Transactional

import spock.lang.Specification

@ContextConfiguration(locations = "classpath:test-context.xml")
@Transactional
@Rollback
class DBUnitUtilsSpec extends Specification {

    @Inject
    NamedParameterJdbcTemplate jdbcTemplate;

    def "DB登録内容の確認"() {
        given: "変更前のテーブル取り出し"

        def connection = getConnection(jdbcTemplate)

        // 変更前データ
        IDataSet databaseDataSet = connection.createDataSet();
        ITable before = databaseDataSet.getTable("customer");

        // データ投入
        def setupxlsfile = 'setup_and_expect_insert_Customer.xlsx'
        def setupDataSet = loadXls(setupxlsfile, this)
        DatabaseOperation operation =  DatabaseOperation.REFRESH
        operation.execute(connection, setupDataSet)

        String q;
        Map<String, Object> param;

        q = "UPDATE customer SET customer_name = :customerName, customer_kana = :customerKana WHERE customer_code = :customerCode";
        param = new HashMap<String, Object>();
        param.put("customerCode", "00000001");
        param.put("customerName", "木村　次郎");
        param.put("customerKana", "キムラ　ジロウ");
        jdbcTemplate.update(q, param);

        q = "UPDATE customer SET customer_birth = :customerBirth WHERE customer_code = :customerCode";
        param = new HashMap<String, Object>();
        param.put("customerCode", "00000002");
        param.put("customerBirth", new DateTime(2012, 7, 10, 0, 0, 0).toDate());
        jdbcTemplate.update(q, param);

        q = "DELETE FROM customer WHERE customer_code = :customerCode";
        param = new HashMap<String, Object>();
        param.put("customerCode", "00000009");
        jdbcTemplate.update(q, param);

        q = "DELETE FROM customer WHERE customer_code = :customerCode";
        param = new HashMap<String, Object>();
        param.put("customerCode", "00000010");
        jdbcTemplate.update(q, param);

        // 変更後データ
        ITable after = databaseDataSet.getTable("customer");

        // 差分
        def actual = diff(before, after)
        println "差分 ${actual}"

        when:
        // 期待値
        def xlsfile = 'setup_and_expect_insert_Customer.xlsx'
        def expectedDataSet = loadXls(xlsfile, this)
        def expectedInsert = expectedDataSet.getTable("customer");

        then:
        diff(actual.inserted, expectedInsert) == null
        //diff(actual.deleted, expectedDelete) == null
        //diff(actual.updated, expectedUpdate) == null
    }
}
<file_sep>package org.terasoluna.tourreservation.domain.service.customer;

import static org.hamcrest.CoreMatchers.*
import static org.junit.Assert.*
import static org.mockito.Mockito.*

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.terasoluna.tourreservation.domain.model.Customer;
import org.terasoluna.tourreservation.domain.repository.customer.CustomerRepository;

import spock.lang.Specification

class CustomerServiceImplSpec extends Specification {

    CustomerServiceImpl customerService;

    CustomerRepository customerRepository;

    /*
     * https://qiita.com/aya_eiya/items/d12f72b16fcd1d619192
     *
     * テストを通じて振る舞いが変わらないMock対象
     * setupSpecでMockオブジェクトを用意する
     * 同様にsetupSpecで振る舞いまで定義する
     * ことによって、テスト全体の前提となるMock定義を一箇所で管理する
     *
     * それぞれのテストにおいて振る舞いを変える必要のあるMock対象
     * setupでMockオブジェクトを用意する
     * 各テストメソッドのsetupまたはwhenで動作を定義する
     * ことによって、whereによるDataDrivenなテストをやりやすくする
     */
    def setup() {
        customerService = new CustomerServiceImpl();
        customerRepository = Mock();
        customerService.customerRepository = customerRepository;
        customerService.passwordEncoder = new BCryptPasswordEncoder();
    }

    def testFindOne01() {
        given:
        def c = new Customer()
        customerRepository.findOne("xxx") >> c

        when:
        def result = customerService.findOne("xxx")

        then:
        result == c
    }

    def testFindOne02() {
        given:
        customerRepository.findOne("xxx") >> null

        when:
        def result = customerService.findOne("xxx")

        then:
        result == null
    }

    def testRegister01() {
        given:
        def c = new Customer();

        when:
        customerService.register(c, "foo");

        then: "insertメソッドが1回は呼ばれること"
        1 * customerRepository.insert(c)
    }

}
<file_sep>package org.terasoluna.tourreservation.domain.service.customer;

import static org.hamcrest.CoreMatchers.*
import static org.junit.Assert.*
import static org.mockito.Mockito.*
import static org.terasoluna.tourreservation.domain.util.DBUnitUtils.*

import javax.inject.Inject

import org.dbunit.dataset.IDataSet
import org.dbunit.dataset.ITable
import org.joda.time.DateTime
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ContextConfiguration
import org.springframework.transaction.annotation.Transactional
import org.terasoluna.tourreservation.domain.model.Customer

import spock.lang.Specification

@ContextConfiguration(locations = "classpath:test-context.xml")
@Transactional
@Rollback
class CustomerServiceImplDBUnitSpec extends Specification {

    @Inject
    CustomerService customerService;

    @Inject
    NamedParameterJdbcTemplate jdbcTemplate;

    def "DB登録内容の確認"() {
        given: ""
        def connection = getConnection(jdbcTemplate)
        IDataSet databaseDataSet = connection.createDataSet();
        ITable before = databaseDataSet.getTable("customer");

        // シーケンス番号初期化
        jdbcTemplate.queryForList("select setval ('customer_code_seq', 11);", new HashMap())

        def c = new Customer(
                customerName: '<NAME>',
                customerKana: 'データ　ジュウロウ',
                customerPass: '<PASSWORD>',
                customerBirth: new DateTime(1987, 5, 25, 0, 0, 0).toDate(),
                customerJob: '営業',
                customerMail: '<EMAIL>',
                customerTel: '123-1234-1234',
                customerPost: '135-8671' ,
                customerAdd: '東京都江東区豊洲3-3-9',
                );
        customerService.register(c, "foo");

        when:
        ITable after = databaseDataSet.getTable("customer");
        def actual = diff(before, after).inserted

        def expectedDataSet = loadXls('expect_insert_CustomerServiceImplDBUnitSpec.xlsx', this)
        def expected = expectedDataSet.getTable("customer");

        then:
        diff(actual, expected) == null
    }
}
<file_sep>## DBUnit+Spock (+jdbc.resultsettable like output tools) on TERASOLUNA Sample Application

## Contents
See [changes (Added environment setting and sample of "Eclipse + DBUnit + Spock")](https://github.com/hide212131/terasoluna-tourreservation-mybatis3/commit/600311a7549ae56786398ca86c9691d704b7ec7c)

## Tools
[DBUnitUtils.java](https://github.com/hide212131/terasoluna-tourreservation-mybatis3/blob/600311a7549ae56786398ca86c9691d704b7ec7c/terasoluna-tourreservation-domain/src/test/java/org/terasoluna/tourreservation/domain/util/DBUnitUtils.java)

### jdbc.resultsettable like output
```
println toString(itable)

|customer_code|customer_name|     customer_kana|                                               customer_pass|customer_birth|customer_job|         customer_mail| customer_tel|customer_post|         customer_add|
|-------------|-------------|------------------|------------------------------------------------------------|--------------|------------|----------------------|-------------|-------------|---------------------|
|     00000001|   木村　太郎|    キムラ　タロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1975-01-05|  プログラマ|     <EMAIL>|111-1111-1111|     276-0022| 千葉県八千代市上高野|
|     00000002|   前田　五郎|    マエダ　ゴロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1980-12-13|      建設業|     <EMAIL>|222-2222-2222|     135-8671|東京都江東区豊洲3-3-9|
|     00000003|   鈴木　花子|    スズキ　ハナコ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1960-10-21|        主婦|                      |333-3333-3333|     616-0000|         京都市右京区|
|     00000004|   加藤　一郎|  カトウ　イチロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1965-03-12|      自営業|   <EMAIL>|444-4444-4444|     039-1500|         三戸郡五戸町|
|     00000005| 田中　南都化|  タナカ　ナントカ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1970-06-30|      自営業|   <EMAIL>|555-5555-5555|     039-1500|         三戸郡五戸町|
|     00000006|     渡辺　梟|ワタナベ　フクロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1966-11-03|      自営業|<EMAIL>|666-6666-6666|     135-8671|東京都江東区豊洲3-3-9|
|     00000007| データ　太郎|    データ　タロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1970-04-05|        営業|     <EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|     00000008| データ　次郎|    データ　ジロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1972-05-15|        営業|     <EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|     00000009| データ　三郎|  データ　サブロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1974-06-02|        営業|     <EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|     00000010| データ　四郎|    データ　シロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1976-12-30|        営業|     <EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|     00000011| データ　五郎|    データ　ゴロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|    1978-05-25|        営業|     <EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
```

### Two ITable's diff
```
println diff(before, after)

|CUD|customer_code|           customer_name|                   customer_kana|                                               customer_pass|          customer_birth|customer_job|    customer_mail| customer_tel|customer_post|         customer_add|
|---|-------------|------------------------|--------------------------------|------------------------------------------------------------|------------------------|------------|-----------------|-------------|-------------|---------------------|
| D |     00000009|            データ　三郎|                データ　サブロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|              1974-06-02|        営業|<EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
| D |     00000010|            データ　四郎|                  データ　シロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|              1976-12-30|        営業|<EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
| C |     00000012|            データ　八郎|              データ　ジュウロウ|                                                    password|              1987-05-25|        営業|<EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
| U |     00000002|              前田　五郎|                  マエダ　ゴロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|1980-12-13 >> 2012-07-10|      建設業|<EMAIL>|222-2222-2222|     135-8671|東京都江東区豊洲3-3-9|
| U |     00000001|木村　太郎 >> 木村　次郎|キムラ　タロウ >> キムラ　ジロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|              1975-01-05|  プログラマ|<EMAIL>|111-1111-1111|     276-0022| 千葉県八千代市上高野|
```

### with Spock report
```
in where clause:

diff(actual.inserted, expectedInsert) == null
|    |      |         |               |
|    |      |         |               false
|    |      |
|    |      |         |customer_code|customer_name|     customer_kana|customer_pass|customer_birth|customer_job|    customer_mail| customer_tel|customer_post|         customer_add|
|    |      |         |-------------|-------------|------------------|-------------|--------------|------------|-----------------|-------------|-------------|---------------------|
|    |      |         |     00000012| データ　八郎|データ　ジュウロウ|     password|    <PASSWORD>|        営業|<EMAIL>|<PASSWORD>|     135-8671|東京都江東区豊洲3-3-9|
|    |
|    |      |customer_code|customer_name|     customer_kana|customer_pass|customer_birth|customer_job|    customer_mail| customer_tel|customer_post|         customer_add|
|    |      |-------------|-------------|------------------|-------------|--------------|------------|-----------------|-------------|-------------|---------------------|
|    |      |     00000012| データ　八郎|データ　ジュウロウ|     password|    <PASSWORD>|        営業|<EMAIL>|<PASSWORD>|     135-8671|東京都江東区豊洲3-3-9|
|
|    |CUD|customer_code|           customer_name|                   customer_kana|                                               customer_pass|          customer_birth|customer_job|    customer_mail| customer_tel|customer_post|         customer_add|
|    |---|-------------|------------------------|--------------------------------|------------------------------------------------------------|------------------------|------------|-----------------|-------------|-------------|---------------------|
|    | D |     00000009|            データ　三郎|                データ　サブロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|              1974-06-02|        営業|<EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|    | D |     00000010|            データ　四郎|                  データ　シロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|              1976-12-30|        営業|<EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|    | C |     00000012|            データ　八郎|              データ　ジュウロウ|                                                    password|              1987-05-25|        営業|<EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
|    | U |     00000002|              前田　五郎|                  マエダ　ゴロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|1980-12-13 >> 2012-07-10|      建設業|<EMAIL>|222-2222-2222|     135-8671|東京都江東区豊洲3-3-9|
|    | U |     00000001|木村　太郎 >> 木村　次郎|キムラ　タロウ >> キムラ　ジロウ|$2a$12$Jfwcv/ZpfE0QjVlLT9CB9eqTLrYdAsvfGxXKvRMlpkfEn.9Uirgou|              1975-01-05|  プログラマ|<EMAIL>|111-1111-1111|     276-0022| 千葉県八千代市上高野|

|CUD|customer_code|customer_name|     customer_kana|customer_pass|          customer_birth|customer_job|                         customer_mail| customer_tel|customer_post|         customer_add|
|---|-------------|-------------|------------------|-------------|------------------------|------------|--------------------------------------|-------------|-------------|---------------------|
| U |     00000012| データ　八郎|データ　ジュウロウ|     password|<PASSWORD> >> 1987-05-26|        営業|<EMAIL> >> <EMAIL>|123-1234-1234|     135-8671|東京都江東区豊洲3-3-9|
```

## Tour Reservation Sample Application
This is a reference application built completely using TERASOLUNA Server Framework for Java (5.x) ([http://terasoluna.org](http://terasoluna.org "http://terasoluna.org")).

This application shows **how an IDEAL project configuration and package structure must be like.** It also shows working sample of best practices recommended in TERASOLUNA Server Framework for Java (5.x) Development Guideline.

**This sample uses MyBatis3.**

[![Build Status for master](https://travis-ci.org/terasolunaorg/terasoluna-tourreservation-mybatis3.svg?branch=master)](https://travis-ci.org/terasolunaorg/terasoluna-tourreservation-mybatis3)

### Getting started

#### Download

Download source code from [here](https://github.com/terasolunaorg/terasoluna-tourreservation-mybatis3/releases "here").
Extract the zip file at any location of choice.

#### Run PostgreSQL

Install and start PostgreSQL.
select '<PASSWORD>' as password for db user or select any password of choice. Be sure to remember the password.
If '<PASSWORD>' is not used, some changes will be required in configuration files. Hence be sure to remember it.

### Run PostgreSQL

Install and start PostgreSQL.

create database 'tourreserve'.

#### Insert test data

It is assumed that maven is already installed.
Move to the directory where the downloaded source-code is unzipped.
If password of db user is set to '<PASSWORD>' its not required to edit any file and directly execute the below command.
If it is set to any other password, then update the password in `terasoluna-tourreservation-initdb/pom.xml`.

Execute the below command:

```console
$ mvn -f terasoluna-tourreservation-initdb/pom.xml sql:execute
```

Test data is currently available in Japanese only.

#### Install jars and build war

If db user password is not set to '<PASSWORD>', then go to `terasoluna-tourreservation-env/src/main/resources/META-INF/spring/terasoluna-tourreservation-infra.properties` and update the password. If it is set to '<PASSWORD>', no changes are required.

```console
$ mvn clean install
```

#### Run server and deploy war

Deploy `terasoluna-tourreservation-web/target/terasoluna-tourreservation-web.war` to your Application server (e.g. Tomcat8)

You can also use `mvn cargo:run` to test this application quickly with option `MAVEN_OPTS=-XX:MaxPermSize=256m` in environment variable.

```console
$ mvn -f terasoluna-tourreservation-web/pom.xml cargo:run
```

access [http://localhost:8080/terasoluna-tourreservation-web/](http://localhost:8080/terasoluna-tourreservation-web/)

Alternatively, these project can also be imported into Eclipse and application can be run using WTP.

#### Test with selenium

Install Firefox to run test.

Run test.

```console
$ mvn -f terasoluna-tourreservation-selenium/pom.xml clean test
```

languages:
Groovy
Markdown
Maven POM

repo_language: Groovy