github.com/hy3/cuto@v0.9.8-0.20160830082821-aa6652f877b7/master/jobnet/parser/network.go (about)

     1  // ジョブネットワーク定義ファイル全体の定義。
     2  // Copyright 2015 unirita Inc.
     3  // Created 2015/04/10 honda
     4  
     5  package parser
     6  
     7  import (
     8  	"encoding/xml"
     9  	"fmt"
    10  	"io"
    11  	"os"
    12  )
    13  
    14  // ネットワーク定義BPMNのdefinitions要素。
    15  type Definitions struct {
    16  	Process []Process `xml:"process"`
    17  }
    18  
    19  // ネットワーク定義BPMNのprocess要素。
    20  type Process struct {
    21  	Start   []StartEvent      `xml:"startEvent"`
    22  	End     []EndEvent        `xml:"endEvent"`
    23  	Task    []ServiceTask     `xml:"serviceTask"`
    24  	Gateway []ParallelGateway `xml:"parallelGateway"`
    25  	Flow    []SequenceFlow    `xml:"sequenceFlow"`
    26  }
    27  
    28  // ネットワーク定義BPMNのstartEvent要素。
    29  type StartEvent struct {
    30  	ID string `xml:"id,attr"`
    31  }
    32  
    33  // ネットワーク定義BPMNのendEvent要素。
    34  type EndEvent struct {
    35  	ID string `xml:"id,attr"`
    36  }
    37  
    38  // ネットワーク定義BPMNのserviceTask要素。
    39  type ServiceTask struct {
    40  	ID   string `xml:"id,attr"`
    41  	Name string `xml:"name,attr"`
    42  }
    43  
    44  // ネットワーク定義BPMNのparallelGateway要素。
    45  type ParallelGateway struct {
    46  	ID string `xml:"id,attr"`
    47  }
    48  
    49  // ネットワーク定義BPMNのsequenceFlow要素。
    50  type SequenceFlow struct {
    51  	From string `xml:"sourceRef,attr"`
    52  	To   string `xml:"targetRef,attr"`
    53  }
    54  
    55  // ネットワーク定義をファイルから読み込み、パース結果を返す
    56  func ParseNetworkFile(fileName string) (*Process, error) {
    57  	file, err := os.Open(fileName)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	defer file.Close()
    62  
    63  	return ParseNetwork(file)
    64  }
    65  
    66  // ネットワーク定義をio.Readerから読み込み、パース結果を返す
    67  func ParseNetwork(reader io.Reader) (*Process, error) {
    68  	dec := xml.NewDecoder(reader)
    69  
    70  	defs := new(Definitions)
    71  	err := dec.Decode(defs)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	if len(defs.Process) != 1 {
    77  		return nil, fmt.Errorf("Process element is required, and must be unique.")
    78  	}
    79  	proc := defs.Process[0]
    80  
    81  	if len(proc.Start) != 1 {
    82  		return nil, fmt.Errorf("StartEvent element is required, and must be unique.")
    83  	}
    84  
    85  	if len(proc.End) != 1 {
    86  		return nil, fmt.Errorf("EndEvent element is required, and must be unique.")
    87  	}
    88  
    89  	return &proc, nil
    90  }