아래 그림처럼 config.php 파일 상단에 나와있습니다.

There is above in config.php file like this below capture

 

'Programing' 카테고리의 다른 글

구글 캘린더 API 자바 연동  (14) 2019.04.12
php 프로그래밍 게시판 사진 보이게 하는 소스코드  (0) 2016.03.27
알고리즘의 종류  (0) 2015.10.18
br 태그  (0) 2015.10.18
배치파일 명령어  (0) 2014.03.13

구글 캘린더 API를 자바 기준으로 작성해보겠습니다.

 

목차

1. 구글캘린더 API 연동

2. Controller구현

3. 화면구현

4. 실행화면

 

 

1. 구글캘린더 API 연동

밑에 google API 콘솔로 들어갑니다

https://console.developers.google.com/?hl=ko

 

 

프로젝트 만들기 클릭

 

 

프로젝트를 만들어줍니다.

 

 

라이브러리 -> Calendar API 클릭

 

 

사용 설정 클릭

 

 

사용자 인증 정보 만들기 클릭

 

 

java로 구현하기때문에 웹서버 -> 애플리케이션 데이터 -> 아니요 -> 사용자 인정 정보 클릭

 

 

서비스 계정 이름은 아무거나 적고 -> 역할도 적당히 설정 -> 키 유형 JSON 체크 -> 계속

 

 

사용자 동의화면을 정해줍니다. -> 저장클릭

 

 

사용자 인증 정보 만들기 -> OAuth 클라이언트 ID 클릭

 

 

기타유형 -> 생성

 

 

접속정보 JSON을 다운 받습니다.

 

 

파일명을 변경

 

 

client_secret.json

 

 

src/main/resources 경로에 넣어줍니다.

 

 

dependency

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

        <!-- google api -->

        <dependency>

            <groupId>com.google.api-client</groupId>

            <artifactId>google-api-client</artifactId>

            <version>1.22.0</version>

        </dependency>

 

        <dependency>

            <groupId>com.google.oauth-client</groupId>

            <artifactId>google-oauth-client-jetty</artifactId>

            <version>1.22.0</version>

        </dependency>

 

        <dependency>

            <groupId>com.google.apis</groupId>

            <artifactId>google-api-services-calendar</artifactId>

            <version>v3-rev235-1.22.0</version>

        </dependency>

Colored by Color Scripter

cs

 

 

 

 

 

java로 접속할 객체를 만들어줍니다.

 

 

GoogleCalendarService.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

package com.t.hc.beans;

 

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.Arrays;

import java.util.List;

 

import com.google.api.client.auth.oauth2.Credential;

import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;

import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;

import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;

import com.google.api.client.http.HttpTransport;

import com.google.api.client.json.JsonFactory;

import com.google.api.client.json.jackson2.JacksonFactory;

import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.calendar.Calendar;

import com.google.api.services.calendar.CalendarScopes;

//import com.google.api.services.calendar.model.CalendarList;

//import com.google.api.services.calendar.model.CalendarListEntry;

 

public class GoogleCalendarService {

 

    private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";

 

    private static final java.io.File DATA_STORE_DIR = new java.io.File(

            System.getProperty("user.home"),

            ".credentials/calendar-java-quickstart");

 

    private static FileDataStoreFactory DATA_STORE_FACTORY;

 

    private static final JsonFactory JSON_FACTORY = JacksonFactory

            .getDefaultInstance();

 

    private static HttpTransport HTTP_TRANSPORT;

 

    private static final List<String> SCOPES = Arrays

            .asList(CalendarScopes.CALENDAR);

 

    static {

        try {

            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);

        } catch (Throwable t) {

            t.printStackTrace();

            System.exit(1);

        }

    }

 

    public static Credential authorize() throws IOException {

        InputStream in = GoogleCalendarService.class

                .getResourceAsStream("/client_secret.json");

        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(

                JSON_FACTORY, new InputStreamReader(in));

 

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(

                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)

                .setDataStoreFactory(DATA_STORE_FACTORY)

                .setAccessType("offline").build();

        Credential credential = new AuthorizationCodeInstalledApp(flow,

                new LocalServerReceiver()).authorize("user");

        System.out.println("Credentials saved to "

                + DATA_STORE_DIR.getAbsolutePath());

        return credential;

    }

 

    public static Calendar getCalendarService() throws IOException {

        Credential credential = authorize();

        return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)

                .setApplicationName(APPLICATION_NAME).build();

    }

 

//    public static void main(String[] args) throws IOException {

//        com.google.api.services.calendar.Calendar service = getCalendarService();

//        // 캘린더 조회

//        String pageToken = null;

//        do {

//          CalendarList calendarList = service.calendarList().list().setPageToken(pageToken).execute();

//          List<CalendarListEntry> items1 = calendarList.getItems();

//

//          for (CalendarListEntry calendarListEntry : items1) {

//            System.out.println(calendarListEntry.getSummary());

//            System.out.println(calendarListEntry.getId());

//          }

//          pageToken = calendarList.getNextPageToken();

//        } while (pageToken != null);

//    }

}

Colored by Color Scripter

cs

 

 

 

 

 

접속 테스트를위해 main메소드를 돌려봅니다.

 

 

성공적으로 수행되면 최초호출시 권한요청 브라우저 창이 뜸니다.

 

 

성공적으로 calendar 목록데이터를 가져온걸 볼수있습니다.

 

 

CalendarDto.java 작성

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

package com.t.hc.dto;

 

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

public class CalendarDto {

    

    private String summary;

    private String startDate;

    private String startTime;

    private String endDate;

    private String endTime;

    private String description;

    private String eventId;

    private String calendarId;

    

    {

        description = "";

    }

    

    public CalendarDto() {}

    

    public Date getStartDateTime() throws ParseException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHH:mm");

        return format.parse(startDate+startTime);

    }

    public Date getEndDateTime() throws ParseException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHH:mm");

        return format.parse(endDate+endTime);

    }

    

    public String getSummary() {

        return summary;

    }

    public void setSummary(String summary) {

        this.summary = summary;

    }

    public String getStartDate() {

        return startDate;

    }

    public void setStartDate(String startDate) {

        this.startDate = startDate;

    }

    public String getStartTime() {

        return startTime;

    }

    public void setStartTime(String startTime) {

        this.startTime = startTime;

    }

    public String getEndDate() {

        return endDate;

    }

    public void setEndDate(String endDate) {

        this.endDate = endDate;

    }

    public String getEndTime() {

        return endTime;

    }

    public void setEndTime(String endTime) {

        this.endTime = endTime;

    }

    public String getDescription() {

        return description;

    }

    public void setDescription(String description) {

        this.description = description;

    }

    public String getEventId() {

        return eventId;

    }

    public void setEventId(String eventId) {

        this.eventId = eventId;

    }

    public String getCalendarId() {

        return calendarId;

    }

    public void setCalendarId(String calendarId) {

        this.calendarId = calendarId;

    }

 

    @Override

    public String toString() {

        return "GoogleCalendarDto [summary=" + summary + ", startDate=" + startDate + ", startTime=" + startTime

                + ", endDate=" + endDate + ", endTime=" + endTime + ", description=" + description + ", eventId="

                + eventId + ", calendarId=" + calendarId + "]";

    }

}

Colored by Color Scripter

cs

 

 

 

2. Controller구현

캘린더 리스트 Controller 작성

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

package com.t.hc;

 

import java.io.IOException;

import java.util.List;

 

import javax.servlet.http.HttpServletRequest;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

import com.google.api.services.calendar.Calendar;

import com.google.api.services.calendar.model.CalendarList;

import com.google.api.services.calendar.model.CalendarListEntry;

import com.t.hc.beans.GoogleCalendarService;

import com.t.hc.dto.CalendarDto;

 

@Controller

public class HandcodingController {

    

    private Logger logger = LoggerFactory.getLogger(HandcodingController.class);

    

    // 캘린더리스트

    @RequestMapping(value="/coding.do", method=RequestMethod.GET)

    public String coding(Model model) {

        logger.info("calendarList");

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            CalendarList calendarList = service.calendarList().list().setPageToken(null).execute();

            List<CalendarListEntry> items = calendarList.getItems();

            model.addAttribute("items", items);

        } catch (IOException e) {

            e.printStackTrace();

        }

        return "coding";

    }

    

    // 캘린더 생성 처리

    @RequestMapping(value="/calendarAdd.do", method=RequestMethod.POST)

    public String calendarAdd(CalendarDto calDto) {

        logger.info("calendarAdd "+calDto.toString());

        

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            com.google.api.services.calendar.model.Calendar calendar = new com.google.api.services.calendar.model.Calendar();

            calendar.setSummary(calDto.getSummary());

            calendar.setTimeZone("America/Los_Angeles");

            service.calendars().insert(calendar).execute();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return "redirect:/coding.do";

    }

    

    // 캘린더 삭제 처리

    @RequestMapping(value="/calendarRemove.do", method=RequestMethod.POST)

    public String calendarRemove(HttpServletRequest req) {

        logger.info("calendarRemove");

        

        String[] chkVal = req.getParameterValues("chkVal");

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            for (String calendarId : chkVal) {

                service.calendars().delete(calendarId).execute();

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

        return "redirect:/coding.do";

    }    

    

    // 캘린더 수정 처리

    @RequestMapping(value="/calendarModify.do", method=RequestMethod.POST)

    public String calendarModify(CalendarDto calDto) {

        logger.info("calendarModify "+calDto.toString());

        

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            com.google.api.services.calendar.model.Calendar calendar = service.calendars().get(calDto.getCalendarId()).execute();

            calendar.setSummary(calDto.getSummary());

            service.calendars().update(calendar.getId(), calendar).execute();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return "redirect:/coding.do";

    }    

    

    // 캘린더 이동처리

    @RequestMapping(value="/schdule.do", method=RequestMethod.GET)

    public String schdule(Model model, String calendarId, String title) {

        logger.info("schdule");

        model.addAttribute("calendarId", calendarId);

        model.addAttribute("title", title);

        return "schdule";

    }    

}

 

Colored by Color Scripter

cs

 

 

 

 

일정이벤트 핸들링할 ajax컨트롤러 작성

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

package com.t.hc;

 

import java.io.IOException;

import java.text.ParseException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 

import com.google.api.client.util.DateTime;

import com.google.api.services.calendar.Calendar;

import com.google.api.services.calendar.model.Event;

import com.google.api.services.calendar.model.EventDateTime;

import com.google.api.services.calendar.model.Events;

import com.t.hc.beans.GoogleCalendarService;

import com.t.hc.dto.CalendarDto;

 

@RestController

public class CalendarAjaxController {

    

    private Logger logger = LoggerFactory.getLogger(CalendarAjaxController.class);

    

    // 일정 데이터 처리

    @RequestMapping(value="/calendarEventList.do", method=RequestMethod.POST)

    public List<Event> calendarEventList(CalendarDto calDto) {

        logger.info("calendarEventList "+calDto.toString());

        

        List<Event> items = new ArrayList<Event>();

        try {

            com.google.api.services.calendar.Calendar service = GoogleCalendarService.getCalendarService();

            Events events = service.events().list(calDto.getCalendarId()).setOrderBy("startTime").setSingleEvents(true).execute();

            items = events.getItems();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return items;

    }

    

    // 일정 저장 처리

    @RequestMapping(value="/calendarEventAdd.do", method=RequestMethod.POST)

    public Map<String, Boolean> calendarEventAdd(CalendarDto calDto) {

        logger.info("calendarEventAdd "+calDto.toString());

        

        boolean isc = false;

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            Event event = new Event().setSummary(calDto.getSummary()).setDescription(calDto.getDescription());

            //시작일

            DateTime startDateTime = new DateTime(calDto.getStartDateTime());

            EventDateTime start = new EventDateTime().setDateTime(startDateTime).setTimeZone("America/Los_Angeles");

            event.setStart(start);

            //종료일

            DateTime endDateTime = new DateTime(calDto.getEndDateTime());

            EventDateTime end = new EventDateTime().setDateTime(endDateTime).setTimeZone("America/Los_Angeles");

            event.setEnd(end);

            event = service.events().insert(calDto.getCalendarId(), event).execute();

            isc = true;

        } catch (IOException | ParseException e) {

            e.printStackTrace();

        }

        Map<String, Boolean> map = new HashMap<String, Boolean>();

        map.put("isc", isc);

        return map;

    }    

    

    // 일정 삭제

    @RequestMapping(value="/calendarEventRemoveOne.do", method=RequestMethod.POST)

    public Map<String, Boolean> calendarEventRemoveOne(CalendarDto calDto) {

        logger.info("calendarEventRemoveOne "+calDto.toString());

        

        boolean isc = false;

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            service.events().delete(calDto.getCalendarId(), calDto.getEventId()).execute();

            isc = true;

        } catch (IOException e) {

            e.printStackTrace();

        }

        Map<String, Boolean> map = new HashMap<String, Boolean>();

        map.put("isc", isc);

        return map;

    }

    

    // 일정 수정

    @RequestMapping(value="/calendarEventModify.do", method=RequestMethod.POST)

    public Map<String, Boolean> calendarEventModify(CalendarDto calDto) {

        logger.info("calendarEventModify "+calDto.toString());

        

        boolean isc = false;

        try {

            Calendar service = GoogleCalendarService.getCalendarService();

            Event event = service.events().get(calDto.getCalendarId(), calDto.getEventId()).execute();

            event.setSummary(calDto.getSummary()).setDescription(calDto.getDescription());

            service.events().update(calDto.getCalendarId(), event.getId(), event).execute();

            isc = true;

        } catch (IOException e) {

            e.printStackTrace();

        }

        Map<String, Boolean> map = new HashMap<String, Boolean>();

        map.put("isc", isc);

        return map;

    }

}

Colored by Color Scripter

cs

 

 

 

 

3. 화면구현

캘린더 리스트화면

coding.jsp

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>캘린더 관리</title>

<script src="./js/jquery-3.1.1.min.js"></script>

<script src="./js/bootstrap.min.js"></script>

<link rel="stylesheet" href="./css/bootstrap.min.css">

<link rel="stylesheet" href="./css/bootstrap-theme.min.css">

<script type="text/javascript" src='./js/sweetalert.min.js?ver=1'></script>

<link rel="stylesheet" type="text/css" href='./css/sweetalert.css?ver=1.2'>

<script type="text/javascript" src="./js/calendarList.js"></script>

</head>

<body>

    <form action="./calendarRemove.do" method="post" id="frmCalendarRemove">

        <table class="table table-bordered">

            <tr>

                <th><input type='checkbox' onclick='checkAllDel(this.checked)' />전체</th>

                <th>캘린더이름</th>

                <th>캘린더코드</th>

            </tr>

            <c:forEach items="${items}" var="item">

                <tr>

                    <td><input type='checkbox' name='chkVal' value="${item.id}" /></td>

                    <td><input type="hidden" name='summarys' value="${item.summary}" />

                        <a href="./schdule.do?calendarId=${item.id}&title=${item.summary}">${item.summary}</a>

                    </td>

                    <td>${item.id}</td>

                </tr>

            </c:forEach>

        </table>

    </form>

    <input type="button" class='btn btn-sm btn-warning' value="캘린더 생성"

        onclick="calendarAddForm()" />

    <input type="button" class='btn btn-sm btn-warning' value="캘린더 수정"

        onclick="calendarModifyForm()" />

    <input type="button" class='btn btn-sm btn-warning' value="캘린더 삭제"

        onclick="calendarRemove()" />

    <!-- 캘린더 생성 modal -->

    <div class="modal fade" id="calendarAddForm" role="dialog">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <h4 class="modal-title">캘린더 생성</h4>

                </div>

                <div class="modal-body">

                    <!-- 캘린더 생성처리 form -->

                    <form action="./calendarAdd.do" method='post' id='frmCalendarAdd'>

                        <div class='form-group'>

                            <label>캘린더이름</label><input class='form-control' type="text"

                                name='summary' id='summary' />

                        </div>

                        <div class='modal-footer'>

                            <input type="button" class='btn btn-sm btn-warning' value="확인"

                                onclick="calendarAdd()" /> <input type="reset"

                                class='btn btn-sm btn-warning' value="초기화" /> <input

                                type='button' class='btn btn-sm btn-warning'

                                data-dismiss='modal' value="취소" />

                        </div>

                    </form>

                </div>

            </div>

        </div>

    </div>

    <!-- 캘린더 수정 modal -->

    <div class="modal fade" id="calendarModifyForm" role="dialog">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <h4 class="modal-title">캘린더 수정</h4>

                </div>

                <div class="modal-body">

                    <!-- 캘린더 생성처리 form -->

                    <form action="./calendarModify.do" method='post'

                        id='frmCalendarModify'>

                        <div class='form-group'>

                            <label>캘린더이름</label><input class='form-control' type="text"

                                name='summary' id='summaryModify' />

                        </div>

                        <input type="hidden" name="calendarId" id='calendarIdModify' />

                        <div class='modal-footer'>

                            <input type="button" class='btn btn-sm btn-warning' value="확인"

                                onclick="calendarModify()" /> <input type="reset"

                                class='btn btn-sm btn-warning' value="초기화" /> <input

                                type='button' class='btn btn-sm btn-warning'

                                data-dismiss='modal' value="취소" />

                        </div>

                    </form>

                </div>

            </div>

        </div>

    </div>

</body>

</html>

Colored by Color Scripter

cs

 

 

 

 

캘린더 일정화면

schdule.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>일정관리</title>

<script src="./js/jquery-3.1.1.min.js"></script>

<script src="./js/bootstrap.min.js"></script>

<link rel="stylesheet" href="./css/bootstrap.min.css">

<link rel="stylesheet" href="./css/bootstrap-theme.min.css">

<script type="text/javascript" src='./js/sweetalert.min.js?ver=1'></script>

<link rel="stylesheet" type="text/css"

    href='./css/sweetalert.css?ver=1.2'>

<script type="text/javascript" src="./js/stringBuffer.js"></script>

<script type="text/javascript" src="./js/calendar.js"></script>

<script type="text/javascript" src="./js/calendarSchdule.js"></script>

<style type="text/css">

thead {

    text-align: center;

}

thead td {

    width: 100px;

}

#tbody td {

    height: 150px;

}

#yearMonth {

    font: bold;

    font-size: 18px;

}

</style>

</head>

<body>

    <input type="hidden" id="chk" value="0" />

    <input type="hidden" id="calendarId" value="${calendarId}" />

    <table class="table table-bordered">

        <thead id='thead'>

            <tr>

                <td colspan="7">

                    <button type='button' class='btn btn-sm btn-warning'

                        id='moveFastPre' onclick="moveFastMonthPre()">«</button>

                     

                    <button type='button' class='btn btn-sm btn-warning' id='movePre'

                        onclick="moveMonthPre()"></button>    <span

                    id='yearMonth'></span>   

                    <button type='button' class='btn btn-sm btn-warning' id='moveNext'

                        onclick="moveMonthNext()"></button>  

                    <button type='button' class='btn btn-sm btn-warning'

                        id='moveFastNext' onclick="moveFastMonthNext()">»</button>

                    <div style="text-align: right;">

                        <span>${title}</span> <input class='btn btn-sm btn-info'

                            type="button" value="주" onclick='tabWeek()' /> <input

                            class='btn btn-sm btn-info' type="button" value="월"

                            onclick='tabMonth()' /> <input class='btn btn-sm btn-info'

                            type="button" value="목록" onclick='location.href="./coding.do"' />

                    </div>

                </td>

            </tr>

            <tr>

                <td><span class='week'></span></td>

                <td><span class='week'></span></td>

                <td><span class='week'></span></td>

                <td><span class='week'></span></td>

                <td><span class='week'></span></td>

                <td><span class='week'></span></td>

                <td><span class='week'></span></td>

            </tr>

        </thead>

        <tbody id='tbody'></tbody>

    </table>

    <!-- 일정 생성 modal -->

    <div class="modal fade" id="schduleForm" role="dialog">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <h4 class="modal-title">일정등록</h4>

                </div>

                <div class="modal-body">

                    <form class='form-margin40' role='form' action="#" method='post'

                        id='frmSchdule'>

                        <div class='form-group'>

                            <label>제목</label> <input type='text' class='form-control'

                                id='summary' name='summary'

                                placeholder="예: 오후 7시에 멕시코 음식점에서 저녁식사">

                        </div>

                        <div class='form-group'>

                            <label>시작시간</label> <input class='form-control' type="time"

                                id='startTime' name='startTime'>

                        </div>

                        <div class='form-group'>

                            <label>시작날짜</label> <input class='form-control startDate'

                                type="date" id='startDate' name='startDate' readonly="readonly">

                        </div>

                        <div class='form-group'>

                            <label>종료시간</label> <input class='form-control' type="time"

                                id='endTime' name='endTime'>

                        </div>

                        <div class='form-group'>

                            <label>종료날짜</label> <input class='form-control startDate'

                                type="date" id='endDate' name='endDate'>

                        </div>

                        <div class='form-group'>

                            <label>내용</label>

                            <textarea rows="7" class='form-control' id="description"

                                name='description'></textarea>

                        </div>

                        <div class='modal-footer'>

                            <input type="button" class='btn btn-sm btn-warning' value="확인"

                                onclick="calendarSchduleAdd()" /> <input type="reset"

                                class='btn btn-sm btn-warning' value="초기화" /> <input

                                type='button' class='btn btn-sm btn-warning'

                                data-dismiss='modal' value="취소" />

                        </div>

                    </form>

                </div>

            </div>

        </div>

    </div>

    <!-- 일정 수정 modal -->

    <div class="modal fade" id="schduleFormModify" role="dialog">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>

                    <h4 class="modal-title">일정수정</h4>

                </div>

                <div class="modal-body">

                    <form class='form-margin40' role='form' action="#" method='post'

                        id='frmSchduleModify'>

                        <div class='form-group'>

                            <label>제목</label> <input type='text' class='form-control'

                                id='modifySummary' name='summary'>

                        </div>

                        <div class='form-group'>

                            <label>내용</label>

                            <textarea rows="7" class='form-control' id="modifyDescription"

                                name='description'></textarea>

                        </div>

                        <input type="hidden" id="modifyEventId" name="eventId" /> <input

                            type="hidden" name="calendarId" value="${calendarId}" />

                        <div class='modal-footer'>

                            <input type="button" class='btn btn-sm btn-warning' value="확인"

                                onclick="modifyEvent()" /> <input type="reset"

                                class='btn btn-sm btn-warning' value="초기화" /> <input

                                type='button' class='btn btn-sm btn-warning'

                                data-dismiss='modal' value="취소" />

                        </div>

                    </form>

                </div>

            </div>

        </div>

    </div>

</body>

</html>

Colored by Color Scripter

cs

 

 

 

 

화면 라이브러리는 부트스트랩, jQuery, sweetalert을 씁니다.

 

 

기타 util javaScript

stringBuffer.js

1

2

3

4

5

6

7

8

9

10

// StringBuffer

var StringBuffer = function() {

    this.buffer = new Array();

};

StringBuffer.prototype.append = function(str) {

    this.buffer[this.buffer.length= str;

};

StringBuffer.prototype.toString = function() {

    return this.buffer.join("");

};

Colored by Color Scripter

cs

 

 

 

 

달력연산객체를 하나 만들어줍니다.

calendar.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

// 캘린더 객체

var calendar = {

    LEAF : [ 312931303130313130313031 ], //윤년

    PLAIN : [ 312831303130313130313031 ], //평년

    iscLeafCheck :

    //윤년 판단

    function(year) {

        var isc = false;

        if ((year % 4 == 0 && year % 100 != 0|| year % 400 == 0) { // 윤년이면

            isc = true;

        }

        return isc;

    },

    daysY :

    //년도에 따른 일수 누적

    function(year) {

        var daySum = 0;

        for (var i = 1; i < year; i++) {

            if (this.iscLeafCheck(i)) {

                daySum += 366;

            } else {

                daySum += 365;

            }

        }

        return daySum;

    },

    daysM :

    //년도누적 + 월 일수 누적

    function(year, month) {

        var daySum = this.daysY(year);

        for (var i = 1; i < month; i++) {

            daySum += this.PLAIN[i - 1];

        }

        if (month >= 2 && this.iscLeafCheck(year)) {

            daySum++;

        }

        return daySum;

    },

    daysD :

    //년도누적 + 월 누적 + 일수 누적

    function(year, month, day) {

        return this.daysM(year, month) + day;

    },

    lastDay :

    // 구하고자 하는 년월의 최대 일수

    function(year, month) {

        var last_day = 0;

        if (this.iscLeafCheck(year)) {

            last_day = this.LEAF[month - 1];

        } else {

            last_day = this.PLAIN[month - 1];

        }

        return last_day;

    },

    isBeforeDays :

    // 앞의 달에 년도 분기

    function(year, month) {

        var days = 0;

        if (month == 1) {

            days = this.lastDay(year - 112);

        } else {

            days = this.lastDay(year, month - 1);

        }

        return days;

    },

    make :

    // 해당달력을 배열로 반환

    function(year, month) {

        var dateOfWeek = (this.daysD(year, month, 1)) % 7;

        var beforeLastDay = this.isBeforeDays(year, month);

        var startLastDay = beforeLastDay - dateOfWeek + 1;

        var last_day = this.lastDay(year, month); // 구하고자 하는 년월의 최대 일수

        var lastWeekDays = (7 - (dateOfWeek + last_day) % 7) % 7;

        if (this.iscLeafCheck(year)) {

            startLastDay++;

            lastWeekDays++;

        }

        var dayArray = new Array();

        var cnt = 0;

        for (var i = startLastDay; i <= beforeLastDay; i++, cnt++) {

            dayArray[cnt] = i;

        }

        for (var i = 1; i <= last_day; i++, cnt++) {

            dayArray[cnt] = i;

        }

        for (var i = 1; i <= lastWeekDays; i++, cnt++) {

            dayArray[cnt] = i;

        }

        return dayArray;

    },

    makeOne :

    // 달력 한개만

    function(year, month){

        var last_day = this.lastDay(year, month); // 구하고자 하는 년월의 최대 일수

        var dayArray = new Array();

        var cnt = 0;

        for (var i = 1; i <= last_day; i++, cnt++) {

            dayArray[cnt] = i;

        }

        return dayArray;

    }

}

Colored by Color Scripter

cs

 

 

 

캘린더 리스트 화면을 핸들링할 javaScript

calendarList.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

// 캘린더 생성폼 호출

function calendarAddForm() {

    $('#calendarAddForm').modal();

}

// 캘린더 생성 처리

function calendarAdd() {

    var summary = $('#summary').val();

    if(summary.trim() == '' || summary.trim().length == 0) {

        swal('이름','입력해주세요');

        return false;

    }

    $('#frmCalendarAdd').submit();

}

//전체체크

function checkAllDel(bool) {

    var chkVal = document.getElementsByName("chkVal");

    for (var i = 0; i < chkVal.length; i++) {

        chkVal[i].checked = bool;

    }

}

//캘린더 삭제

function calendarRemove() {

    var chkVal = document.getElementsByName("chkVal");

    var n = 0;

    for (var i = 0; i < chkVal.length; i++) {

        if(chkVal[i].checked == true){

            n++;

        }

    }

    if(n>0){

        $('#frmCalendarRemove').submit();

    }else {

        swal("캘린더 삭제"'선택해주세요');

    }

}

// 캘린더 수정 호출

function calendarModifyForm() {

    var chkVal = document.getElementsByName("chkVal");

    var summarys = document.getElementsByName("summarys");

    var n = 0;

    var calendarId = '';

    var summary = '';

    for (var i = 0; i < chkVal.length; i++) {

        if(chkVal[i].checked == true){

            n++;

            calendarId = chkVal[i].value;

            summary = summarys[i].value;

        }

    }

    if(n==1) {

        $('#frmCalendarModify').find('#summaryModify').val(summary);

        $('#frmCalendarModify').find('#calendarIdModify').val(calendarId);

    }else if(n>1) {

        swal("캘린더 수정"'1개만 선택해주세요');

        return false;

    }else {

        swal("캘린더 수정"'선택해주세요');

        return false;

    }

    $('#calendarModifyForm').modal();

}

// 캘린더 수정 처리

function calendarModify() {

    $('#frmCalendarModify').submit();

}

 

Colored by Color Scripter

cs

 

 

 

 

 

일정을 핸들링할 js

calendarSchdule.js

var data = {} // List<Event>

var locationMonth = 0// 현재 달력위치

var locationYear = 0// 현재 년도위치

var locationWeek = 0// 현재 주차위치

// 날짜 테그를 만들어준다

function dayTagFormat(year, month, day) {

    var tag = new StringBuffer();

    tag.append("<td id="+year+month+day+">");

    tag.append("<a onclick='schduleAdd("+year+","+month+","+day+")'>"+numFormat(day)+"</a>");

    tag.append("</td>");

    return tag.toString();

}

//숫자 5 -> 05 변경

function numFormat(num) {

    var str = ''+num;

    if(num<10 && str.indexOf('0'== -1 || str.length == 1) {

        str = '0'+num;

    }

    return str;

}

// 시간을 리턴한다

function getTime(item) {

    return numFormat(item.getHours()) + ":" + numFormat(item.getMinutes());

}

// 일정추가 폼

function schduleAdd(year, month, day) {

    $('.startDate').val(year + "-" + numFormat(month) + "-" + numFormat(day));

    $('#summary').val('');

    $('#startTime').val('');

    $('#endTime').val('');

    $('#description').val('');

    $('#schduleForm').modal();

}

// 유효성 검사 일정 저장처리

function calendarSchduleAdd() {

    var summary = $('#summary').val();

    var startTime = $('#startTime').val().split(":");

    var endTime = $('#endTime').val().split(":");

    if(summary.trim() == '' || summary.trim().length == 0) {

        swal('제목','입력해주세요');

        return false;

    }else if($('#startTime').val() == '') {

        swal('시작시간','입력해주세요');

        return false;

    }else if($('#endTime').val() == '') {

        swal('종료시간','입력해주세요');

        return false;        

    }else if(new Date(0,0,0,endTime[0],endTime[1]).getTime() - new Date(0,0,0,startTime[0],startTime[1]).getTime() < 0) {

        swal('시간','종료시간이 시작시간보다 늦습니다');

        return false;

    }else if($('#endDate').val() == '') {

        swal('종료날짜','입력해주세요');

        return false;

    }else if(new Date($('#endDate').val()).getTime() - new Date($('#startDate').val()).getTime() < 0) {

        swal('날짜','종료일이 시작일보다 늦습니다');

        return false;

    }

    $("#schduleForm").modal('hide');

    swal('calendar''google토큰이 필요합니다.');

    $.ajax({

        url: './calendarEventAdd.do',

        type: 'post',

        async: false,

        data : $('#frmSchdule').serialize(),

        success: function(msg) {

            if(msg.isc) {

                swal('저장''성공하였습니다');

            }else {

                swal('저장''실패하였습니다');

            }

        }

    });

    calendarEventList();

    screenWriteMonth();

}

//달력의 해당 날짜의 요일을 구하기위해 현재위치 반환

function monthDayIndex(month, day) {

    for(var i=0; i<month.length; i++) {

        if(month[i]==day) {

            return i;

        }

    }

}

// 달력 이전으로 이동

function moveMonthPre() {

    locationMonth--;

    screenWriteMonth();

}

// 달력 다음으로 이동

function moveMonthNext() {

    locationMonth++;

    screenWriteMonth();

}

// 달력 이전 년도로 이동

function moveFastMonthPre() {

    locationYear--;

    screenWriteMonth();    

}

// 달력 다음 년도로 이동

function moveFastMonthNext() {

    locationYear++;

    screenWriteMonth();        

}

// 화면에 달력과 이벤트를 그려준다

function screenWriteMonth() {

    var date = new Date();

    var month = date.getMonth()+1+locationMonth;

    if(month == 0) {

        locationYear--;

        locationMonth = 12 - Math.abs(locationMonth);

        month = date.getMonth()+1+locationMonth;

    }else if(month == 13) {

        locationYear++;

        locationMonth = locationMonth - 12;

        month = date.getMonth()+1+locationMonth;

    }

    var months = [month-1, month, month+1];

    if(month == 1) {

        months = [12, month, month+1];

    }else if(month == 12) {

        months = [month-1, month, 1];

    }

    var year = date.getFullYear()+locationYear;

    var monthDay = calendar.make(year, months[1]);

    var tag = new StringBuffer();

    var startIndex = monthDayIndex(monthDay, 1);

    var lastIndex = monthDayIndex(calendar.makeOne(year, months[1]), calendar.lastDay(year, months[1])) + startIndex;

    for(var i=0; i<monthDay.length; i++) {

        if(i%7 == 0) {

            tag.append('<tr>');

        }

        if(i<startIndex) {

            if(months[0]==12) {

                tag.append(dayTagFormat(year-1, months[0], monthDay[i]));

            }else {

                tag.append(dayTagFormat(year, months[0], monthDay[i]));

            }

        }else if(i <= lastIndex) {

            tag.append(dayTagFormat(year, months[1], monthDay[i]));

        }else {

            if(months[2]==1) {

                tag.append(dayTagFormat(year+1, months[2], monthDay[i]));

            }else {

                tag.append(dayTagFormat(year, months[2], monthDay[i]));

            }

        }

        if(i%7 == 6) {

            tag.append('</tr>');

        }

    }

    $('#tbody').html(tag.toString());

    $('#yearMonth').text(year + "년 " + numFormat(months[1]) + "월");

    if(data.chk) {

        for(var i=0; i<data.cnt; i++) {

            var itemMonth = data.start[i].getMonth()+1;

            var itemYear = data.start[i].getFullYear();

            if((itemMonth == months[1|| itemMonth == months[0|| itemMonth == months[2])

                    && (itemYear == year || itemYear == year-1 || itemYear == year+1)) {

                $('#'+itemYear+itemMonth+data.start[i].getDate()).append(eventTagFormat(getTime(data.start[i]), data.title[i], data.eventId[i], data.description[i]));

            }

        }

    }

}

// 일정 태그를 만들어 준다

function eventTagFormat(time, title, eventId, description) {

    var tag = new StringBuffer();

    tag.append("<p>");

    tag.append('<a data-toggle="collapse" data-target="#collapseExample'+eventId+'" aria-expanded="false" aria-controls="collapseExample" onclick="collapse(\''+eventId+'\')">');

    tag.append(time+"  "+title);

    tag.append('</a>');

    tag.append('<div class="collapse" id="collapseExample'+eventId+'">');

    if(description == null) {

        tag.append('<div class="well">내용이 없습니다</div>');

    }else {

        tag.append('<div class="well">'+description+'</div>');

    }

    tag.append('<div style="text-align: right;"><input type="button" class="btn btn-sm btn-warning" value="수정" onclick="modifyEventModal(\''+title+'\',\''+eventId+'\',\''+description+'\')"/> ');

    tag.append('<input type="button" class="btn btn-sm btn-warning" value="삭제" onclick="removeEventOne(\''+eventId+'\')"/></div>');

    tag.append('</div>');

    tag.append("</p>");

    return tag.toString();

}

// collapse 처리

function collapse(eventId) {

    $('.collapse').not('#collapseExample'+eventId).each(function(){

        $(this).attr('class''collapse collapse');

    });    

}

// 일정수정 modal

function modifyEventModal(title, eventId, description) {

    $('#modifySummary').val(title);

    if(description != 'undefined') {

        $('#modifyDescription').val(description);

    }else {

        $('#modifyDescription').val('');

    }

    $('#modifyEventId').val(eventId);

    $('#schduleFormModify').modal();

}

// 일정수정 처리

function modifyEvent() {

    var summary = $('#modifySummary').val();

    if(summary.trim() == '' || summary.trim().length == 0) {

        swal('제목','입력해주세요');

        return false;    

    }

    $("#schduleFormModify").modal('hide');

    $.ajax({

        url: './calendarEventModify.do',

        type: 'post',

        async: false,

        data: $('#frmSchduleModify').serialize(),

        success: function(msg) {

            if(msg.isc) {

                swal('수정''성공하였습니다');

            }else {

                swal('수정''실패하였습니다');

            }

        }

    });

    calendarEventList();    

    if($('#chk').val() == '1') {

        screenWriteWeek();

    }else {

        screenWriteMonth();

    }

}

// 일정삭제

function removeEventOne(eventId) {

    $.ajax({

        url: './calendarEventRemoveOne.do',

        type: 'post',

        async: false,

        data : {

            "eventId" : eventId,

            "calendarId" : $('#calendarId').val()

        },

        success: function(msg) {

            if(msg.isc) {

                swal('삭제''성공하였습니다');

            }else {

                swal('삭제''실패하였습니다');

            }

        }

    });

    calendarEventList();

    if($('#chk').val() == '1') {

        screenWriteWeek();

    }else {

        screenWriteMonth();

    }

}

// ajax로 이벤트 데이터를 받는다

function calendarEventList() {

    $.ajax({

        url: './calendarEventList.do',

        type: 'post',

        data: {

            "calendarId" : $('#calendarId').val()

        },

        async: false,

        success: function(lists) {

            if(lists.length != 0) {

                data.chk = true;

                data.cnt = lists.length;

                data.title = new Array();

                data.description = new Array();

                data.start = new Array();

                data.end = new Array();

                data.eventId = new Array();

                $.each(lists, function(i, item){

                    data.title[i] = item.summary;

                    data.description[i] = item.description;

                    data.start[i] = new Date(item.start.dateTime.value);

                    data.end[i] = new Date(item.end.dateTime.value);

                    data.eventId[i] = item.id;

                });

            }else {

                data.chk = false;

            }

        }

    });

}

// 주단위로 화면에 그린다

function screenWriteWeek() {

    var date = new Date();

    var month = date.getMonth()+1+locationMonth;

    if(month == 0) {

        locationYear--;

        locationMonth = 12 - Math.abs(locationMonth);

        month = date.getMonth()+1+locationMonth;

    }else if(month == 13) {

        locationYear++;

        locationMonth = locationMonth - 12;

        month = date.getMonth()+1+locationMonth;

    }

    var year = date.getFullYear()+locationYear;

    if(locationWeek < 0) {

        locationMonth--;

        month = date.getMonth()+1+locationMonth;

        if(month == 0) {

            locationYear--;

            locationMonth = 12 - Math.abs(locationMonth);

            month = date.getMonth()+1+locationMonth;

            year = date.getFullYear()+locationYear;

        }

        if(new Date(year, month-1, calendar.lastDay(year, month)).getDay() == 6) {

            locationWeek = calendar.make(year, month).length/7-1;

        }else {

            locationWeek = calendar.make(year, month).length/7-2;

        }

    }else if(locationWeek > calendar.make(year, month).length/7-2) {

        locationMonth++;

        month = date.getMonth()+1+locationMonth;

        if(month == 13) {

            locationYear++;

            locationMonth = locationMonth - 12;

            month = date.getMonth()+1+locationMonth;

            year = date.getFullYear()+locationYear;

        }        

        locationWeek = 0;

    }

    var months = [month-1, month, month+1];

    if(month == 1) {

        months = [12, month, month+1];

    }else if(month == 12) {

        months = [month-1, month, 1];

    }

    var monthDay = calendar.make(year, months[1]);

    var start = 0+locationWeek*7;

    var last = 6+locationWeek*7;

    var startIndex = monthDayIndex(monthDay, 1);

    var lastIndex = monthDayIndex(calendar.makeOne(year, months[1]), calendar.lastDay(year, months[1])) + startIndex;

    for(var i=start; i<=last; i++) {

        if(i<startIndex) {

            $('.week').eq(i%7).text('('+numFormat(months[0])+'.'+numFormat(monthDay[i])+')');

        }else if(i <= lastIndex) {

            $('.week').eq(i%7).text('('+numFormat(months[1])+'.'+numFormat(monthDay[i])+')');

        }else {

            $('.week').eq(i%7).text('('+numFormat(months[2])+'.'+numFormat(monthDay[i])+')');

        }

    }

    if(locationWeek != 0) {

        $('#yearMonth').text(year + "년 " + numFormat(months[1]) + "월 " + numFormat(monthDay[start]) + "일 ~ " + numFormat(months[1]) + "월 " + numFormat(monthDay[last]) + "일");

    }else {

        if(months[1== 1) {

            $('#yearMonth').text((year-1+ "년 " + numFormat(months[0]) + "월 " + numFormat(monthDay[start]) + "일 ~ " + year + "년 " + numFormat(months[1]) + "월 " + numFormat(monthDay[last]) + "일");

        }else {

            $('#yearMonth').text(year + "년 " + numFormat(months[0]) + "월 " + numFormat(monthDay[start]) + "일 ~ " + numFormat(months[1]) + "월 " + numFormat(monthDay[last]) + "일");

        }

    }

    var tag = new StringBuffer();

    for(var i=0, j=0, k=0; i<384; i++) {

        if(i%8 == 0) {

            tag.append('<tr style="text-align: center;">');

            j++;

        }

        if(j%2 == 1) {

            if(i%8 == 0) {

                tag.append('<td rowspan="2" style="height: 5px;></td>');

                tag.append('<td style="height: 5px; border-bottom: 1px dotted orange;">'+numFormat(k++)+':00</td>');

            }else {

                tag.append('<td class="'+j+'" style="height: 5px; border-bottom: 1px dotted orange;"></td>');

            }

        }else {

            if(i%8 < 7) {

                tag.append('<td class="'+j+'" style="height: 5px; border-top: 1px dotted orange;"></td>');

            }

        }

        if(i%8 == 7) {

            tag.append('</tr>');

        }

    }

    $('#tbody').html(tag.toString());

    // 캘린더 날짜정보 처리 고민필요 지금은 귀찮으니 대충 작성

    if(data.chk) {

        for(var i=start; i<=last; i++) {

            for(var j=0; j<data.cnt; j++) {

                if(i<startIndex) {

                    weekStartTimeAppend(i, j, monthDay, months, year, -1);

                    weekEndTimeAppend(i, j, monthDay, months, year, -1);

                }else if(i <= lastIndex) {

                    if(monthDay[i] == data.start[j].getDate() && months[1== data.start[j].getMonth()+1 && year == data.start[j].getFullYear()) {

                        if(data.start[j].getMinutes() < 30) {

                            $('.'+(data.start[j].getHours()*2+1)).eq(i%7).html(eventTagFormat(getTime(data.start[j]), data.title[j], data.eventId[j], data.description[j]));

                        }else {

                            $('.'+(data.start[j].getHours()*2+2)).eq(i%7).html(eventTagFormat(getTime(data.start[j]), data.title[j], data.eventId[j], data.description[j]));

                        }

                    }

                    if(data.start[j].getHours() != data.end[j].getHours() || (data.start[j].getMinutes() < 30 && data.end[j].getMinutes() >= 30)) {

                        if(monthDay[i] == data.end[j].getDate() && months[1== data.end[j].getMonth()+1 && year == data.end[j].getFullYear()) {

                            if(data.end[j].getMinutes() < 30) {

                                $('.'+(data.end[j].getHours()*2+1)).eq(i%7).html(eventTagFormatEnd(getTime(data.end[j]), data.title[j], data.eventId[j], data.description[j]));

                            }else {

                                $('.'+(data.end[j].getHours()*2+2)).eq(i%7).html(eventTagFormatEnd(getTime(data.end[j]), data.title[j], data.eventId[j], data.description[j]));

                            }

                        }                    

                    }

                }else {

                    weekStartTimeAppend(i, j, monthDay, months, year, 1);

                    weekEndTimeAppend(i, j, monthDay, months, year, 1);

                }

            }

        }

    }

}

// startTime Tag append

function weekStartTimeAppend(i, j, monthDay, months, year, num) {

    if(monthDay[i] == data.start[j].getDate() && months[0== data.start[j].getMonth()+1) {

        if(months[0== 12 && year+num == data.start[j].getFullYear()) {

            if(data.start[j].getMinutes() < 30) {

                $('.'+(data.start[j].getHours()*2+1)).eq(i%7).html(eventTagFormat(getTime(data.start[j]), data.title[j], data.eventId[j], data.description[j]));

            }else {

                $('.'+(data.start[j].getHours()*2+2)).eq(i%7).html(eventTagFormat(getTime(data.start[j]), data.title[j], data.eventId[j], data.description[j]));

            }

        }else if(year == data.start[j].getFullYear()) {

            if(data.start[j].getMinutes() < 30) {

                $('.'+(data.start[j].getHours()*2+1)).eq(i%7).html(eventTagFormat(getTime(data.start[j]), data.title[j], data.eventId[j], data.description[j]));

            }else {

                $('.'+(data.start[j].getHours()*2+2)).eq(i%7).html(eventTagFormat(getTime(data.start[j]), data.title[j], data.eventId[j], data.description[j]));

            }                        

        }

    }    

}

// endTime Tag append

function weekEndTimeAppend(i, j, monthDay, months, year, num) {

    if(data.start[j].getHours() != data.end[j].getHours() || (data.start[j].getMinutes() < 30 && data.end[j].getMinutes() >= 30)) {

        if(monthDay[i] == data.end[j].getDate() && months[2== data.end[j].getMonth()+1) {

            if(months[2== 1 && year+num == data.end[j].getFullYear()) {

                if(data.end[j].getMinutes() < 30) {

                    $('.'+(data.end[j].getHours()*2+1)).eq(i%7).html(eventTagFormatEnd(getTime(data.end[j]), data.title[j], data.eventId[j], data.description[j]));

                }else {

                    $('.'+(data.end[j].getHours()*2+2)).eq(i%7).html(eventTagFormatEnd(getTime(data.end[j]), data.title[j], data.eventId[j], data.description[j]));

                }

            }else if(year == data.end[j].getFullYear()) {

                if(data.end[j].getMinutes() < 30) {

                    $('.'+(data.end[j].getHours()*2+1)).eq(i%7).html(eventTagFormatEnd(getTime(data.end[j]), data.title[j], data.eventId[j], data.description[j]));

                }else {

                    $('.'+(data.end[j].getHours()*2+2)).eq(i%7).html(eventTagFormatEnd(getTime(data.end[j]), data.title[j], data.eventId[j], data.description[j]));

                }

            }

        }                    

    }    

}

//일정 종료 태그를 만들어 준다

function eventTagFormatEnd(time, title, eventId, description) {

    var tag = new StringBuffer();

    tag.append("<p>");

    tag.append('<a style="color: red;" data-toggle="collapse" data-target="#collapseExample'+eventId+'" aria-expanded="false" aria-controls="collapseExample" onclick="collapse(\''+eventId+'\')">');

    tag.append(time+"  "+title);

    tag.append('</a>');

    tag.append("</p>");

    return tag.toString();

}

// 이전 주 이동

function moveWeekPre() {

    locationWeek--;

    screenWriteWeek();

}

// 다음 주 이동

function moveWeekNext() {

    locationWeek++;

    screenWriteWeek();

}

//이전 달 주 이동

function moveFastWeekPre() {

    locationMonth--;

    screenWriteWeek();    

}

// 다음 달 주 이동

function moveFastWeekNext() {

    locationMonth++;

    screenWriteWeek();    

}

// 주단위로 바꾼다

function tabWeek() {

    $('#movePre').attr('onclick''moveWeekPre()');

    $('#moveNext').attr('onclick''moveWeekNext()');

    $('#moveFastPre').attr('onclick''moveFastWeekPre()');

    $('#moveFastNext').attr('onclick''moveFastWeekNext()');

    if($('#chk').val() != '1') {

        $('#thead tr:eq(0) td:eq(0)').attr('colspan''8');

        $('#thead tr:eq(1)').prepend('<td>시간</td>');

        $('#chk').val('1');

    }

    screenWriteWeek();

}

// 월단위로 바꾼다

function tabMonth() {

    $('#movePre').attr('onclick''moveMonthPre()');

    $('#moveNext').attr('onclick''moveMonthNext()');

    $('#moveFastPre').attr('onclick''moveFastMonthPre()');

    $('#moveFastNext').attr('onclick''moveFastMonthNext()');

    if($('#chk').val() != '0') {

        $('#thead tr:eq(0) td:eq(0)').attr('colspan''7');

        $('#thead tr:eq(1) td:eq(0)').remove();

        $('.week').text('');

        $('#chk').val('0');

    }

    screenWriteMonth();

}

$(document).ready(function(){

    calendarEventList();

    screenWriteMonth();

});

Colored by Color Scripter

cs

 

 

 

 

4. 실행화면

캘린더 리스트 화면

 

 

캘린더 생성시 modal처리 화면

 

 

 

캘린더 수정시 modal처리 화면

 

 

 

캘린더 삭제시 sweetalert처리 화면

 

 

일정 월 처리화면

 

 

일정 주 처리화면

 

 

일정 상세보기 화면

 

 

일정등록 modal처리 화면

 

 

일정 수정처리 modal처리 화면

 

 

일정 삭제시 sweetalert처리 화면

 

 

일정 주 상세보기 화면

 

 

 

이상으로 google calendar API 구현이였는데요

저는 java로 구현했기때문에

만약 배포시 권한동의화면을 띄워야하는데 전혀 써먹지 못합니다.(java코드에서 브라우저를 실행시키기때문에 ㅋㅋ)

 

소감으로는 API를 쓰는데 생각보다 많은 노력이 필요하고 그 시간에 DB구축하고도 남아돌기 때문에 추천하지 않습니다.

만약 만든다면 배포할때를 위해 javaScript로 구현하시기 바랍니다.

참고 API문서

연동 : https://developers.google.com/google-apps/calendar/quickstart/js

CRUD 코드 : https://developers.google.com/google-apps/calendar/v3/reference/events/get

Data속성 : https://developers.google.com/google-apps/calendar/v3/reference/events

 

 

 GoogleCalendarAPI.zip 

 

 

출처 : https://handcoding.tistory.com/20

'Programing' 카테고리의 다른 글

그누보드 버전 확인 How to gnuboard CMS version check  (0) 2019.09.18
php 프로그래밍 게시판 사진 보이게 하는 소스코드  (0) 2016.03.27
알고리즘의 종류  (0) 2015.10.18
br 태그  (0) 2015.10.18
배치파일 명령어  (0) 2014.03.13

<td><input type="image" src="data/<?=$row[filename]?>"></td> 



'Programing' 카테고리의 다른 글

그누보드 버전 확인 How to gnuboard CMS version check  (0) 2019.09.18
구글 캘린더 API 자바 연동  (14) 2019.04.12
알고리즘의 종류  (0) 2015.10.18
br 태그  (0) 2015.10.18
배치파일 명령어  (0) 2014.03.13

프로세스들이 작업을 수행하기 위해서는 프로세스 스케줄러로 부터 CPU를 할당 받아야 한다. 이런 작업은 운영체제에 의해 구현되고 CPU를 언제, 어떤 프로세스에게 배당되는지 결정하는 작업을 프로세스 스케줄링 이라 한다. 프로세스 스케줄링은 방법에 따라서 선점 스케줄링과 비선점 스케줄링으로 나눌수 있다. 다음은 프로세스 스케줄링의 종류이다. 


각각 스케줄링 알고리즘의 특징을 알기 전에 스케줄링의 목절을 알아보면 다음과 같은 목적을 고려해서 스케줄링 되어야 한다. 

●  공정한 스케줄링 : 스케줄링할 때 모든 프로세스들은 공평하게 취급되어야 하며 어느 프로세스도 무한정 대기 하는일이 없어야 한다. 

  처리량 극대화 : 스케줄링할 때 프로세스들의 가능한 한 단위 시간당 처리량을 최대화 한다. 

  응답 시간 최소화 : 대화식 사용자에게는 가능한 최대한 응답 시간을 빠르게 한다. 

  반환 시간 예측 가능 : 시스템의 부하에 관계없이 일정한 작업은 같은 시간 내에 같은 비용으로 실행, 완료되어 반환시기를
 예측 
가능해야 한다. 
  균형 있는 자원 사용 : 스케줄링 시 시스템 내의 자원들이 유휴 상태로 놓이지 않게 골고루 사용하게 하고, 유휴 상태의 자원을 사용하는 프로세스에게 더 나은 서비스를 제공 한다. 
  응답 시간과 자원 이용간의 조화 : 빠른 응답 시간과 자원의 활용도를 고려하여 응용에 따라 적절하게 조화시킨다.

  우선 순위제를 실시 : 프로세스들에게 우선순위를 부여하여 우선순위가 높을수록 먼저 실행되도록 한다. 

  페이지 부재를 적게 발생시키는 프로세스에게 더 좋은 서비스를 해준다. 

■ 선점 스케줄링  

선점은 한 프로세스가 CPU를 점유하고 있을 때 다른 프로세스가 현재 프로세스를 중지시키고 자신이 CPU를 차지 할 수 있는 방식이다. 우선순위가 높은 프로세스가 먼저 수행 될 때 유리하고, 빠른 응답시간을 요구하는 시분할 시스템에 유용하다. 하지만
선점 때문에 많은 오버헤드를 초래한다. 

□ Round robin 스케줄링

라운드 로빈 스케줄링은 FCFS (First come First service) 방식으로 각 프로세스는 같은 크기의 타임 슬라이스를 할당 받는다. 
만약 프로세스가 할당 받은 시간동안 작업을 완료하지 못하면 다음 프로세스로 넘어가고 실행 중이던 프로세스는 준비 완료 리스트의 가장 뒤로 보내진다. 


라운드 로빈 방식의 특징은 다음과 같다. 

● 시분할 방식의 시스템에서 효과적이다. 
● 할당 시간의 크기는 시스템의 효과적인 동작에 절대적인 영향을 미친다.
● 할당 시간이 크면 FCFS 방식과 같다. 
● 할당 시간이 작으면 자주 문맥교환이 발생하므로 오버헤드가 커진다. 

□ SRT 스케줄링

준비 큐에 있는 프로세스들 중에서 가장 짧은 시간이 소요된다고 판단되는 프로세스를 먼저 수행 시킨다. 
SJF 방식에 선점 방식을 도입한 방식이라고 생각하면 편하다. 


현재 프로세스가 CPU를 할당 받아 사용중이더라도 남은 처리 시간이 더 짧다고 판단되는 프로세스가 준비 큐에 생기면 언제라도 실행 중인 프로세스는 선점될 수 있다. 또한 수행 중인 각각의 작업들의 실행 시간을 추적 보유하고 있어야 한다. 

□ MLQ 스케줄링 

작업들을 여러 종류의 그룹으로 나누어 여러개의 큐를 이용하는 스케줄링 기법이다. 그룹화된 작업들은 각각의 준비 큐에 넣어서 각 큐의 독자적인 스케줄링 알고리즘에 따라서 CPU를 할당 받는다. 

● 다단계 큐 알고리즘은 준비 상태 큐를 여러 종류로 분할해 둔다.
● 각 큐는 자신만의 독자적인 스케줄링을 가지고 있다. 
● 각각의 서로 다른 작업들이 다른 묶음으로 분류될 수 있을 때 사용되는 알고리즘이다. 
● 일괄 처리 작업이 실행 중일지라도 상위 단계 큐에 작업이 들어오면 일괄 처리 작업은 선점 당한다.
● 한 큐에서 다른 큐로의 작업 이동은 불가능 하다.

□ MFQ 스케줄링

새로운 프로세스가 들어오면 높은 우선순위를 할당해 주어 단계1에서 즉시 수행해 주고 점차 낮은 우선순위를 부여하며 단계 n쯤 되는 나중에는 그 작업이 완료될 때까지 라운드 로빈으로 순환된다. 하나의 준비 큐를 통해 여러 피드백 큐를 걸치며 작업을 수행하는 방법이다. 이 방법은 CPU에 대한 요구량에 따라 프로세스들을 분류하는대 이상적인 방법이다.

● 짧은 작업에 유리하다.
● 입출력 장치를 효과적으로 이용하려고 입출력 위주의 작업들에 우선권을 준다.
● 가능한 빨리 작업의 특성을 알고 그것에 맞게 해당 작업을 스케줄링 한다.
● 프로세스가 보다 하위 단계의 큐로 옮겨갈수록 주어진 할당 시간은 점차 크게 설정된다. 

■ 비선점 스케줄링

비선점은 한 프로세스가 CPU를 할당받으면 다른 프로세스는 할당 받은 프로세스가 작업을 종료할때 까지 CPU를 사용 불가능 한 방식이다. 모든 프로세스의 요구를 공정히 처리할 수 있다. 응답시간이 예측 가능하다. 단 짧은 작업이 긴 작업을 기다리는 경우가 발생 할 수 있다. 

□ 우선순위 스케줄링

각 프로세스에게 우선순위를 부여하여 순위가 높은 순서대로 처리하는 방법이다. 우선순위는 보통 프로세스의 특성과 종류에 따라서 각각 다르게 부여될 수 있다. 우선순위 스케줄링은 정적 우선 방법과 동적 우선 방법이 있다. 

정적 우선순위 방법 : 실행이 쉽고 상대적으로 오버 헤드는 적지만 주위 여건의 변화에 적응하지 못하고 우선순위를 바꾸지 않는다.

동적 우선순위 방법 : 상항 변화에 잘 적응한다. 구현하기가 복잡하고 오버헤드가 많으나 시스템이 응답도를 증가시켜 주므로 효율성이 있다. 

□ 기한부 스케줄링 

기한부 스케줄링은 작업들이 명시된 시간이나 기한 내에 완료되게 계획되고 작업들의 결과가 시간내에 구해지면 유용하고 마감 시간이 지난 후에 결과가 구해지면 쓸모가 없게 된다. 

● 사용자는 사전에 작업이 요구하는 정확한 자원을 제시해야만 한다. 만약 기한 시간 내에 일을 끝내지 못하면 막대한 손해를 초래한다.
● 시스템은 다른 사용자들에 대한 서비스를 감소시키지 않으면서 기한부 작업을 실행할 수 있어야 한다.
● 시스템은 기한까지 일을 끝내기위해 자원 안배를 주의 깊게 계획해야 한다.
● 만약 많은 기한부 작업들이 동시에 실행된다면 스케줄링이 너무 복잡하게 된다.
● 기한부 스케줄링으로 요구되는 집중적인 자원 운영은 많은 오버헤드가 뒤따른다. 

□ FCFS(FIFO) 스케줄링

가장 단순한 방식으로 프로세스들이 대기 큐에 도착한 순서에 따라 CPU를 할당 받는 방식이다. 


이방식은 일단 프로세스가 CPU를 차지하면 완료될 때까지 수행한다. 다른 방식에 비하여 작업 완료 시간을 예측하기가 쉽다. 선점이 불가능하기때문에 수행시간이 긴 프로세스가 할당받은 상태라면 수행시간이 짧은 프로그램이 대기할 경우가 생기고 중요한 작업이 대기하는 상황이 발생할수 있다. 또한 대화식 사용자들에게는 부적합하다.

□ SJF 스케줄링

SJF 방식 (SJN)은 준비큐에서 기다리는 작업중 수행시간이 가장 짧다고 판단되는 것을 가장 먼저 수행하는 스케줄링 방법이다. 


FCFS 보다 평균 대기 시간을 감소시키지만 큰 작업일수록 FCFS에 비해 예측이 어렵다. 긴 작업보다 짧은 작업일 수록 오버헤드 면에서 볼 때 유리하다. 하지만 이 방법은 수행할 작업이 얼마나 긴 것인지를 정확히 판단 해서 수행해야 하는대 수행시간을 정확히 얻는다는 것이 어렵다. 

□ HRN 스케줄링

이 방법은 SJF의 약점 특히 긴 작업과 짧은 작업 간의 불평등을 어느 정도 보안한 방법이다. 



이 방법도 비선점 스케줄링 방식이므로 한 작업이 CPU를 차지하면 그 작업은 완성될 때까지 실행한다. 
우선순위는  (대기 시간 + 버스트 시간) / 버스트 시간 으로 정한다. 

각각 스케줄링 방법을 표로 정리해보면 다음과 같다. 


'Programing' 카테고리의 다른 글

구글 캘린더 API 자바 연동  (14) 2019.04.12
php 프로그래밍 게시판 사진 보이게 하는 소스코드  (0) 2016.03.27
br 태그  (0) 2015.10.18
배치파일 명령어  (0) 2014.03.13
bat(배치)파일 문법  (0) 2014.03.13

<br> 태그는 line break 의 약자 입니다. 줄바꿈 할 때 쓰죠


<p> 는 문단을 나눌때 쓴답니다.



'Programing' 카테고리의 다른 글

구글 캘린더 API 자바 연동  (14) 2019.04.12
php 프로그래밍 게시판 사진 보이게 하는 소스코드  (0) 2016.03.27
알고리즘의 종류  (0) 2015.10.18
배치파일 명령어  (0) 2014.03.13
bat(배치)파일 문법  (0) 2014.03.13

배치파일 명령어



배치 파일 연산자 쉘 스크립트 동의어
% $ 명령어줄 매개변수 접두사
/ - 명령어 옵션 플래그
\ / 디렉토리 패스 구분자
== = (같음) 문자열 비교 테스트
!==! != (다름) 문자열 비교 테스트
| | 파이프
@ set +v 현재 명령어를 에코하지 말 것
* * 파일명 "와일드 카드"
> > 파일 재지향(덮어 쓰기)
>> >> 파일 재지향(덧붙여 쓰기)
< < 표준입력 재지향
%VAR% $VAR 환경 변수
REM # 주석
NOT ! 뒤에 나오는 테스트 부정
NUL /dev/null 명령어 출력을 없애기 위한 "블랙홀"
ECHO echo 에코 (Bash 에는 옵션이 많이 있음)
ECHO. echo 빈 줄 에코
ECHO OFF set +v 다음에 나오는 명령어를 에코하지 말 것
FOR %%VAR IN (LIST) DO for var in [list]; do "for" 루프
:LABEL 없음 (필요치 않음) 라벨
GOTO 없음 (대신 함수를 씀) 스크립트의 다른 곳으로 건너 뜀
PAUSE sleep 일정 간격을 두고 잠시 대기
CHOICE case 나 select 메뉴 선택
IF if if-test
IF EXIST FILENAME if [ -e filename ] 파일이 존재하는지 확인
IF !%N==! if [ -z "$N" ] 변경가능한 매개변수인 "N"이 없다면
CALL source 나 . (도트 연산자) 다른 스크립트를 "포함"
COMMAND /C source 나 . (도트 연산자) 다른 스크립트를 "포함"(CALL과 동일)
SET export 환경 변수를 세트
SHIFT shift 명령어줄 변수 목록을 왼쪽으로 이동(shift)
SGN -lt or -gt (정수) 부호(sign)
ERRORLEVEL $? 종료 상태
CON stdin "콘솔"(표준입력)
PRN /dev/lp0 (일반적인) 프린터 디바이스
LP1 /dev/lp0 첫번째 프린터 디바이스
COM1 /dev/ttyS0 첫번째 시리얼 포트



'Programing' 카테고리의 다른 글

구글 캘린더 API 자바 연동  (14) 2019.04.12
php 프로그래밍 게시판 사진 보이게 하는 소스코드  (0) 2016.03.27
알고리즘의 종류  (0) 2015.10.18
br 태그  (0) 2015.10.18
bat(배치)파일 문법  (0) 2014.03.13

출처: http://blog.naver.com/mokomoji

bat(배치)파일 문법
일괄처리(Batch) 파일 #1

1.배치파일(Batch File, 일괄처리용 화일)

1.1. 배치파일?
Batch(배치)는 '한 묶음','한벌'의 의미하며, 배치파일은 여러 가지 명령어를 한 파일에 모아 작업하는 파일, 즉 하나의 일을 처리하기 위해 여러번 내리는 명령어를 한 번만에 처리할 수 있도록 만들어 놓은 실행파일이다.

  ① 확장자 이름은 반드시 'BAT'이어야 한다.
  ② 파일명은 도스의 내부명령어 이름을 피하라.
  ③ COM, EXE 파일의 이름을 피하라.

  ④ 명령어 이름이 서로 같아 충돌할 때, DOS는 도스키-->내부명령-->외부명령( *.COM-->*.EXE)-->*.BAT) 순으로 실행한다.

    다만 '파일명.BAT'라고 확장자 이름까지 써서 명령을 내리면 이런 문제는 해결된다.

  ⑤ BAT파일은 표준 ASCII 문장(Text) 파일이어야 한다.


1.2. BAT파일 만드는 방법.
일반 도스 명령어와 배치전용 명령어를 사용하여 다음의 3가지 방식을 사용하여 아스키 문장파일 형식으로 만든다.

  ① COPY명령사용 ....  C:\>COPY CON XXXX.BAT
  ② 문서편집기 이용 ... 'EDIT', 'SAN'
  ③ 문서 작성기(WordProcessor) ..  아래한글,훈민정음 등



작성 예①)  C:\>COPY CON SAMPLE.BAT  <엔터>
─────       CLS
                DIR A:
                V3 C:
                ^Z
                1 File(s) Copied

<설명1> COPY 명령을 사용하여 텍스트 파일 만드는 방법을 이용한다.
CON은 장치 파일명으로 여기서는 키보드를 지칭한다.키보드로 입력한 문자를 SAMPLE.BAT라는 파일명으로 복사.출력하라는 뜻이다.

입력한 배치 내용을 보면
  화면을 깨끗이지우고(CLS), A드라이브의 파일목록을 보이라, 그리고 C 디스크에 바이러스 감염 여부를 점검.치료하라는 명령이다.

줄을 바꿀 때는 항상 엔터하면 된다. 끝낼 때는 언제나 Ctrl+Z 또는 F6키를 누르고 엔터하면 1개 파일이 복사되었다는 메시지가 나오면서 C루트에 SAMPLE.BAT란 파일이 1개 생긴다.

<실행> C:\>SAMPLE <엔터>하면 배치파일 내용 순서데로 명령을 실행한다.

-----

작성 예②)  C:\>EDIT <엔터>

     도스 편집기 화면이 뜬다.  이때  ESC키를 한번 눌러 메시지 상자를 제거하고 깨끗한 화면에다 첫째 줄부터 입력하되, 줄을 바꿀 때는 엔터한다.

               CLS
               DIR A:
               V3 C:

끝내려고 저장글쇠(@F,S)를 누르면 파일이름을 써넣으라고 상자자 나온다. SAMPLE.BAT라고 입력하고 <엔터>하여 저장한 후, 에디트를 끝(@F, X)낸다.그러면 C루트 디렉토리에 SAMPLE.BAT 라는 배치파일이 생긴다.

<실행> C:\>SAMPLE <엔터>하면    C루트에 있는 SAMPLE.BAT 파일이 실행된다.


******* 배치파일 내용에 파일스펙 경로명을 쓸 때 주의점.****

ⓐ 배치파일 내용 중에
  C:\GAME\SUPER\SUPER.EXE 라고 해놓으면

현재 도스 작업방을 바꾸지 말고 C:\GAME\SUPER\ 방에있는 SUPER.EXE를 실행하라는 뜻이기 때문에 경우에 따라서는 실행이 되지 않는다.

ⓑ 배치 내용을 아래와 같이 하면 틀림없이 실행하게 된다.
  C:
  CD\GAME\SUPER
  SUPER

현재 도스작업방이 먼저 C드라이브로 바뀌고,절대경로명 CD\GAME\SUPER
디렉토리로 이동한 후에 SUPER.EXE 파일을 실행한다            ******


1.3.배치파일 명령어들

① 일반적인 도스명령를 그대로 사용한다.

  CLS  COPY  DEL  DIR  DATE  TIME   PAYH   PROMPT  CHKDSK 등등.

② 배치에만 사용하는 전용 명령가 있다.
  ECHO   REM   PAUSE  CALL   GOTO    CHOICE   IF   FOR   SHIFT
(메아리)(설명) (쉼)  (부름) (가기)   (선택) (조건)(순환) (옮김)


ⓐ REM
  [베치파일 속에 달고 싶은 설명.주석]....설명이 화면에 나옴.

ⓑ PAUSE
  배치파일 실행중 일시 멈추게함.
  화면에 'Press any key to continue...'
          (계속하려면 아무키나 누르세요)

  배치실행을 중단하려면 Ctrl+C키를 누른다. 그러면 화면에
           'Terminate batch job (Y/N)?'
          (배치작업을 끝내겠읍니까?)  Yes / No

ⓒ ECHO 명령
형식> ECHO 문자열
      에코명령 다음에 오는 문자열을 화면에 나타낸다.

    ECHO ON
      이후부터 '명령어'라인을 화면에 보인다.(도스 초기값)

    ECHO OFF
      이후 실행되는 명령어 라인을 화면에 나타내지 않는다.
      화면이 깨끗하고, 화면출력속도.가독성 증가한다.
      'ECHO OFF'라는 그 자체까지 보이지 않게 하려면 @ 을 앞에 쓴
      다.( @ECHO OFF )

    ECHO
      현재 ECHO ON/OFF 상태를 확인한다.


<예> C:\>COPY CON EDIT2.bat
  ECHO OFF
                 이후에 실행되는 명령어는 화면에 나타나지 않는다.
                 화면에 ECHO OFF 자체는 나타난다.

  TB
                 태백한글을 메모리에 상주 띄우기.
                 각자 지원되는 다른 한글코드(HANME,HT,DKBY 등)를
                 실행하면 된다.
                 한글도스인 때는 HBIOS.COM을 실행한다.

  PAUSE
               잠시 중지. 엔터하면 다시 진행한다.

  CLS
              화면청소

  ECHO 'This is Hangul Edit.'
                            '문자열'을 화면에 출력한다.

  PAUSE
  REM NOW,DOS EDIT IS HANGUL EDITOR.

                REM 다음에 오는 설명은 화면에 나오지 않는다. 다만
                사용자가 배치파일 내용을 볼 때 참고할 내용이다.

  ECHO ON
              이후에 실행되는 명령어는 화면에 나타남

  EDIT
              도스 에디터 화면이 나오면 한글로 문서를 작성.저장한
              후 끝낸다.

  @ECHO OFF

             이후에 실행되는 명령어는 화면에 나타나지 않는다.
             ECHO OFF자체도 나타나지않음.

  TB/U
            태백한글 메모리서 제거한다.

  CLS
  ^Z
           CTRL+Z 또는 F6를 누른다.

  1 File(s) Copied

  실습을 위하여 일부러 여러가지 명령 종류를 써 보았으며,한글로 설 명을 하느라고 줄이 떨어졌으나 각자 실습할 때는 영문글자 부분만 쓰고 엔터하여 줄울 바꾸고 줄간격을 붙여가며 쓴다.

<실행 예>  C:\>EDIT2 <엔터> 하면

위의 내용을 순서데로 실행하고 도스 문서편집기가 화면에 나타난다. 문서작성기를 끝내면 한글프로그램을 메모리에서 제거하고 도스로 나온다.  (계속)


제14장 배치파일 #2 (계속)

1.4 배치파일 전용 명령에서
? 판단과 분기에 관한 명령  ....  CALL, CHOICE, IF, GOTO

앞에서 공부한 배치파일의 경우는 입력된 명령어들의 순서데로 실행되었었지만, 판단과 분기의 명령들은 명령어의 실행의 흐름을 사용자가 임의로 변경,지정할 수있어 배치파일의 기능을 보다 강력하게 한다.

분기 명령..배치파일의 순차적 수행을 필요에 따라 변경할 때 사용하며
          배치파일에 프로그램적 기능을 갖게하는 명령이다.

조건분기(Conditional Branching).......IF명령

무조건분기(Unconditional Branching)...GOTO명령

① CALL [배치파일 인자]

배치파일 실행 중 다른 배치파일을 도중에 호출하여 실행시키고 다시
원래 배치파일로 돌아오게 하는 명령이다.

<예>  H1.BAT의 내용이 'DIR C:\ > A:MDIRLIST.TXT' ( C루트의 파일목
록을 A드라이브에 MDIRLIST.TXT 란 파일로 출력하라) 이라고 하자.

  C:\>COPY CON H2.BAT
    CALL H1.BAT
    TYPE A:MDIRLIST
    ^Z

<실행> C:\>H2 엔터하면 H1.BAT란 배치파일을 불러(CALL) 실행하여 MDIRLIST.TXT 파일을 A드라이브에 만든 후, 다시 H2.BAT 파일로 돌아와서 A드라이브의 'MDIRLIST.TXT' 파일을 화면에 타이프해 보인다.


②  IF 조건

주어진 조건에 따라 명령을 선별적으로 선택.실행케 하는 명령이다.

IF EXIST [파일이름] [명령]
         찾는 파일이 존재하면 명령을 실행하라

IF NOT EXIT [파일이름] [명령]
         찾는 파일이 없으면 명령을 실행하라

<예> IF EXIST *.BAK DEL *.BAK
       BAK라는 백업파일이 있으면 모두 지워버리라.


IF [NOT] "문자열1" == "문자열2" [명령]
    "문자열1"과 "문자열2"가 서로 일치 [불일치] 하면 명령을 실행하라.                     (양쪽 비교 문자열의 영문 대소문자를 구분한다)
    ==은 EQ로, !=은 같지 않다는 부호인데 NE로 대신할 수 있다.
  문자열은 " " 으로 반드시 구분하고 부호와는 한 칸 띈다.

<예> C:\>COPY CON TEST1.BAT
    @ECHO OFF
    IF "%1" == "A" ECHO TESTING A
    IF NOT "%1" == "A" ECHO IT IS NOT EQUAL.
    ^z

<실행> C:\>TEST1 A 엔터하면 화면에 TESTING A 라고 표시한다.
      C:\>TEST1 C 엔터하면 A와 같지 않으므로 IT IS NOT EQUAL 라고 표시한다.

IF [NOT] ERRORLEVEL [값] [명령]
     IF명령 바로 앞에서 수행되었던 프로그램이 수행을 마치면서 남긴 종료코드(ExitCode)를 검사하여 지정 값보다 크면(작으면) 명령을 실행하라는 뜻이다.

종료코드를 발생하는 명령어(FORMAT,XCOPY,COPY,BACKUP,RESTORE 등 일
반 도스명령어들 메뉴얼 참조)들은 0~255 범위에서 종료코드(EXITCODE)
값을 가지는데
에를 들면 XCOPY명령에서 성공적 수행일 때는 0, 화일이 없을 때 1, CTRL+C로 중단하면 2, 초기화 오류발생 때는 4, 디스크 에러에는 5를 반환하는 식으로 정해저 있다.

예>  C:\>COPY CON XY.BAT
        XCOPY %1 A:
        IF NOT ERRORLEEVEL 0 ECHO COPY FAILED !
        IF ERRORLEVEL 0 ECHO SUCCESSFULLY !
        ^Z

실행> C:\>XY *.* 엔터하면 성공적 수행여부에 따라  'FAILED !' 또는
                         'SUCCESSFULLY !' 라는 메시지가 나온다.

③ GOTO [레이블이름]
  레이블 이름이 있는 행으로 실행 순서를 옮긴다.
  '레이블(Label)'은 8자이 내로, 레이블 앞에는 콜론(:)을 사용한다.

<예> 현재 디렉토리에 *.HWP 파일을 C:\HNCDOC 디렉토리로 옮겨주는
     배치파일을 만들어 보자.

  C:\>COPY CON HWPMV.BAT
      @ECHO OFF
      IF NOT EXIST *.HWP GOTO FIRST
      MOVE /-Y *.HWP C:\HNCDOC
      ECHO HWPFILE MOVE DONE !
      GOTO END
      :FIRST
      ECHO *.HWP FILE NOT FOUND !
      :END
      ^Z

실행> C:\>HWPMV  엔터하면 C루트 디렉토리에 있는 모든 HWP 파일을 C:\HNCDOC 디렉토리로 옮기고 'HWP 파일을 모두 옮겼다'는 메시지를 화면에 보이고 END(끝) 레이블로 와서 도스상태로 빠저나 온다. 옮길 HWP 파일이 없으면 ' HWP 파일을 찾지 못했다'는 메시지가 나오고 끝(END) 낸다.

     GOTO 문에서는 항상 END 레이블로 배치를 끝낸다.

  배치 안에서 COPY,XCOPY,MOVE 명령은 /-Y 스위치를 써야 만이 목적지에 같은 이름의 파일이 있을 경우 덮어 쓸지여부를 확인하는 메시지를 출력한다.

④ 의사변수(Dummy Variables 가상의 변수)

바꿔 쓸 수 있는 인자(Replaceable Parameter)를 의사변수라 하며,
  %0 ~ %9(10개)으로 표시한다.

형식> C:\>명령어 파일1 파일2   "    "   "   "   "   " 파일9
           %0    %1    %2    %3   %4  %5  %6  %7  %8  %9

작성예1> C:\>COPY CON DIRALL.BAT
           DIR %1
           pause
           DIR %2
           pause
           type %0
           ^Z

실행예> C:\>DIRALL A: B: (엔터)

설명> 위 '실행 예'에서 명령어 DIRALL(.BAT)은 %0, A:은 %1, B:은 %2 에 해당하므로 '작성예1'의 내용 중 %1,%2,%0에 대입하여 명령을 수행한 결과가 화면에 나오게 된다. 즉 화면에는 'DIR A:'과, 'DIR B:'이 차례로 출력되고 멈췄다가 'DIRALL.BAT' 파일 내용이 출력된다.


작성예2> C:\>COPY CON EDIT2.BAT
             @ECHO OFF
             CLS
             TB          .....tb라는 프로그램을 메모리에 설치
             EDIT %1     ......%1은 '지정 파일'로 대체된다.
             TB/U        .......태백 한글을 메모리에서 제거
             ^Z

실행예> C:\>EDIT2 SAMPLE.TXT (엔터)
             %0    %1

설명> 위 '실행예'에서 명령어(EDIT2.BAT)는 %0, 파일1(SAMPLE.TXT)은 %1 에 해당하므로, '작성예2'의 배치파일 내용중 %1 대신에 SAMPLE.TXT라는 텍스트 파일이 대입된다.

화면은 한글을 읽고 쓸 수 있도록 태백한글을 메모리에 상주시킨다. 편집기는 SAMPLE.TXT 라는 파일을 읽어 화면에 띄워 수정.삽입 등 편집하고 저장할 수 있다. 편집을 끝내면 한글코드가 메모리에서 제거된다.


⑤ SHIFT

쉬프트는 옮김,변위를 의미하는 데 10개 이상의 대체 인자(Replaceable
Paramete)도 사용 가능하다. 대체인자를 한 자리씩 왼쪽으로 이동한다.

작성예> 지정한 문장(text) 파일들을 차례로 TYPE시키는 배치파일 예.

A:\>COPY CON TELLME.BAT
    @ECHO OFF
    :BEGIN
    IF NOT EXIST %1 GOTO END
    TYPE %1
    SHIFT
    GOTO BEGIN
    :END
    ECHO 더이상 파일이 없습니다.
    ^Z

실행예> A:\>TELLME AAA.TXT BBB.TXT CCC.TXT .........   엔터
           %0     %1       %2      %3     ........%15

설명> 위 '실행예'의 텍스트 파일명은 특정해야 하며 Wildcard문자(*,?)는 사용할 수 없다. 지정된 여러 파일들에 %1 변수가 차례로 SHIFT(변위)되면서 파일을 대입시켜 내용을 출력한다.
즉 AAA.TXT가 먼저 %1이 되고, 다음 BBB.TXT, 또 CCC.TXT, .....등이 %1에 대입된다. 계속 10개 이상의 변수도 지정할 수 있다.

지정된 파일이 모두 옮겨 대입되고 나면 배치파일이 끝나게 된다. 배치파일 내용 중 GOTO 명령에서 BEGIN 레이블로 가서 다시 시작하게하는 것을 LOOP(고리)라고 한다.


⑥ FOR
FOR 명령은 지정된 횟수 만큼 배치파일이 같은 명령을 계속 반복하게하는 명령, 즉 반복수행 (Looping) 명령이다.

형식)  FOR %%변수 IN (셋트 파라미터) DO [명령어] %%변수

     '(셋트 파라미터)'는 일련의 많은 갯수의 파일들을 말하고, '%%변수'는 SET에 명시된 각 파일에 순차적으로 설정되어 명령을 실행하는 대입변수이다.

     셋트 파라미터에 와일드카드문자(*,?)를  사용할 수 있다.

작성예> 확장명이 BAT,DOC,TXT,CAP인 문장 파일 모두를 차례로 화면에 출력(TYPE)되게 배치파일을 만들어 보자.

  C:\> COPY CON TYPEALL.BAT
       FOR %%Z IN (*.BAT *.DOC *.TXT *.CAP) DO TYPE %%Z
       ^Z

<실행>  C:\>TYPEALL C:\MDIR\*.BAT 엔터

  (*.BAT,  *.DOC,  *.TXT,  *.CAP 중에서 한 종류 파일만 지정한다.)

위 TYPEALL.BAT 파일을 실행할 때는 파일스펙(경로특정)이 있어야 한다.


2. 자동형 배치파일 (Aautoexec.bat)

일반배치파일 만들기와 동일하며 다만 이름만 AUTOEXEC.BAT로 한다.

컴퓨터를 구입할 때 이미 작성되어 있으므로 그 내용만 자기 필요에 따라 변경하면 될 것이다. 만약을 위해 원본 파일을 다른 곳에 백업해 놓고 필요시 다시 복사하면 좋을 것이다.

<작성예>  C:\>COPY CON AUTOEXEC.BAT
         @ECHO OFF
         CLS
         SMARTDRV
         LH V3RES
         PROMPT $P$G
         PATH=C:\;C:\DOS;C:\MDIR;C:\V&P
         LH DOSKEY
         M
         ^Z
         1 FIle(s) Copied

①  컴퓨터가 부팅할 때 DOS 시스템 프로그램을 메모리에 상주시킨 후
  곧 바로 자동실행 배치파일의 내용의 명령들을 실행한다. 


배치화일로 파일 내에 문자쓰기 
http://blog.naver.com/mokomoji/130001367333

배치파일로 폴더 내의 여러 파일을 각각 압축하기 
http://blog.naver.com/mokomoji/130001367394

배치화일 수동 초이스 만들기  
http://blog.naver.com/mokomoji/130001367431

html 배치화일 특수문자 해결
http://blog.naver.com/mokomoji/130001367445

배치화일 명령어
http://blog.naver.com/mokomoji/130001367473

[본문스크랩] 네트워크 드라이브 자동 연결하기
http://blog.naver.com/mokomoji/130003167299

[본문스크랩] IP 자동 변경 스크립트 
http://blog.naver.com/mokomoji/130003167289

[본문스크랩] 반복적인 ip 변경은 Bat 파일을 이용하여 간단하게
http://blog.naver.com/mokomoji/130003167083

[펌] 윈도우 콘솔 명령어들 
http://blog.naver.com/mokomoji/130001368352

배치파일로 폴더 내의 여러 파일을 각각 압축하기
http://blog.naver.com/mokomoji/130001367394

폴더 분기 
http://blog.naver.com/mokomoji/120019472999

[펌] 날짜 및 시간 얻어오기 배치파일
http://blog.naver.com/mokomoji/120016354197

배치화일 오늘날짜 폴더 생성
http://blog.naver.com/mokomoji/120014798527

배치화일 bat 화일 자동처리 1
http://blog.naver.com/mokomoji/120014798176







'Programing' 카테고리의 다른 글

구글 캘린더 API 자바 연동  (14) 2019.04.12
php 프로그래밍 게시판 사진 보이게 하는 소스코드  (0) 2016.03.27
알고리즘의 종류  (0) 2015.10.18
br 태그  (0) 2015.10.18
배치파일 명령어  (0) 2014.03.13

+ Recent posts