You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficcontrol.apache.org by da...@apache.org on 2018/02/22 16:57:09 UTC

[incubator-trafficcontrol] branch master updated (36eee10 -> fd728da)

This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git.


    from 36eee10  Updated configuration.rst and renamed defaultGeolocations
     new ea6f53a  converted the read to use the Read() interface
     new 589df81  renamed the Inserter interface to Creator to match the CRUD acronym
     new 8324aab  fixed test cases for the Inserter to Creator interface name change
     new 22eab8b  updated comment to reflect the Creator refactor
     new a2361c6  added functionality to support CRUD on the /divisions endpoint
     new 861b873  added TO Client funcs for invoking the /divisions CRUD
     new c929d89  cleaned up the cdns to account for the cdn package
     new a0bdfc8  refactored the asns to refer to the CRUD interface framework
     new 2d73bd6  cleaned up queries to account for the package names
     new 262e969  added TO client for ASNs
     new e61724c  added more test fixtures
     new c7397f9  updated to only deleteByID
     new 0e7d855  fixed asns test case
     new 49e18dd  added the TestInterface
     new 2b0ea08  added TestInterfaces test
     new 0b39602  added TestInterfaces test
     new e3e2c05  updated to support the GetID() interface change and the Inserter to Creator interface rename
     new 7ecb032  fixed merge conflict
     new fd8f390  fixed merge issue
     new 9360cb1  fixed merge issue
     new ae533b5  ds Inserter->Creator
     new e493f07  fix sql syntax
     new fd728da  fix column names; include cachegroup table in queries

The 23 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 traffic_ops/client/{cdn.go => asn.go}              |  91 ++-----
 traffic_ops/client/cdn.go                          |   6 +-
 traffic_ops/client/{cdn.go => division.go}         |  91 ++-----
 traffic_ops/testing/api/tc-fixtures.json           | 110 ++++++++
 traffic_ops/testing/api/v13/cdns_test.go           |  17 +-
 traffic_ops/traffic_ops_golang/api/change_log.go   |   2 +-
 .../traffic_ops_golang/api/change_log_test.go      |   4 +-
 .../traffic_ops_golang/api/shared_handlers.go      |  14 +-
 .../traffic_ops_golang/api/shared_handlers_test.go |   4 +-
 .../traffic_ops_golang/api/shared_interfaces.go    |   4 +-
 .../{cdn/cdns.go => asn/asns.go}                   | 266 +++++++++---------
 .../traffic_ops_golang/{ => asn}/asns_test.go      |  40 ++-
 traffic_ops/traffic_ops_golang/asns.go             | 125 ---------
 traffic_ops/traffic_ops_golang/cdn/cdns.go         | 178 ++++++------
 traffic_ops/traffic_ops_golang/cdn/cdns_test.go    |  24 +-
 .../deliveryservice/deliveryservices.go            |   6 +-
 .../deliveryservice/deliveryservices_test.go       |   4 +-
 .../deliveryservice/request/requests.go            |   6 +-
 .../deliveryservice/request/requests_test.go       |   4 +-
 .../{cdn/cdns.go => division/divisions.go}         | 299 ++++++++++++---------
 .../{ => division}/divisions_test.go               |  30 ++-
 traffic_ops/traffic_ops_golang/divisions.go        | 118 --------
 traffic_ops/traffic_ops_golang/routes.go           |  19 +-
 23 files changed, 670 insertions(+), 792 deletions(-)
 copy traffic_ops/client/{cdn.go => asn.go} (54%)
 copy traffic_ops/client/{cdn.go => division.go} (54%)
 create mode 100644 traffic_ops/testing/api/tc-fixtures.json
 copy traffic_ops/traffic_ops_golang/{cdn/cdns.go => asn/asns.go} (69%)
 rename traffic_ops/traffic_ops_golang/{ => asn}/asns_test.go (70%)
 delete mode 100644 traffic_ops/traffic_ops_golang/asns.go
 copy traffic_ops/traffic_ops_golang/{cdn/cdns.go => division/divisions.go} (60%)
 rename traffic_ops/traffic_ops_golang/{ => division}/divisions_test.go (79%)
 delete mode 100644 traffic_ops/traffic_ops_golang/divisions.go

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 12/23: updated to only deleteByID

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit c7397f9e6fda996cb777a7a0a899c661b4686559
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Mon Feb 19 13:31:11 2018 -0700

    updated to only deleteByID
---
 traffic_ops/client/cdn.go                |  6 +++---
 traffic_ops/testing/api/v13/cdns_test.go | 17 ++++++++++++-----
 2 files changed, 15 insertions(+), 8 deletions(-)

diff --git a/traffic_ops/client/cdn.go b/traffic_ops/client/cdn.go
index 7ab3c90..6bf2d93 100644
--- a/traffic_ops/client/cdn.go
+++ b/traffic_ops/client/cdn.go
@@ -117,9 +117,9 @@ func (to *Session) GetCDNByName(name string) ([]tc.CDN, ReqInf, error) {
 	return data.Response, reqInf, nil
 }
 
-// DELETE a CDN by CDN name
-func (to *Session) DeleteCDNByName(name string) (tc.Alerts, ReqInf, error) {
-	route := fmt.Sprintf("%s/name/%s", API_v2_CDNs, name)
+// DELETE a CDN by ID
+func (to *Session) DeleteCDNByID(id int) (tc.Alerts, ReqInf, error) {
+	route := fmt.Sprintf("%s/%d", API_v2_CDNs, id)
 	resp, remoteAddr, err := to.request(http.MethodDelete, route, nil)
 	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
 	if err != nil {
diff --git a/traffic_ops/testing/api/v13/cdns_test.go b/traffic_ops/testing/api/v13/cdns_test.go
index 2e425b1..1a7d9a8 100644
--- a/traffic_ops/testing/api/v13/cdns_test.go
+++ b/traffic_ops/testing/api/v13/cdns_test.go
@@ -84,18 +84,25 @@ func GetTestCDNs(t *testing.T) {
 
 func DeleteTestCDNs(t *testing.T) {
 
-	secondCDN := testData.CDNs[1]
-	resp, _, err := TOSession.DeleteCDNByName(secondCDN.Name)
+	cdn := testData.CDNs[1]
+	// Retrieve the CDN by name so we can get the id for the Update
+	resp, _, err := TOSession.GetCDNByName(cdn.Name)
+	if err != nil {
+		t.Errorf("cannot GET CDN by name: %v - %v\n", cdn.Name, err)
+	}
+	respCDN := resp[0]
+
+	delResp, _, err := TOSession.DeleteCDNByID(respCDN.ID)
 	if err != nil {
-		t.Errorf("cannot DELETE CDN by name: %v - %v\n", err, resp)
+		t.Errorf("cannot DELETE CDN by name: %v - %v\n", err, delResp)
 	}
 
 	// Retrieve the CDN to see if it got deleted
-	cdns, _, err := TOSession.GetCDNByName(secondCDN.Name)
+	cdns, _, err := TOSession.GetCDNByName(cdn.Name)
 	if err != nil {
 		t.Errorf("error deleting CDN name: %s\n", err.Error())
 	}
 	if len(cdns) > 0 {
-		t.Errorf("expected CDN name: %s to be deleted\n", secondCDN.Name)
+		t.Errorf("expected CDN name: %s to be deleted\n", cdn.Name)
 	}
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 08/23: refactored the asns to refer to the CRUD interface framework

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit a0bdfc89a04295c1a2360a1dfb6f68f58f3de5f8
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 14:36:49 2018 -0700

    refactored the asns to refer to the CRUD interface framework
---
 traffic_ops/traffic_ops_golang/asn/asns.go         | 326 +++++++++++++++++++++
 .../traffic_ops_golang/{ => asn}/asns_test.go      |   2 +-
 traffic_ops/traffic_ops_golang/asns.go             | 125 --------
 traffic_ops/traffic_ops_golang/routes.go           |   8 +-
 4 files changed, 334 insertions(+), 127 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/asn/asns.go b/traffic_ops/traffic_ops_golang/asn/asns.go
new file mode 100644
index 0000000..59ea4cc
--- /dev/null
+++ b/traffic_ops/traffic_ops_golang/asn/asns.go
@@ -0,0 +1,326 @@
+package asn
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+import (
+	"errors"
+	"fmt"
+	"strconv"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
+	"github.com/jmoiron/sqlx"
+	"github.com/lib/pq"
+)
+
+// ASNsPrivLevel ...
+const ASNsPrivLevel = 10
+
+//we need a type alias to define functions on
+type TOASN tc.ASN
+
+//the refType is passed into the handlers where a copy of its type is used to decode the json.
+var refType = TOASN(tc.ASN{})
+
+func GetRefType() *TOASN {
+	return &refType
+}
+
+//Implementation of the Identifier, Validator interface functions
+func (asn *TOASN) GetID() int {
+	return asn.ID
+}
+
+func (asn *TOASN) GetAuditName() string {
+	return strconv.Itoa(asn.ASN)
+}
+
+func (asn *TOASN) GetType() string {
+	return "asn"
+}
+
+func (asn *TOASN) SetID(i int) {
+	asn.ID = i
+}
+
+func (asn *TOASN) Validate(db *sqlx.DB) []error {
+	errs := []error{}
+	if asn.ASN < 1 {
+		errs = append(errs, errors.New(`ASN 'asn' is required.`))
+	}
+	return errs
+}
+
+//The TOASN implementation of the Creator interface
+//all implementations of Creator should use transactions and return the proper errorType
+//ParsePQUniqueConstraintError is used to determine if a asn with conflicting values exists
+//if so, it will return an errorType of DataConflict and the type should be appended to the
+//generic error message returned
+//The insert sql returns the id and lastUpdated values of the newly inserted asn and have
+//to be added to the struct
+func (asn *TOASN) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	resultRows, err := tx.NamedQuery(insertQuery(), asn)
+	if err != nil {
+		if pqErr, ok := err.(*pq.Error); ok {
+			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
+			if eType == tc.DataConflictError {
+				return errors.New("a asn with " + err.Error()), eType
+			}
+			return err, eType
+		} else {
+			log.Errorf("received non pq error: %++v from create execution", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	defer resultRows.Close()
+
+	var id int
+	var lastUpdated tc.Time
+	rowsAffected := 0
+	for resultRows.Next() {
+		rowsAffected++
+		if err := resultRows.Scan(&id, &lastUpdated); err != nil {
+			log.Error.Printf("could not scan id from insert: %s\n", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	if rowsAffected == 0 {
+		err = errors.New("no asn was inserted, no id was returned")
+		log.Errorln(err)
+		return tc.DBError, tc.SystemError
+	} else if rowsAffected > 1 {
+		err = errors.New("too many ids returned from asn insert")
+		log.Errorln(err)
+		return tc.DBError, tc.SystemError
+	}
+	asn.SetID(id)
+	asn.LastUpdated = lastUpdated
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
+func (asn *TOASN) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+	var rows *sqlx.Rows
+
+	// Query Parameters to Database Query column mappings
+	// see the fields mapped in the SQL query
+	queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
+		"domainName":    dbhelpers.WhereColumnInfo{"domain_name", nil},
+		"dnssecEnabled": dbhelpers.WhereColumnInfo{"dnssec_enabled", nil},
+		"id":            dbhelpers.WhereColumnInfo{"id", api.IsInt},
+		"name":          dbhelpers.WhereColumnInfo{"name", nil},
+	}
+	where, orderBy, queryValues, errs := dbhelpers.BuildWhereAndOrderBy(parameters, queryParamsToQueryCols)
+	if len(errs) > 0 {
+		return nil, errs, tc.DataConflictError
+	}
+
+	query := selectQuery() + where + orderBy
+	log.Debugln("Query is ", query)
+
+	rows, err := db.NamedQuery(query, queryValues)
+	if err != nil {
+		log.Errorf("Error querying ASNs: %v", err)
+		return nil, []error{tc.DBError}, tc.SystemError
+	}
+	defer rows.Close()
+
+	ASNs := []interface{}{}
+	for rows.Next() {
+		var s tc.ASN
+		if err = rows.StructScan(&s); err != nil {
+			log.Errorf("error parsing ASN rows: %v", err)
+			return nil, []error{tc.DBError}, tc.SystemError
+		}
+		ASNs = append(ASNs, s)
+	}
+
+	return ASNs, []error{}, tc.NoError
+}
+
+func selectQuery() string {
+	query := `SELECT
+id,
+asn,
+last_updated,
+cachegroup
+
+FROM asn a`
+	return query
+}
+
+//The TOASN implementation of the Updater interface
+//all implementations of Updater should use transactions and return the proper errorType
+//ParsePQUniqueConstraintError is used to determine if a asn with conflicting values exists
+//if so, it will return an errorType of DataConflict and the type should be appended to the
+//generic error message returned
+func (asn *TOASN) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	log.Debugf("about to run exec query: %s with asn: %++v", updateQuery(), asn)
+	resultRows, err := tx.NamedQuery(updateQuery(), asn)
+	if err != nil {
+		if pqErr, ok := err.(*pq.Error); ok {
+			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
+			if eType == tc.DataConflictError {
+				return errors.New("a asn with " + err.Error()), eType
+			}
+			return err, eType
+		} else {
+			log.Errorf("received error: %++v from update execution", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	defer resultRows.Close()
+
+	var lastUpdated tc.Time
+	rowsAffected := 0
+	for resultRows.Next() {
+		rowsAffected++
+		if err := resultRows.Scan(&lastUpdated); err != nil {
+			log.Error.Printf("could not scan lastUpdated from insert: %s\n", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	log.Debugf("lastUpdated: %++v", lastUpdated)
+	asn.LastUpdated = lastUpdated
+	if rowsAffected != 1 {
+		if rowsAffected < 1 {
+			return errors.New("no asn found with this id"), tc.DataMissingError
+		} else {
+			return fmt.Errorf("this update affected too many rows: %d", rowsAffected), tc.SystemError
+		}
+	}
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
+//The ASN implementation of the Deleter interface
+//all implementations of Deleter should use transactions and return the proper errorType
+func (asn *TOASN) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	log.Debugf("about to run exec query: %s with asn: %++v", deleteQuery(), asn)
+	result, err := tx.NamedExec(deleteQuery(), asn)
+	if err != nil {
+		log.Errorf("received error: %++v from delete execution", err)
+		return tc.DBError, tc.SystemError
+	}
+	rowsAffected, err := result.RowsAffected()
+	if err != nil {
+		return tc.DBError, tc.SystemError
+	}
+	if rowsAffected != 1 {
+		if rowsAffected < 1 {
+			return errors.New("no asn with that id found"), tc.DataMissingError
+		} else {
+			return fmt.Errorf("this create affected too many rows: %d", rowsAffected), tc.SystemError
+		}
+	}
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
+func insertQuery() string {
+	query := `INSERT INTO asn (
+asn,
+cachegroup) 
+VALUES (
+:asn,
+:cachegroup) RETURNING id,last_updated`
+	return query
+}
+
+func updateQuery() string {
+	query := `UPDATE
+asn SET
+asn=:asn,
+cachegroup=:cachegroup,
+WHERE id=:id RETURNING last_updated`
+	return query
+}
+
+func deleteQuery() string {
+	query := `DELETE FROM asn
+WHERE id=:id`
+	return query
+}
diff --git a/traffic_ops/traffic_ops_golang/asns_test.go b/traffic_ops/traffic_ops_golang/asn/asns_test.go
similarity index 99%
rename from traffic_ops/traffic_ops_golang/asns_test.go
rename to traffic_ops/traffic_ops_golang/asn/asns_test.go
index 64101c0..6501a72 100644
--- a/traffic_ops/traffic_ops_golang/asns_test.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns_test.go
@@ -1,4 +1,4 @@
-package main
+package asn
 
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
diff --git a/traffic_ops/traffic_ops_golang/asns.go b/traffic_ops/traffic_ops_golang/asns.go
deleted file mode 100644
index 86a2fa7..0000000
--- a/traffic_ops/traffic_ops_golang/asns.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package main
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-import (
-	"encoding/json"
-	"fmt"
-	"net/http"
-
-	"github.com/apache/incubator-trafficcontrol/lib/go-log"
-	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
-	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
-	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
-	"github.com/jmoiron/sqlx"
-)
-
-// ASNsPrivLevel ...
-const ASNsPrivLevel = 10
-
-// ASNsHandler ...
-func ASNsHandler(db *sqlx.DB) http.HandlerFunc {
-	return func(w http.ResponseWriter, r *http.Request) {
-		handleErrs := tc.GetHandleErrorsFunc(w, r)
-
-		params, err := api.GetCombinedParams(r)
-		if err != nil {
-			log.Errorf("unable to get parameters from request: %s", err)
-			handleErrs(http.StatusInternalServerError, err)
-		}
-
-		resp, errs, errType := getASNsResponse(params, db)
-		if len(errs) > 0 {
-			tc.HandleErrorsWithType(errs, errType, handleErrs)
-			return
-		}
-
-		respBts, err := json.Marshal(resp)
-		if err != nil {
-			handleErrs(http.StatusInternalServerError, err)
-			return
-		}
-
-		w.Header().Set("Content-Type", "application/json")
-		fmt.Fprintf(w, "%s", respBts)
-	}
-}
-
-func getASNsResponse(parameters map[string]string, db *sqlx.DB) (*tc.ASNsResponse, []error, tc.ApiErrorType) {
-	asns, errs, errType := getASNs(parameters, db)
-	if len(errs) > 0 {
-		return nil, errs, errType
-	}
-
-	resp := tc.ASNsResponse{
-		Response: asns,
-	}
-	return &resp, nil, tc.NoError
-}
-
-func getASNs(parameters map[string]string, db *sqlx.DB) ([]tc.ASN, []error, tc.ApiErrorType) {
-	var rows *sqlx.Rows
-	var err error
-
-	// Query Parameters to Database Query column mappings
-	// see the fields mapped in the SQL query
-	queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
-		"asn":        dbhelpers.WhereColumnInfo{"a.asn", api.IsInt},
-		"id":         dbhelpers.WhereColumnInfo{"a.id", api.IsInt},
-		"cachegroup": dbhelpers.WhereColumnInfo{"cg.id", api.IsInt},
-	}
-
-	where, orderBy, queryValues, errs := dbhelpers.BuildWhereAndOrderBy(parameters, queryParamsToQueryCols)
-	if len(errs) > 0 {
-		return nil, errs, tc.DataConflictError
-	}
-	query := selectASNsQuery() + where + orderBy
-	log.Debugln("Query is ", query)
-
-	rows, err = db.NamedQuery(query, queryValues)
-	if err != nil {
-		return nil, []error{err}, tc.SystemError
-	}
-	defer rows.Close()
-
-	ASNs := []tc.ASN{}
-	for rows.Next() {
-		var s tc.ASN
-		if err = rows.StructScan(&s); err != nil {
-			return nil, []error{fmt.Errorf("getting ASNs: %v", err)}, tc.SystemError
-		}
-		ASNs = append(ASNs, s)
-	}
-	return ASNs, nil, tc.NoError
-}
-
-func selectASNsQuery() string {
-
-	query := `SELECT
-a.asn,
-cg.name as cachegroup,
-a.cachegroup as cachegroup_id,
-a.id,
-a.last_updated
-
-FROM asn a
-JOIN cachegroup cg ON cg.id = a.cachegroup`
-	return query
-}
diff --git a/traffic_ops/traffic_ops_golang/routes.go b/traffic_ops/traffic_ops_golang/routes.go
index 8da3ce0..58f2a54 100644
--- a/traffic_ops/traffic_ops_golang/routes.go
+++ b/traffic_ops/traffic_ops_golang/routes.go
@@ -30,6 +30,7 @@ import (
 
 	tclog "github.com/apache/incubator-trafficcontrol/lib/go-log"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/asn"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/cdn"
 	dsrequest "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice/request"
@@ -55,7 +56,12 @@ func Routes(d ServerData) ([]Route, http.Handler, error) {
 
 	routes := []Route{
 		//ASNs
-		{1.2, http.MethodGet, `asns/?(\.json)?$`, ASNsHandler(d.DB), ASNsPrivLevel, Authenticated, nil},
+		{1.3, http.MethodGet, `asns/?(\.json)?$`, api.ReadHandler(asn.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+		{1.3, http.MethodGet, `asns/{id}$`, api.ReadHandler(asn.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+		{1.3, http.MethodPut, `asns/{id}$`, api.UpdateHandler(asn.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
+		{1.3, http.MethodPost, `asns/?$`, api.CreateHandler(asn.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
+		{1.3, http.MethodDelete, `asns/{id}$`, api.DeleteHandler(asn.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
+
 		//CDNs
 		// explicitly passed to legacy system until fully implemented.  Auth handled by legacy system.
 		{1.2, http.MethodGet, `cdns/capacity$`, handlerToFunc(proxyHandler), 0, NoAuth, []Middleware{}},

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 19/23: fixed merge issue

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit fd8f390f8682b1fe52fa109ea9f15db3dc9de224
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Thu Feb 22 08:12:48 2018 -0700

    fixed merge issue
---
 traffic_ops/traffic_ops_golang/division/divisions.go | 1 +
 1 file changed, 1 insertion(+)

diff --git a/traffic_ops/traffic_ops_golang/division/divisions.go b/traffic_ops/traffic_ops_golang/division/divisions.go
index 176c256..a461a3c 100644
--- a/traffic_ops/traffic_ops_golang/division/divisions.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions.go
@@ -50,6 +50,7 @@ func (division *TODivision) GetAuditName() string {
 func (division *TODivision) GetID() (int, bool) {
 	return division.ID, true
 }
+
 func (division *TODivision) SetID(i int) {
 	division.ID = i
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 20/23: fixed merge issue

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 9360cb185762b9ffb88db9c0311c8a74c13c5fe7
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Thu Feb 22 08:14:26 2018 -0700

    fixed merge issue
---
 traffic_ops/traffic_ops_golang/cdn/cdns.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns.go b/traffic_ops/traffic_ops_golang/cdn/cdns.go
index 4639390..c1b7510 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns.go
@@ -156,7 +156,7 @@ func (cdn *TOCDN) Read(db *sqlx.DB, parameters map[string]string, user auth.Curr
 		return nil, errs, tc.DataConflictError
 	}
 
-	query := selectCDNsQuery() + where + orderBy
+	query := selectQuery() + where + orderBy
 	log.Debugln("Query is ", query)
 
 	rows, err := db.NamedQuery(query, queryValues)
@@ -289,7 +289,7 @@ func (cdn *TOCDN) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 	return nil, tc.NoError
 }
 
-func selectCDNsQuery() string {
+func selectQuery() string {
 	query := `SELECT
 dnssec_enabled,
 domain_name,

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 04/23: updated comment to reflect the Creator refactor

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 22eab8b4c808231f151fcfb1214258d7b05a7fd0
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 13:52:29 2018 -0700

    updated comment to reflect the Creator refactor
---
 traffic_ops/traffic_ops_golang/cdn/cdns.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns.go b/traffic_ops/traffic_ops_golang/cdn/cdns.go
index 00b99a8..26ae242 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns.go
@@ -187,8 +187,8 @@ func (cdn *TOCDN) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 	return nil, tc.NoError
 }
 
-//The TOCDN implementation of the Inserter interface
-//all implementations of Inserter should use transactions and return the proper errorType
+//The TOCDN implementation of the Creator interface
+//all implementations of Creator should use transactions and return the proper errorType
 //ParsePQUniqueConstraintError is used to determine if a cdn with conflicting values exists
 //if so, it will return an errorType of DataConflict and the type should be appended to the
 //generic error message returned

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 22/23: fix sql syntax

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit e493f07bef4162c9440d0d4c3ffb520fa9f75d97
Author: Dan Kirkwood <da...@apache.org>
AuthorDate: Wed Feb 21 15:24:09 2018 -0700

    fix sql syntax
---
 traffic_ops/traffic_ops_golang/asn/asns.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/traffic_ops/traffic_ops_golang/asn/asns.go b/traffic_ops/traffic_ops_golang/asn/asns.go
index b2a129f..6e8c0d6 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns.go
@@ -314,7 +314,7 @@ func updateQuery() string {
 	query := `UPDATE
 asn SET
 asn=:asn,
-cachegroup=:cachegroup,
+cachegroup=:cachegroup
 WHERE id=:id RETURNING last_updated`
 	return query
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 18/23: fixed merge conflict

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 7ecb0320d3d81c597bb13134c58b773a144410c0
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Thu Feb 22 08:11:25 2018 -0700

    fixed merge conflict
---
 traffic_ops/traffic_ops_golang/cdn/cdns.go | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns.go b/traffic_ops/traffic_ops_golang/cdn/cdns.go
index 5366140..4639390 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns.go
@@ -179,18 +179,6 @@ func (cdn *TOCDN) Read(db *sqlx.DB, parameters map[string]string, user auth.Curr
 	return CDNs, []error{}, tc.NoError
 }
 
-func selectCDNsQuery() string {
-	query := `SELECT
-dnssec_enabled,
-domain_name,
-id,
-last_updated,
-name
-
-FROM cdn c`
-	return query
-}
-
 //The TOCDN implementation of the Updater interface
 //all implementations of Updater should use transactions and return the proper errorType
 //ParsePQUniqueConstraintError is used to determine if a cdn with conflicting values exists
@@ -301,6 +289,18 @@ func (cdn *TOCDN) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 	return nil, tc.NoError
 }
 
+func selectCDNsQuery() string {
+	query := `SELECT
+dnssec_enabled,
+domain_name,
+id,
+last_updated,
+name
+
+FROM cdn c`
+	return query
+}
+
 func updateQuery() string {
 	query := `UPDATE
 cdn SET

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 13/23: fixed asns test case

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 0e7d855196b26189348fe41fc3bbbc96d19bc9eb
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Tue Feb 20 11:37:27 2018 -0700

    fixed asns test case
---
 traffic_ops/traffic_ops_golang/asn/asns_test.go | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/asn/asns_test.go b/traffic_ops/traffic_ops_golang/asn/asns_test.go
index 6501a72..85bc948 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns_test.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns_test.go
@@ -24,6 +24,7 @@ import (
 	"time"
 
 	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/test"
 	"github.com/jmoiron/sqlx"
 
@@ -73,13 +74,14 @@ func TestGetASNs(t *testing.T) {
 	mock.ExpectQuery("SELECT").WillReturnRows(rows)
 	v := map[string]string{"dsId": "1"}
 
-	servers, errs, errType := getASNs(v, db)
+	asns, errs, _ := refType.Read(db, v, auth.CurrentUser{})
+
 	if len(errs) > 0 {
-		t.Errorf("getASNs expected: no errors, actual: %v with type %s", errs, errType.String())
+		t.Errorf("asn.Read expected: no errors, actual: %v", errs)
 	}
 
-	if len(servers) != 2 {
-		t.Errorf("getASNs expected: len(servers) == 1, actual: %v", len(servers))
+	if len(asns) != 2 {
+		t.Errorf("asn.Read expected: len(asns) == 2, actual: %v", len(asns))
 	}
 
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 23/23: fix column names; include cachegroup table in queries

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit fd728da0e42b5d53a72f2c260683942153c65c30
Author: Dan Kirkwood <da...@apache.org>
AuthorDate: Wed Feb 21 17:57:43 2018 -0700

    fix column names; include cachegroup table in queries
---
 traffic_ops/traffic_ops_golang/asn/asns.go | 27 ++++++++++++++++-----------
 1 file changed, 16 insertions(+), 11 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/asn/asns.go b/traffic_ops/traffic_ops_golang/asn/asns.go
index 6e8c0d6..5037e2e 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns.go
@@ -146,10 +146,9 @@ func (asn *TOASN) Read(db *sqlx.DB, parameters map[string]string, user auth.Curr
 	// Query Parameters to Database Query column mappings
 	// see the fields mapped in the SQL query
 	queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
-		"domainName":    dbhelpers.WhereColumnInfo{"domain_name", nil},
-		"dnssecEnabled": dbhelpers.WhereColumnInfo{"dnssec_enabled", nil},
-		"id":            dbhelpers.WhereColumnInfo{"id", api.IsInt},
-		"name":          dbhelpers.WhereColumnInfo{"name", nil},
+		"asn":        dbhelpers.WhereColumnInfo{"a.asn", nil},
+		"cachegroup": dbhelpers.WhereColumnInfo{"c.name", nil},
+		"id":         dbhelpers.WhereColumnInfo{"a.id", api.IsInt},
 	}
 	where, orderBy, queryValues, errs := dbhelpers.BuildWhereAndOrderBy(parameters, queryParamsToQueryCols)
 	if len(errs) > 0 {
@@ -181,12 +180,13 @@ func (asn *TOASN) Read(db *sqlx.DB, parameters map[string]string, user auth.Curr
 
 func selectQuery() string {
 	query := `SELECT
-id,
-asn,
-last_updated,
-cachegroup
+a.id,
+a.asn,
+a.last_updated,
+a.cachegroup AS cachegroup_id,
+c.name AS cachegroup
 
-FROM asn a`
+FROM asn a JOIN cachegroup c ON a.cachegroup = c.id`
 	return query
 }
 
@@ -306,7 +306,10 @@ asn,
 cachegroup) 
 VALUES (
 :asn,
-:cachegroup) RETURNING id,last_updated`
+(SELECT id from cachegroup
+WHERE name=:cachegroup
+))
+RETURNING id,last_updated`
 	return query
 }
 
@@ -314,7 +317,9 @@ func updateQuery() string {
 	query := `UPDATE
 asn SET
 asn=:asn,
-cachegroup=:cachegroup
+cachegroup=(SELECT id from cachegroup
+WHERE name=:cachegroup
+)
 WHERE id=:id RETURNING last_updated`
 	return query
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 03/23: fixed test cases for the Inserter to Creator interface name change

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 8324aabe9e7a91b947740a69383c9322bc6dee0e
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 11:20:35 2018 -0700

    fixed test cases for the Inserter to Creator interface name change
---
 traffic_ops/traffic_ops_golang/api/change_log_test.go      | 4 ++--
 traffic_ops/traffic_ops_golang/api/shared_handlers_test.go | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/api/change_log_test.go b/traffic_ops/traffic_ops_golang/api/change_log_test.go
index 62e69c7..bfbcab2 100644
--- a/traffic_ops/traffic_ops_golang/api/change_log_test.go
+++ b/traffic_ops/traffic_ops_golang/api/change_log_test.go
@@ -44,7 +44,7 @@ func (i *testIdentifier) GetAuditName() string {
 	return "testerInstance"
 }
 
-func TestInsertChangeLog(t *testing.T) {
+func TestCreateChangeLog(t *testing.T) {
 	mockDB, mock, err := sqlmock.New()
 	if err != nil {
 		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
@@ -60,7 +60,7 @@ func TestInsertChangeLog(t *testing.T) {
 
 	mock.ExpectExec("INSERT").WithArgs(ApiChange, expectedMessage, 1).WillReturnResult(sqlmock.NewResult(1, 1))
 	user := auth.CurrentUser{ID: 1}
-	err = InsertChangeLog(ApiChange, Created, &i, user, db)
+	err = CreateChangeLog(ApiChange, Created, &i, user, db)
 	if err != nil {
 		t.Fatal(err)
 	}
diff --git a/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go b/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go
index 7f6873c..51b3aa6 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go
@@ -62,8 +62,8 @@ func (v *tester) Validate(db *sqlx.DB) []error {
 	return []error{}
 }
 
-//Inserter interface functions
-func (i *tester) Insert(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+//Creator interface functions
+func (i *tester) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
 	return i.error, i.errorType
 }
 

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 11/23: added more test fixtures

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit e61724c7ffcc76dfa4390c82d2cc962806a74582
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Thu Feb 15 13:13:36 2018 -0700

    added more test fixtures
---
 traffic_ops/testing/api/tc-fixtures.json | 110 +++++++++++++++++++++++++++++++
 1 file changed, 110 insertions(+)

diff --git a/traffic_ops/testing/api/tc-fixtures.json b/traffic_ops/testing/api/tc-fixtures.json
new file mode 100644
index 0000000..4154fa0
--- /dev/null
+++ b/traffic_ops/testing/api/tc-fixtures.json
@@ -0,0 +1,110 @@
+{
+    "asns": [
+        {
+            "asn": 1111,
+            "cachegroup": "cachegroup1",
+            "cachegroupId": 1
+        },
+        {
+            "asn": 2222,
+            "cachegroup": "cachegroup2",
+            "cachegroupId": 2
+        }
+    ],
+    "cachegroups": [
+        {
+            "latitude": 0,
+            "longitude": 0,
+            "name": "parentCacheGroup",
+            "parentCacheGroupName": null
+        },
+        {
+            "latitude": 0,
+            "longitude": 0,
+            "name": "secondaryCacheGroup",
+            "parentCacheGroupName": null
+        },
+        {
+            "latitude": 0,
+            "longitude": 0,
+            "name": "cachegroup1",
+            "parentCacheGroupName": "parentCacheGroup",
+            "secondaryCacheGroupName": "parentCacheGroup",
+            "shortName": "cg1"
+        },
+        {
+            "latitude": 24.1234,
+            "longitude": -121.1234,
+            "name": "cachegroup2",
+            "parentCacheGroupName": "secondaryCacheGroup",
+            "secondaryCacheGroupName": "secondaryCacheGroup",
+            "shortName": "cg2"
+        }
+    ],
+    "cdns": [
+        {
+            "dnssecEnabled": true,
+            "domainName": "test.cdn1.net",
+            "name": "cdn1"
+        },
+        {
+            "dnssecEnabled": false,
+            "domainName": "test.cdn2.net",
+            "name": "cdn2"
+        },
+        {
+            "dnssecEnabled": true,
+            "domainName": "test.cdn3.net",
+            "name": "cdn3"
+        }
+    ],
+    "deliveryServices": [
+        {
+            "active": false,
+            "dscp": 40,
+            "tenantName": "tenant1",
+            "xmlId": "ds1"
+        },
+        {
+            "active": false,
+            "dscp": 40,
+            "tenantName": "tenant2",
+            "xmlId": "ds2"
+        }
+    ],
+    "divisions": [
+        {
+            "name": "division1"
+        },
+        {
+            "name": "division2"
+        }
+    ],
+    "regions": [
+        {
+            "divisionName": "division1",
+            "name": "region1"
+        },
+        {
+            "divisionName": "division2",
+            "name": "region2"
+        }
+    ],
+    "tenants": [
+        {
+            "active": true,
+            "name": "root",
+            "parentTenantName": null
+        },
+        {
+            "active": true,
+            "name": "tenant1",
+            "parentTenantName": "root"
+        },
+        {
+            "active": false,
+            "name": "tenant2",
+            "parentTenantName": "root"
+        }
+    ]
+}

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 21/23: ds Inserter->Creator

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit ae533b52484943572a700bef90c3af7abbc2f29e
Author: Dan Kirkwood <da...@apache.org>
AuthorDate: Wed Feb 21 11:52:45 2018 -0700

    ds Inserter->Creator
---
 traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go
index bc26ace..a969b21 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go
@@ -264,14 +264,14 @@ func (ds *TODeliveryService) Update(db *sqlx.DB, user auth.CurrentUser) (error,
 	return nil, tc.NoError
 }
 
-// Insert implements the Inserter interface.
-//all implementations of Inserter should use transactions and return the proper errorType
+// Create implements the Creator interface.
+//all implementations of Creator should use transactions and return the proper errorType
 //ParsePQUniqueConstraintError is used to determine if a ds with conflicting values exists
 //if so, it will return an errorType of DataConflict and the type should be appended to the
 //generic error message returned
 //The insert sql returns the id and lastUpdated values of the newly inserted ds and have
 //to be added to the struct
-func (ds *TODeliveryService) Insert(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (ds *TODeliveryService) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
 	tx, err := db.Beginx()
 	defer func() {
 		if tx == nil {

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 15/23: added TestInterfaces test

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 2b0ea08457349e0ec78f6064819d8b59786cb5b2
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Tue Feb 20 14:33:07 2018 -0700

    added TestInterfaces test
---
 .../traffic_ops_golang/division/divisions_test.go  | 28 +++++++++++++++-------
 1 file changed, 19 insertions(+), 9 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/division/divisions_test.go b/traffic_ops/traffic_ops_golang/division/divisions_test.go
index dd6a9a7..10ab007 100644
--- a/traffic_ops/traffic_ops_golang/division/divisions_test.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions_test.go
@@ -24,6 +24,7 @@ import (
 	"time"
 
 	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/test"
 	"github.com/jmoiron/sqlx"
 
@@ -81,14 +82,23 @@ func TestGetDivisions(t *testing.T) {
 
 }
 
-type SortableDivisions []tc.Division
+func TestInterfaces(t *testing.T) {
+	var i interface{}
+	i = &TODivision{}
 
-func (s SortableDivisions) Len() int {
-	return len(s)
-}
-func (s SortableDivisions) Swap(i, j int) {
-	s[i], s[j] = s[j], s[i]
-}
-func (s SortableDivisions) Less(i, j int) bool {
-	return s[i].Name < s[j].Name
+	if _, ok := i.(api.Creator); !ok {
+		t.Errorf("division must be creator")
+	}
+	if _, ok := i.(api.Reader); !ok {
+		t.Errorf("division must be reader")
+	}
+	if _, ok := i.(api.Updater); !ok {
+		t.Errorf("division must be updater")
+	}
+	if _, ok := i.(api.Deleter); !ok {
+		t.Errorf("division must be deleter")
+	}
+	if _, ok := i.(api.Identifier); !ok {
+		t.Errorf("division must be Identifier")
+	}
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 05/23: added functionality to support CRUD on the /divisions endpoint

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit a2361c6c4c3a2fffc349307f29414aff8a750971
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 13:53:01 2018 -0700

    added functionality to support CRUD on the /divisions endpoint
---
 .../traffic_ops_golang/division/divisions.go       | 232 ++++++++++++++++++++-
 traffic_ops/traffic_ops_golang/routes.go           |   1 +
 2 files changed, 229 insertions(+), 4 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/division/divisions.go b/traffic_ops/traffic_ops_golang/division/divisions.go
index 68acd03..881e7c0 100644
--- a/traffic_ops/traffic_ops_golang/division/divisions.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions.go
@@ -20,6 +20,7 @@ package division
  */
 
 import (
+	"errors"
 	"fmt"
 
 	"github.com/apache/incubator-trafficcontrol/lib/go-log"
@@ -28,6 +29,7 @@ import (
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
 	"github.com/jmoiron/sqlx"
+	"github.com/lib/pq"
 )
 
 //we need a type alias to define functions on
@@ -40,7 +42,99 @@ func GetRefType() *TODivision {
 	return &refType
 }
 
-func (cdn *TODivision) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+func (division *TODivision) GetAuditName() string {
+	return division.Name
+}
+
+//Implementation of the Identifier, Validator interface functions
+func (division *TODivision) GetID() int {
+	return division.ID
+}
+func (division *TODivision) SetID(i int) {
+	division.ID = i
+}
+func (division *TODivision) GetType() string {
+	return "division"
+}
+
+func (division *TODivision) Validate(db *sqlx.DB) []error {
+	errs := []error{}
+	if len(division.Name) < 1 {
+		errs = append(errs, errors.New(`Division 'name' is required.`))
+	}
+	return errs
+}
+
+//The TODivision implementation of the Creator interface
+//all implementations of Creator should use transactions and return the proper errorType
+//ParsePQUniqueConstraintError is used to determine if a division with conflicting values exists
+//if so, it will return an errorType of DataConflict and the type should be appended to the
+//generic error message returned
+//The insert sql returns the id and lastUpdated values of the newly inserted division and have
+//to be added to the struct
+func (division *TODivision) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	resultRows, err := tx.NamedQuery(insertQuery(), division)
+	if err != nil {
+		if pqErr, ok := err.(*pq.Error); ok {
+			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
+			if eType == tc.DataConflictError {
+				return errors.New("a division with " + err.Error()), eType
+			}
+			return err, eType
+		} else {
+			log.Errorf("received non pq error: %++v from create execution", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	defer resultRows.Close()
+
+	var id int
+	var lastUpdated tc.Time
+	rowsAffected := 0
+	for resultRows.Next() {
+		rowsAffected++
+		if err := resultRows.Scan(&id, &lastUpdated); err != nil {
+			log.Error.Printf("could not scan id from insert: %s\n", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	if rowsAffected == 0 {
+		err = errors.New("no division was inserted, no id was returned")
+		log.Errorln(err)
+		return tc.DBError, tc.SystemError
+	} else if rowsAffected > 1 {
+		err = errors.New("too many ids returned from division insert")
+		log.Errorln(err)
+		return tc.DBError, tc.SystemError
+	}
+	division.SetID(id)
+	division.LastUpdated = lastUpdated
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
+func (division *TODivision) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
 	// Query Parameters to Database Query column mappings
 	// see the fields mapped in the SQL query
 	queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
@@ -52,7 +146,7 @@ func (cdn *TODivision) Read(db *sqlx.DB, parameters map[string]string, user auth
 		return nil, errs, tc.DataConflictError
 	}
 
-	query := selectDivisionsQuery() + where + orderBy
+	query := selectQuery() + where + orderBy
 	log.Debugln("Query is ", query)
 
 	rows, err := db.NamedQuery(query, queryValues)
@@ -75,6 +169,71 @@ func (cdn *TODivision) Read(db *sqlx.DB, parameters map[string]string, user auth
 	return divisions, []error{}, tc.NoError
 }
 
+//The TODivision implementation of the Updater interface
+//all implementations of Updater should use transactions and return the proper errorType
+//ParsePQUniqueConstraintError is used to determine if a division with conflicting values exists
+//if so, it will return an errorType of DataConflict and the type should be appended to the
+//generic error message returned
+func (division *TODivision) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	log.Debugf("about to run exec query: %s with division: %++v", updateQuery(), division)
+	resultRows, err := tx.NamedQuery(updateQuery(), division)
+	if err != nil {
+		if pqErr, ok := err.(*pq.Error); ok {
+			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
+			if eType == tc.DataConflictError {
+				return errors.New("a division with " + err.Error()), eType
+			}
+			return err, eType
+		} else {
+			log.Errorf("received error: %++v from update execution", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	defer resultRows.Close()
+
+	var lastUpdated tc.Time
+	rowsAffected := 0
+	for resultRows.Next() {
+		rowsAffected++
+		if err := resultRows.Scan(&lastUpdated); err != nil {
+			log.Error.Printf("could not scan lastUpdated from insert: %s\n", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	log.Debugf("lastUpdated: %++v", lastUpdated)
+	division.LastUpdated = lastUpdated
+	if rowsAffected != 1 {
+		if rowsAffected < 1 {
+			return errors.New("no division found with this id"), tc.DataMissingError
+		} else {
+			return fmt.Errorf("this update affected too many rows: %d", rowsAffected), tc.SystemError
+		}
+	}
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
 func getDivisionsResponse(params map[string]string, db *sqlx.DB) (*tc.DivisionsResponse, []error, tc.ApiErrorType) {
 	divisions, errs, errType := getDivisions(params, db)
 	if len(errs) > 0 {
@@ -103,7 +262,7 @@ func getDivisions(params map[string]string, db *sqlx.DB) ([]tc.Division, []error
 		return nil, errs, tc.DataConflictError
 	}
 
-	query := selectDivisionsQuery() + where + orderBy
+	query := selectQuery() + where + orderBy
 	log.Debugln("Query is ", query)
 
 	rows, err = db.NamedQuery(query, queryValues)
@@ -123,7 +282,58 @@ func getDivisions(params map[string]string, db *sqlx.DB) ([]tc.Division, []error
 	return o, nil, tc.NoError
 }
 
-func selectDivisionsQuery() string {
+//The Division implementation of the Deleter interface
+//all implementations of Deleter should use transactions and return the proper errorType
+func (division *TODivision) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	log.Debugf("about to run exec query: %s with division: %++v", deleteQuery(), division)
+	result, err := tx.NamedExec(deleteQuery(), division)
+	if err != nil {
+		log.Errorf("received error: %++v from delete execution", err)
+		return tc.DBError, tc.SystemError
+	}
+	rowsAffected, err := result.RowsAffected()
+	if err != nil {
+		return tc.DBError, tc.SystemError
+	}
+	if rowsAffected != 1 {
+		if rowsAffected < 1 {
+			return errors.New("no division with that id found"), tc.DataMissingError
+		} else {
+			return fmt.Errorf("this create affected too many rows: %d", rowsAffected), tc.SystemError
+		}
+	}
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
+func insertQuery() string {
+	query := `INSERT INTO division (
+name) VALUES (:name) RETURNING id,last_updated`
+	return query
+}
+
+func selectQuery() string {
 
 	query := `SELECT
 id,
@@ -133,3 +343,17 @@ name
 FROM division d`
 	return query
 }
+
+func updateQuery() string {
+	query := `UPDATE
+division SET
+name=:name
+WHERE id=:id RETURNING last_updated`
+	return query
+}
+
+func deleteQuery() string {
+	query := `DELETE FROM division
+WHERE id=:id`
+	return query
+}
diff --git a/traffic_ops/traffic_ops_golang/routes.go b/traffic_ops/traffic_ops_golang/routes.go
index 4be4d4d..8da3ce0 100644
--- a/traffic_ops/traffic_ops_golang/routes.go
+++ b/traffic_ops/traffic_ops_golang/routes.go
@@ -91,6 +91,7 @@ func Routes(d ServerData) ([]Route, http.Handler, error) {
 		//Divisions
 		{1.2, http.MethodGet, `divisions/?(\.json)?$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
 		{1.3, http.MethodGet, `divisions/{id}$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+		{1.3, http.MethodPost, `divisions/?$`, api.CreateHandler(division.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
 
 		//HwInfo
 		{1.2, http.MethodGet, `hwinfo-wip/?(\.json)?$`, hwInfoHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 10/23: added TO client for ASNs

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 262e969c0dfda7ca54c525405982ec3b8e4b22d7
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 14:37:36 2018 -0700

    added TO client for ASNs
---
 traffic_ops/client/asn.go | 132 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 132 insertions(+)

diff --git a/traffic_ops/client/asn.go b/traffic_ops/client/asn.go
new file mode 100644
index 0000000..fefeeae
--- /dev/null
+++ b/traffic_ops/client/asn.go
@@ -0,0 +1,132 @@
+/*
+
+   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 client
+
+import (
+	"encoding/json"
+	"fmt"
+	"net"
+	"net/http"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+)
+
+const (
+	API_v2_ASNs = "/api/1.3/asns"
+)
+
+// Create a ASN
+func (to *Session) CreateASN(entity tc.ASN) (tc.Alerts, ReqInf, error) {
+
+	var remoteAddr net.Addr
+	reqBody, err := json.Marshal(entity)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	resp, remoteAddr, err := to.request(http.MethodPost, API_v2_ASNs, reqBody)
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	defer resp.Body.Close()
+	var alerts tc.Alerts
+	err = json.NewDecoder(resp.Body).Decode(&alerts)
+	return alerts, reqInf, nil
+}
+
+// Update a ASN by ID
+func (to *Session) UpdateASNByID(id int, entity tc.ASN) (tc.Alerts, ReqInf, error) {
+
+	var remoteAddr net.Addr
+	reqBody, err := json.Marshal(entity)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	route := fmt.Sprintf("%s/%d", API_v2_ASNs, id)
+	resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody)
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	defer resp.Body.Close()
+	var alerts tc.Alerts
+	err = json.NewDecoder(resp.Body).Decode(&alerts)
+	return alerts, reqInf, nil
+}
+
+// Returns a list of ASNs
+func (to *Session) GetASNs() ([]tc.ASN, ReqInf, error) {
+	resp, remoteAddr, err := to.request(http.MethodGet, API_v2_ASNs, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return nil, reqInf, err
+	}
+	defer resp.Body.Close()
+
+	var data tc.ASNsResponse
+	err = json.NewDecoder(resp.Body).Decode(&data)
+	return data.Response, reqInf, nil
+}
+
+// GET a ASN by the id
+func (to *Session) GetASNByID(id int) ([]tc.ASN, ReqInf, error) {
+	route := fmt.Sprintf("%s/%d", API_v2_ASNs, id)
+	resp, remoteAddr, err := to.request(http.MethodGet, route, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return nil, reqInf, err
+	}
+	defer resp.Body.Close()
+
+	var data tc.ASNsResponse
+	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
+		return nil, reqInf, err
+	}
+
+	return data.Response, reqInf, nil
+}
+
+// GET an ASN by the asn number
+func (to *Session) GetASNByASN(asn int) ([]tc.ASN, ReqInf, error) {
+	url := fmt.Sprintf("%s?asn=%d", API_v2_ASNs, asn)
+	resp, remoteAddr, err := to.request(http.MethodGet, url, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return nil, reqInf, err
+	}
+	defer resp.Body.Close()
+
+	var data tc.ASNsResponse
+	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
+		return nil, reqInf, err
+	}
+
+	return data.Response, reqInf, nil
+}
+
+// DELETE an ASN by asn number
+func (to *Session) DeleteASNByASN(asn int) (tc.Alerts, ReqInf, error) {
+	route := fmt.Sprintf("%s/asn/%d", API_v2_ASNs, asn)
+	resp, remoteAddr, err := to.request(http.MethodDelete, route, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	defer resp.Body.Close()
+	var alerts tc.Alerts
+	err = json.NewDecoder(resp.Body).Decode(&alerts)
+	return alerts, reqInf, nil
+}

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 17/23: updated to support the GetID() interface change and the Inserter to Creator interface rename

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit e3e2c05aa1aa80ac9c80c43a5c80fd669fb6dbac
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 21 11:26:14 2018 -0700

    updated to support the GetID() interface change and the Inserter to Creator interface rename
---
 traffic_ops/traffic_ops_golang/asn/asns.go                          | 4 ++--
 .../traffic_ops_golang/deliveryservice/deliveryservices_test.go     | 4 ++--
 traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go  | 6 +++---
 .../traffic_ops_golang/deliveryservice/request/requests_test.go     | 4 ++--
 traffic_ops/traffic_ops_golang/division/divisions.go                | 4 ++--
 5 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/asn/asns.go b/traffic_ops/traffic_ops_golang/asn/asns.go
index 59ea4cc..b2a129f 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns.go
@@ -47,8 +47,8 @@ func GetRefType() *TOASN {
 }
 
 //Implementation of the Identifier, Validator interface functions
-func (asn *TOASN) GetID() int {
-	return asn.ID
+func (asn *TOASN) GetID() (int, bool) {
+	return asn.ID, true
 }
 
 func (asn *TOASN) GetAuditName() string {
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go
index 55dd62e..28c50ce 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go
@@ -32,8 +32,8 @@ func getInterface(req *TODeliveryService) interface{} {
 func TestInterfaces(t *testing.T) {
 	r := getInterface(&TODeliveryService{})
 
-	if _, ok := r.(api.Inserter); !ok {
-		t.Errorf("DeliveryService must be Inserter")
+	if _, ok := r.(api.Creator); !ok {
+		t.Errorf("DeliveryService must be Creator")
 	}
 	// TODO: uncomment when ds.Reader interface is implemented
 	/*if _, ok := r.(api.Reader); !ok {
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go
index 6770be9..aff4678 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go
@@ -267,14 +267,14 @@ func (req *TODeliveryServiceRequest) Update(db *sqlx.DB, user auth.CurrentUser)
 	return nil, tc.NoError
 }
 
-// Insert implements the tc.Inserter interface
-//all implementations of Inserter should use transactions and return the proper errorType
+// Creator implements the tc.Creator interface
+//all implementations of Creator should use transactions and return the proper errorType
 //ParsePQUniqueConstraintError is used to determine if a request with conflicting values exists
 //if so, it will return an errorType of DataConflict and the type should be appended to the
 //generic error message returned
 //The insert sql returns the id and lastUpdated values of the newly inserted request and have
 //to be added to the struct
-func (req *TODeliveryServiceRequest) Insert(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (req *TODeliveryServiceRequest) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
 	if req == nil {
 		return errors.New("nil deliveryservice_request"), tc.SystemError
 	}
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go
index 103a9c6..e038f69 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go
@@ -32,8 +32,8 @@ func TestInterfaces(t *testing.T) {
 	var i interface{}
 	i = &TODeliveryServiceRequest{}
 
-	if _, ok := i.(api.Inserter); !ok {
-		t.Errorf("DeliveryServiceRequest must be Inserter")
+	if _, ok := i.(api.Creator); !ok {
+		t.Errorf("DeliveryServiceRequest must be Creator")
 	}
 	if _, ok := i.(api.Reader); !ok {
 		t.Errorf("DeliveryServiceRequest must be Reader")
diff --git a/traffic_ops/traffic_ops_golang/division/divisions.go b/traffic_ops/traffic_ops_golang/division/divisions.go
index 881e7c0..176c256 100644
--- a/traffic_ops/traffic_ops_golang/division/divisions.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions.go
@@ -47,8 +47,8 @@ func (division *TODivision) GetAuditName() string {
 }
 
 //Implementation of the Identifier, Validator interface functions
-func (division *TODivision) GetID() int {
-	return division.ID
+func (division *TODivision) GetID() (int, bool) {
+	return division.ID, true
 }
 func (division *TODivision) SetID(i int) {
 	division.ID = i

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 09/23: cleaned up queries to account for the package names

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 2d73bd6be8db46b4b888931939dc8c10db382535
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 14:37:17 2018 -0700

    cleaned up queries to account for the package names
---
 traffic_ops/traffic_ops_golang/cdn/cdns.go | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns.go b/traffic_ops/traffic_ops_golang/cdn/cdns.go
index ef87ba1..5366140 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns.go
@@ -95,7 +95,7 @@ func (cdn *TOCDN) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 		log.Error.Printf("could not begin transaction: %v", err)
 		return tc.DBError, tc.SystemError
 	}
-	resultRows, err := tx.NamedQuery(insertCDNQuery(), cdn)
+	resultRows, err := tx.NamedQuery(insertQuery(), cdn)
 	if err != nil {
 		if pqErr, ok := err.(*pq.Error); ok {
 			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -275,8 +275,8 @@ func (cdn *TOCDN) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 		log.Error.Printf("could not begin transaction: %v", err)
 		return tc.DBError, tc.SystemError
 	}
-	log.Debugf("about to run exec query: %s with cdn: %++v", deleteCDNQuery(), cdn)
-	result, err := tx.NamedExec(deleteCDNQuery(), cdn)
+	log.Debugf("about to run exec query: %s with cdn: %++v", deleteQuery(), cdn)
+	result, err := tx.NamedExec(deleteQuery(), cdn)
 	if err != nil {
 		log.Errorf("received error: %++v from delete execution", err)
 		return tc.DBError, tc.SystemError
@@ -311,7 +311,7 @@ WHERE id=:id RETURNING last_updated`
 	return query
 }
 
-func insertCDNQuery() string {
+func insertQuery() string {
 	query := `INSERT INTO cdn (
 dnssec_enabled,
 domain_name,
@@ -322,7 +322,7 @@ name) VALUES (
 	return query
 }
 
-func deleteCDNQuery() string {
+func deleteQuery() string {
 	query := `DELETE FROM cdn
 WHERE id=:id`
 	return query

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 16/23: added TestInterfaces test

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 0b3960289fe80f3284d0a2a8f315713e8e27611a
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Tue Feb 20 14:35:51 2018 -0700

    added TestInterfaces test
---
 traffic_ops/traffic_ops_golang/cdn/cdns_test.go | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns_test.go b/traffic_ops/traffic_ops_golang/cdn/cdns_test.go
index ff60aae..38c9abd 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns_test.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns_test.go
@@ -24,6 +24,7 @@ import (
 	"time"
 
 	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/test"
 	"github.com/jmoiron/sqlx"
@@ -66,8 +67,6 @@ func TestReadCDNs(t *testing.T) {
 	cols := test.ColsFromStructByTag("db", tc.CDN{})
 	rows := sqlmock.NewRows(cols)
 
-	//TODO: drichardson - build helper to add these Rows from the struct values
-	//                    or by CSV if types get in the way
 	for _, ts := range testCDNs {
 		rows = rows.AddRow(
 			ts.DNSSECEnabled,
@@ -89,3 +88,24 @@ func TestReadCDNs(t *testing.T) {
 		t.Errorf("cdn.Read expected: len(servers) == 2, actual: %v", len(servers))
 	}
 }
+
+func TestInterfaces(t *testing.T) {
+	var i interface{}
+	i = &TOCDN{}
+
+	if _, ok := i.(api.Creator); !ok {
+		t.Errorf("cdn must be creator")
+	}
+	if _, ok := i.(api.Reader); !ok {
+		t.Errorf("cdn must be reader")
+	}
+	if _, ok := i.(api.Updater); !ok {
+		t.Errorf("cdn must be updater")
+	}
+	if _, ok := i.(api.Deleter); !ok {
+		t.Errorf("cdn must be deleter")
+	}
+	if _, ok := i.(api.Identifier); !ok {
+		t.Errorf("cdn must be Identifier")
+	}
+}

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 01/23: converted the read to use the Read() interface

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit ea6f53a2b833218de1e0a306caa6f7c573cad7f6
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 10:34:20 2018 -0700

    converted the read to use the Read() interface
---
 .../traffic_ops_golang/{ => division}/divisions.go | 63 ++++++++++++++--------
 .../{ => division}/divisions_test.go               |  2 +-
 traffic_ops/traffic_ops_golang/routes.go           |  5 +-
 3 files changed, 45 insertions(+), 25 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/divisions.go b/traffic_ops/traffic_ops_golang/division/divisions.go
similarity index 63%
rename from traffic_ops/traffic_ops_golang/divisions.go
rename to traffic_ops/traffic_ops_golang/division/divisions.go
index 10eac0b..68acd03 100644
--- a/traffic_ops/traffic_ops_golang/divisions.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions.go
@@ -1,4 +1,4 @@
-package main
+package division
 
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
@@ -20,42 +20,59 @@ package main
  */
 
 import (
-	"encoding/json"
 	"fmt"
-	"net/http"
 
 	"github.com/apache/incubator-trafficcontrol/lib/go-log"
 	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
 	"github.com/jmoiron/sqlx"
 )
 
-func divisionsHandler(db *sqlx.DB) http.HandlerFunc {
-	return func(w http.ResponseWriter, r *http.Request) {
-		handleErrs := tc.GetHandleErrorsFunc(w, r)
+//we need a type alias to define functions on
+type TODivision tc.Division
 
-		params, err := api.GetCombinedParams(r)
-		if err != nil {
-			log.Errorf("unable to get parameters from request: %s", err)
-			handleErrs(http.StatusInternalServerError, err)
-		}
+//the refType is passed into the handlers where a copy of its type is used to decode the json.
+var refType = TODivision(tc.Division{})
 
-		resp, errs, errType := getDivisionsResponse(params, db)
-		if len(errs) > 0 {
-			tc.HandleErrorsWithType(errs, errType, handleErrs)
-			return
-		}
+func GetRefType() *TODivision {
+	return &refType
+}
 
-		respBts, err := json.Marshal(resp)
-		if err != nil {
-			handleErrs(http.StatusInternalServerError, err)
-			return
-		}
+func (cdn *TODivision) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+	// Query Parameters to Database Query column mappings
+	// see the fields mapped in the SQL query
+	queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
+		"id":   dbhelpers.WhereColumnInfo{"id", api.IsInt},
+		"name": dbhelpers.WhereColumnInfo{"name", nil},
+	}
+	where, orderBy, queryValues, errs := dbhelpers.BuildWhereAndOrderBy(parameters, queryParamsToQueryCols)
+	if len(errs) > 0 {
+		return nil, errs, tc.DataConflictError
+	}
+
+	query := selectDivisionsQuery() + where + orderBy
+	log.Debugln("Query is ", query)
 
-		w.Header().Set("Content-Type", "application/json")
-		fmt.Fprintf(w, "%s", respBts)
+	rows, err := db.NamedQuery(query, queryValues)
+	if err != nil {
+		log.Errorf("Error querying Divisions: %v", err)
+		return nil, []error{tc.DBError}, tc.SystemError
 	}
+	defer rows.Close()
+
+	divisions := []interface{}{}
+	for rows.Next() {
+		var s tc.Division
+		if err = rows.StructScan(&s); err != nil {
+			log.Errorf("error parsing Division rows: %v", err)
+			return nil, []error{tc.DBError}, tc.SystemError
+		}
+		divisions = append(divisions, s)
+	}
+
+	return divisions, []error{}, tc.NoError
 }
 
 func getDivisionsResponse(params map[string]string, db *sqlx.DB) (*tc.DivisionsResponse, []error, tc.ApiErrorType) {
diff --git a/traffic_ops/traffic_ops_golang/divisions_test.go b/traffic_ops/traffic_ops_golang/division/divisions_test.go
similarity index 99%
rename from traffic_ops/traffic_ops_golang/divisions_test.go
rename to traffic_ops/traffic_ops_golang/division/divisions_test.go
index 636b3fb5..dd6a9a7 100644
--- a/traffic_ops/traffic_ops_golang/divisions_test.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions_test.go
@@ -1,4 +1,4 @@
-package main
+package division
 
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
diff --git a/traffic_ops/traffic_ops_golang/routes.go b/traffic_ops/traffic_ops_golang/routes.go
index 5936fc8..4bdd5a7 100644
--- a/traffic_ops/traffic_ops_golang/routes.go
+++ b/traffic_ops/traffic_ops_golang/routes.go
@@ -33,6 +33,7 @@ import (
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/cdn"
 	dsrequest "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice/request"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/division"
 	"github.com/basho/riak-go-client"
 )
 
@@ -85,8 +86,10 @@ func Routes(d ServerData) ([]Route, http.Handler, error) {
 		{1.3, http.MethodPost, `deliveryservices/{xmlID}/urisignkeys$`, saveDeliveryServiceURIKeysHandler(d.DB, d.Config), auth.PrivLevelAdmin, Authenticated, nil},
 		{1.3, http.MethodPut, `deliveryservices/{xmlID}/urisignkeys$`, saveDeliveryServiceURIKeysHandler(d.DB, d.Config), auth.PrivLevelAdmin, Authenticated, nil},
 		{1.3, http.MethodDelete, `deliveryservices/{xmlID}/urisignkeys$`, removeDeliveryServiceURIKeysHandler(d.DB, d.Config), auth.PrivLevelAdmin, Authenticated, nil},
+
 		//Divisions
-		{1.2, http.MethodGet, `divisions/?(\.json)?$`, divisionsHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+		{1.2, http.MethodGet, `divisions/?(\.json)?$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+
 		//HwInfo
 		{1.2, http.MethodGet, `hwinfo-wip/?(\.json)?$`, hwInfoHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
 		//Parameters

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 07/23: cleaned up the cdns to account for the cdn package

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit c929d8933c720f451d459b7b7dbd4a287eb888e5
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 14:02:33 2018 -0700

    cleaned up the cdns to account for the cdn package
---
 traffic_ops/traffic_ops_golang/cdn/cdns.go | 144 ++++++++++++++---------------
 1 file changed, 72 insertions(+), 72 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns.go b/traffic_ops/traffic_ops_golang/cdn/cdns.go
index 26ae242..ef87ba1 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns.go
@@ -71,6 +71,75 @@ func (cdn *TOCDN) Validate(db *sqlx.DB) []error {
 	return errs
 }
 
+//The TOCDN implementation of the Creator interface
+//all implementations of Creator should use transactions and return the proper errorType
+//ParsePQUniqueConstraintError is used to determine if a cdn with conflicting values exists
+//if so, it will return an errorType of DataConflict and the type should be appended to the
+//generic error message returned
+//The insert sql returns the id and lastUpdated values of the newly inserted cdn and have
+//to be added to the struct
+func (cdn *TOCDN) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+	rollbackTransaction := true
+	tx, err := db.Beginx()
+	defer func() {
+		if tx == nil || !rollbackTransaction {
+			return
+		}
+		err := tx.Rollback()
+		if err != nil {
+			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
+		}
+	}()
+
+	if err != nil {
+		log.Error.Printf("could not begin transaction: %v", err)
+		return tc.DBError, tc.SystemError
+	}
+	resultRows, err := tx.NamedQuery(insertCDNQuery(), cdn)
+	if err != nil {
+		if pqErr, ok := err.(*pq.Error); ok {
+			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
+			if eType == tc.DataConflictError {
+				return errors.New("a cdn with " + err.Error()), eType
+			}
+			return err, eType
+		} else {
+			log.Errorf("received non pq error: %++v from create execution", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	defer resultRows.Close()
+
+	var id int
+	var lastUpdated tc.Time
+	rowsAffected := 0
+	for resultRows.Next() {
+		rowsAffected++
+		if err := resultRows.Scan(&id, &lastUpdated); err != nil {
+			log.Error.Printf("could not scan id from insert: %s\n", err)
+			return tc.DBError, tc.SystemError
+		}
+	}
+	if rowsAffected == 0 {
+		err = errors.New("no cdn was inserted, no id was returned")
+		log.Errorln(err)
+		return tc.DBError, tc.SystemError
+	} else if rowsAffected > 1 {
+		err = errors.New("too many ids returned from cdn insert")
+		log.Errorln(err)
+		return tc.DBError, tc.SystemError
+	}
+	cdn.SetID(id)
+	cdn.LastUpdated = lastUpdated
+	err = tx.Commit()
+	if err != nil {
+		log.Errorln("Could not commit transaction: ", err)
+		return tc.DBError, tc.SystemError
+	}
+	rollbackTransaction = false
+	return nil, tc.NoError
+}
+
 func (cdn *TOCDN) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
 	var rows *sqlx.Rows
 
@@ -144,8 +213,8 @@ func (cdn *TOCDN) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 		log.Error.Printf("could not begin transaction: %v", err)
 		return tc.DBError, tc.SystemError
 	}
-	log.Debugf("about to run exec query: %s with cdn: %++v", updateCDNQuery(), cdn)
-	resultRows, err := tx.NamedQuery(updateCDNQuery(), cdn)
+	log.Debugf("about to run exec query: %s with cdn: %++v", updateQuery(), cdn)
+	resultRows, err := tx.NamedQuery(updateQuery(), cdn)
 	if err != nil {
 		if pqErr, ok := err.(*pq.Error); ok {
 			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -187,75 +256,6 @@ func (cdn *TOCDN) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 	return nil, tc.NoError
 }
 
-//The TOCDN implementation of the Creator interface
-//all implementations of Creator should use transactions and return the proper errorType
-//ParsePQUniqueConstraintError is used to determine if a cdn with conflicting values exists
-//if so, it will return an errorType of DataConflict and the type should be appended to the
-//generic error message returned
-//The insert sql returns the id and lastUpdated values of the newly inserted cdn and have
-//to be added to the struct
-func (cdn *TOCDN) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
-	rollbackTransaction := true
-	tx, err := db.Beginx()
-	defer func() {
-		if tx == nil || !rollbackTransaction {
-			return
-		}
-		err := tx.Rollback()
-		if err != nil {
-			log.Errorln(errors.New("rolling back transaction: " + err.Error()))
-		}
-	}()
-
-	if err != nil {
-		log.Error.Printf("could not begin transaction: %v", err)
-		return tc.DBError, tc.SystemError
-	}
-	resultRows, err := tx.NamedQuery(insertCDNQuery(), cdn)
-	if err != nil {
-		if pqErr, ok := err.(*pq.Error); ok {
-			err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
-			if eType == tc.DataConflictError {
-				return errors.New("a cdn with " + err.Error()), eType
-			}
-			return err, eType
-		} else {
-			log.Errorf("received non pq error: %++v from create execution", err)
-			return tc.DBError, tc.SystemError
-		}
-	}
-	defer resultRows.Close()
-
-	var id int
-	var lastUpdated tc.Time
-	rowsAffected := 0
-	for resultRows.Next() {
-		rowsAffected++
-		if err := resultRows.Scan(&id, &lastUpdated); err != nil {
-			log.Error.Printf("could not scan id from insert: %s\n", err)
-			return tc.DBError, tc.SystemError
-		}
-	}
-	if rowsAffected == 0 {
-		err = errors.New("no cdn was inserted, no id was returned")
-		log.Errorln(err)
-		return tc.DBError, tc.SystemError
-	} else if rowsAffected > 1 {
-		err = errors.New("too many ids returned from cdn insert")
-		log.Errorln(err)
-		return tc.DBError, tc.SystemError
-	}
-	cdn.SetID(id)
-	cdn.LastUpdated = lastUpdated
-	err = tx.Commit()
-	if err != nil {
-		log.Errorln("Could not commit transaction: ", err)
-		return tc.DBError, tc.SystemError
-	}
-	rollbackTransaction = false
-	return nil, tc.NoError
-}
-
 //The CDN implementation of the Deleter interface
 //all implementations of Deleter should use transactions and return the proper errorType
 func (cdn *TOCDN) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
@@ -301,7 +301,7 @@ func (cdn *TOCDN) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 	return nil, tc.NoError
 }
 
-func updateCDNQuery() string {
+func updateQuery() string {
 	query := `UPDATE
 cdn SET
 dnssec_enabled=:dnssec_enabled,

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 14/23: added the TestInterface

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 49e18dd47b5e19c3ab72de3fd7c049b493187922
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Tue Feb 20 14:32:11 2018 -0700

    added the TestInterface
---
 traffic_ops/traffic_ops_golang/asn/asns_test.go | 28 +++++++++++++++++--------
 1 file changed, 19 insertions(+), 9 deletions(-)

diff --git a/traffic_ops/traffic_ops_golang/asn/asns_test.go b/traffic_ops/traffic_ops_golang/asn/asns_test.go
index 85bc948..9d967df 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns_test.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns_test.go
@@ -24,6 +24,7 @@ import (
 	"time"
 
 	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth"
 	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/test"
 	"github.com/jmoiron/sqlx"
@@ -86,14 +87,23 @@ func TestGetASNs(t *testing.T) {
 
 }
 
-type SortableASNs []tc.ASN
+func TestInterfaces(t *testing.T) {
+	var i interface{}
+	i = &TOASN{}
 
-func (s SortableASNs) Len() int {
-	return len(s)
-}
-func (s SortableASNs) Swap(i, j int) {
-	s[i], s[j] = s[j], s[i]
-}
-func (s SortableASNs) Less(i, j int) bool {
-	return s[i].ASN < s[j].ASN
+	if _, ok := i.(api.Creator); !ok {
+		t.Errorf("asn must be creator")
+	}
+	if _, ok := i.(api.Reader); !ok {
+		t.Errorf("asn must be reader")
+	}
+	if _, ok := i.(api.Updater); !ok {
+		t.Errorf("asn must be updater")
+	}
+	if _, ok := i.(api.Deleter); !ok {
+		t.Errorf("asn must be deleter")
+	}
+	if _, ok := i.(api.Identifier); !ok {
+		t.Errorf("asn must be Identifier")
+	}
 }

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 02/23: renamed the Inserter interface to Creator to match the CRUD acronym

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 589df81e82b1c7305e63cf3d43fe79c2bcbd3313
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 11:07:28 2018 -0700

    renamed the Inserter interface to Creator to match the CRUD acronym
---
 traffic_ops/client/division.go                     | 132 +++++++++++++++++++++
 traffic_ops/traffic_ops_golang/api/change_log.go   |   2 +-
 .../traffic_ops_golang/api/shared_handlers.go      |  14 +--
 .../traffic_ops_golang/api/shared_interfaces.go    |   4 +-
 traffic_ops/traffic_ops_golang/cdn/cdns.go         |   2 +-
 traffic_ops/traffic_ops_golang/routes.go           |   5 +
 6 files changed, 148 insertions(+), 11 deletions(-)

diff --git a/traffic_ops/client/division.go b/traffic_ops/client/division.go
new file mode 100644
index 0000000..cda8701
--- /dev/null
+++ b/traffic_ops/client/division.go
@@ -0,0 +1,132 @@
+/*
+
+   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 client
+
+import (
+	"encoding/json"
+	"fmt"
+	"net"
+	"net/http"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+)
+
+const (
+	API_v2_Divisions = "/api/1.3/divisions"
+)
+
+// Create a Division
+func (to *Session) CreateDivision(division tc.Division) (tc.Alerts, ReqInf, error) {
+
+	var remoteAddr net.Addr
+	reqBody, err := json.Marshal(division)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	resp, remoteAddr, err := to.request(http.MethodPost, API_v2_Divisions, reqBody)
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	defer resp.Body.Close()
+	var alerts tc.Alerts
+	err = json.NewDecoder(resp.Body).Decode(&alerts)
+	return alerts, reqInf, nil
+}
+
+// Update a Division by ID
+func (to *Session) UpdateDivisionByID(id int, division tc.Division) (tc.Alerts, ReqInf, error) {
+
+	var remoteAddr net.Addr
+	reqBody, err := json.Marshal(division)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	route := fmt.Sprintf("%s/%d", API_v2_Divisions, id)
+	resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody)
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	defer resp.Body.Close()
+	var alerts tc.Alerts
+	err = json.NewDecoder(resp.Body).Decode(&alerts)
+	return alerts, reqInf, nil
+}
+
+// Returns a list of Divisions
+func (to *Session) GetDivisions() ([]tc.Division, ReqInf, error) {
+	resp, remoteAddr, err := to.request(http.MethodGet, API_v2_Divisions, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return nil, reqInf, err
+	}
+	defer resp.Body.Close()
+
+	var data tc.DivisionsResponse
+	err = json.NewDecoder(resp.Body).Decode(&data)
+	return data.Response, reqInf, nil
+}
+
+// GET a Division by the Division id
+func (to *Session) GetDivisionByID(id int) ([]tc.Division, ReqInf, error) {
+	route := fmt.Sprintf("%s/%d", API_v2_Divisions, id)
+	resp, remoteAddr, err := to.request(http.MethodGet, route, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return nil, reqInf, err
+	}
+	defer resp.Body.Close()
+
+	var data tc.DivisionsResponse
+	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
+		return nil, reqInf, err
+	}
+
+	return data.Response, reqInf, nil
+}
+
+// GET a Division by the Division name
+func (to *Session) GetDivisionByName(name string) ([]tc.Division, ReqInf, error) {
+	url := fmt.Sprintf("%s/name/%s", API_v2_Divisions, name)
+	resp, remoteAddr, err := to.request(http.MethodGet, url, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return nil, reqInf, err
+	}
+	defer resp.Body.Close()
+
+	var data tc.DivisionsResponse
+	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
+		return nil, reqInf, err
+	}
+
+	return data.Response, reqInf, nil
+}
+
+// DELETE a Division by Division name
+func (to *Session) DeleteDivisionByName(name string) (tc.Alerts, ReqInf, error) {
+	route := fmt.Sprintf("%s/name/%s", API_v2_Divisions, name)
+	resp, remoteAddr, err := to.request(http.MethodDelete, route, nil)
+	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
+	if err != nil {
+		return tc.Alerts{}, reqInf, err
+	}
+	defer resp.Body.Close()
+	var alerts tc.Alerts
+	err = json.NewDecoder(resp.Body).Decode(&alerts)
+	return alerts, reqInf, nil
+}
diff --git a/traffic_ops/traffic_ops_golang/api/change_log.go b/traffic_ops/traffic_ops_golang/api/change_log.go
index 53d4128..73c06fc 100644
--- a/traffic_ops/traffic_ops_golang/api/change_log.go
+++ b/traffic_ops/traffic_ops_golang/api/change_log.go
@@ -44,7 +44,7 @@ const (
 	Deleted   = "Deleted"
 )
 
-func InsertChangeLog(level string, action string, i Identifier, user auth.CurrentUser, db *sqlx.DB) error {
+func CreateChangeLog(level string, action string, i Identifier, user auth.CurrentUser, db *sqlx.DB) error {
 	query := `INSERT INTO log (level, message, tm_user) VALUES ($1, $2, $3)`
 	id, _ := i.GetID()
 	message := action + " " + i.GetType() + ": " + i.GetAuditName() + " id: " + strconv.Itoa(id)
diff --git a/traffic_ops/traffic_ops_golang/api/shared_handlers.go b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
index 89208fa..903fa9f 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_handlers.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
@@ -220,7 +220,7 @@ func UpdateHandler(typeRef Updater, db *sqlx.DB) http.HandlerFunc {
 			return
 		}
 		//auditing here
-		InsertChangeLog(ApiChange, Updated, u, *user, db)
+		CreateChangeLog(ApiChange, Updated, u, *user, db)
 		//form response to send across the wire
 		resp := struct {
 			Response interface{} `json:"response"`
@@ -291,7 +291,7 @@ func DeleteHandler(typeRef Deleter, db *sqlx.DB) http.HandlerFunc {
 			return
 		}
 		//audit here
-		InsertChangeLog(ApiChange, Deleted, d, *user, db)
+		CreateChangeLog(ApiChange, Deleted, d, *user, db)
 		//
 		resp := struct {
 			tc.Alerts
@@ -308,7 +308,7 @@ func DeleteHandler(typeRef Deleter, db *sqlx.DB) http.HandlerFunc {
 	}
 }
 
-//this creates a handler function from the pointer to a struct implementing the Inserter interface
+//this creates a handler function from the pointer to a struct implementing the Creator interface
 //it must be immediately assigned to a local variable
 //   this generic handler encapsulates the logic for handling:
 //   *fetching the id from the path parameter
@@ -316,7 +316,7 @@ func DeleteHandler(typeRef Deleter, db *sqlx.DB) http.HandlerFunc {
 //   *decoding and validating the struct
 //   *change log entry
 //   *forming and writing the body over the wire
-func CreateHandler(typeRef Inserter, db *sqlx.DB) http.HandlerFunc {
+func CreateHandler(typeRef Creator, db *sqlx.DB) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		handleErrs := tc.GetHandleErrorsFunc(w, r)
 
@@ -326,7 +326,7 @@ func CreateHandler(typeRef Inserter, db *sqlx.DB) http.HandlerFunc {
 			handleErrs(http.StatusBadRequest, errs...)
 			return
 		}
-		i := decoded.(Inserter)
+		i := decoded.(Creator)
 		log.Debugf("%++v", i)
 		//now we have a validated local object to insert
 
@@ -351,13 +351,13 @@ func CreateHandler(typeRef Inserter, db *sqlx.DB) http.HandlerFunc {
 			}
 		}
 
-		err, errType := i.Insert(db, *user)
+		err, errType := i.Create(db, *user)
 		if err != nil {
 			tc.HandleErrorsWithType([]error{err}, errType, handleErrs)
 			return
 		}
 
-		InsertChangeLog(ApiChange, Created, i, *user, db)
+		CreateChangeLog(ApiChange, Created, i, *user, db)
 
 		resp := struct {
 			Response interface{} `json:"response"`
diff --git a/traffic_ops/traffic_ops_golang/api/shared_interfaces.go b/traffic_ops/traffic_ops_golang/api/shared_interfaces.go
index 0cd04ba..da23de5 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_interfaces.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_interfaces.go
@@ -37,8 +37,8 @@ type Identifier interface {
 	GetAuditName() string
 }
 
-type Inserter interface {
-	Insert(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType)
+type Creator interface {
+	Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType)
 	SetID(int)
 	Identifier
 	Validator
diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns.go b/traffic_ops/traffic_ops_golang/cdn/cdns.go
index 9766c28..00b99a8 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns.go
@@ -194,7 +194,7 @@ func (cdn *TOCDN) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiError
 //generic error message returned
 //The insert sql returns the id and lastUpdated values of the newly inserted cdn and have
 //to be added to the struct
-func (cdn *TOCDN) Insert(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (cdn *TOCDN) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
 	rollbackTransaction := true
 	tx, err := db.Beginx()
 	defer func() {
diff --git a/traffic_ops/traffic_ops_golang/routes.go b/traffic_ops/traffic_ops_golang/routes.go
index 4bdd5a7..4be4d4d 100644
--- a/traffic_ops/traffic_ops_golang/routes.go
+++ b/traffic_ops/traffic_ops_golang/routes.go
@@ -66,6 +66,7 @@ func Routes(d ServerData) ([]Route, http.Handler, error) {
 		{1.2, http.MethodGet, `cdns/routing$`, handlerToFunc(proxyHandler), 0, NoAuth, []Middleware{}},
 
 		{1.2, http.MethodGet, `cdns/{name}/configs/monitoring(\.json)?$`, monitoringHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+
 		//CDN generic handlers:
 		{1.3, http.MethodGet, `cdns/?(\.json)?$`, api.ReadHandler(cdn.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
 		{1.3, http.MethodGet, `cdns/{id}$`, api.ReadHandler(cdn.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
@@ -89,14 +90,18 @@ func Routes(d ServerData) ([]Route, http.Handler, error) {
 
 		//Divisions
 		{1.2, http.MethodGet, `divisions/?(\.json)?$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+		{1.3, http.MethodGet, `divisions/{id}$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
 
 		//HwInfo
 		{1.2, http.MethodGet, `hwinfo-wip/?(\.json)?$`, hwInfoHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+
 		//Parameters
 		{1.3, http.MethodGet, `parameters/?(\.json)?$`, parametersHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+
 		//Regions
 		{1.2, http.MethodGet, `regions/?(\.json)?$`, regionsHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
 		{1.2, http.MethodGet, `regions/{id}$`, regionsHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+
 		//Servers
 		// explicitly passed to legacy system until fully implemented.  Auth handled by legacy system.
 		{1.2, http.MethodGet, `servers/checks$`, handlerToFunc(proxyHandler), 0, NoAuth, []Middleware{}},

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.

[incubator-trafficcontrol] 06/23: added TO Client funcs for invoking the /divisions CRUD

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git

commit 861b873925435f55ee057b279d87ae3b70c706ad
Author: Dewayne Richardson <de...@apache.org>
AuthorDate: Wed Feb 14 13:53:26 2018 -0700

    added TO Client funcs for invoking the /divisions CRUD
---
 traffic_ops/client/division.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/traffic_ops/client/division.go b/traffic_ops/client/division.go
index cda8701..28832f9 100644
--- a/traffic_ops/client/division.go
+++ b/traffic_ops/client/division.go
@@ -101,7 +101,7 @@ func (to *Session) GetDivisionByID(id int) ([]tc.Division, ReqInf, error) {
 
 // GET a Division by the Division name
 func (to *Session) GetDivisionByName(name string) ([]tc.Division, ReqInf, error) {
-	url := fmt.Sprintf("%s/name/%s", API_v2_Divisions, name)
+	url := fmt.Sprintf("%s?name=%s", API_v2_Divisions, name)
 	resp, remoteAddr, err := to.request(http.MethodGet, url, nil)
 	reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
 	if err != nil {

-- 
To stop receiving notification emails like this one, please contact
dangogh@apache.org.