filename
stringlengths
4
198
content
stringlengths
25
939k
environment
list
variablearg
list
constarg
list
variableargjson
stringclasses
1 value
constargjson
stringlengths
2
3.9k
lang
stringclasses
3 values
constargcount
float64
0
129
variableargcount
float64
0
0
sentence
stringclasses
1 value
src/main/java/com/example/web/backend/WebAutomationException.java
package com.example.web.backend; import com.example.driver.Driver; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import java.io.File; import java.io.IOException; public class WebAutomationException extends RuntimeException{ public WebAutomationException(String message){ super(message); File scrFile = ((TakesScreenshot) Driver.webDriver).getScreenshotAs(OutputType.FILE); String filePath = "screenshots\\screenshot " + WebAutomationContext.getContextValue(ContextKeys.CASENAME) + ".png"; try { FileUtils.copyFile(scrFile, new File(filePath)); } catch (IOException e) { e.printStackTrace(); } String description = "SPRINKLE-UI WEB AUTOMATION FAILED AT STEP: " + WebAutomationContext.getContextValue(ContextKeys.STEPNAME) + " WITH EXCEPTION MESSAGE: " + message; WebAutomationContext.addContext(ContextKeys.EXCEPTION, description); WebAutomationContext.addContext(ContextKeys.SSLINK, filePath); String environment = System.getenv("ENVIRONMENT"); /* if(false && environment.equalsIgnoreCase("PROD")) { if(!JiraUtil.createIssue("RA", WebAutomationContext.getContextValue(ContextKeys.CASENAME), description, filePath, "ringadmin")){ System.out.println("COULD NOT OPEN JIRA ISSUE"); }*/ } }
[ "\"ENVIRONMENT\"" ]
[]
[ "ENVIRONMENT" ]
[]
["ENVIRONMENT"]
java
1
0
urdu_tts/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "urdu_tts.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
[]
[]
[]
[]
[]
python
0
0
randomnumber/randomnumber/wsgi.py
""" WSGI config for randomnumber project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'randomnumber.settings') application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
api/directory_watcher.py
import datetime import hashlib import os import stat import magic import pytz from django.db.models import Q from django_rq import job from PIL import Image import api.util as util from api.image_similarity import build_image_similarity_index from api.models import LongRunningJob, Photo def is_valid_media(filebuffer): try: filetype = magic.from_buffer(filebuffer, mime=True) return ( "jpeg" in filetype or "png" in filetype or "bmp" in filetype or "gif" in filetype or "heic" in filetype or "heif" in filetype ) except: util.logger.exception("An image throwed an exception") return False def calculate_hash(user, image_path): hash_md5 = hashlib.md5() with open(image_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() + str(user.id) def should_skip(filepath): if not os.getenv('SKIP_PATTERNS'): return False skip_patterns = os.getenv('SKIP_PATTERNS') skip_list = skip_patterns.split(',') skip_list = map(str.strip, skip_list) res = [ele for ele in skip_list if(ele in filepath)] return bool(res) if os.name == "Windows": def is_hidden(filepath): name = os.path.basename(os.path.abspath(filepath)) return name.startswith(".") or has_hidden_attribute(filepath) def has_hidden_attribute(filepath): try: return bool( os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN ) except: return False else: def is_hidden(filepath): return os.path.basename(filepath).startswith(".") def handle_new_image(user, image_path, job_id): try: if is_valid_media(open(image_path, "rb").read(2048)): elapsed_times = { "md5": None, "thumbnails": None, "captions": None, "image_save": None, "exif": None, "geolocation": None, "faces": None, "album_place": None, "album_date": None, "album_thing": None, "im2vec": None, } img_abs_path = image_path util.logger.info("job {}: handling image {}".format(job_id, img_abs_path)) start = datetime.datetime.now() image_hash = calculate_hash(user, image_path) elapsed = (datetime.datetime.now() - start).total_seconds() elapsed_times["md5"] = elapsed photo_exists = Photo.objects.filter( Q(image_hash=image_hash) ).exists() if not photo_exists: photo = Photo.objects.create( image_path=img_abs_path, owner=user, image_hash=image_hash, added_on=datetime.datetime.now().replace(tzinfo=pytz.utc), geolocation_json={}, ) start = datetime.datetime.now() photo._generate_thumbnail() # photo._generate_captions() photo._extract_date_time_from_exif() photo._extract_gps_from_exif() photo._geolocate_mapbox() photo._add_to_album_place() photo._extract_faces() photo._add_to_album_date() photo._add_to_album_thing() # photo._im2vec() elapsed = (datetime.datetime.now() - start).total_seconds() util.logger.info( "job {}: image processed: {}, elapsed: {}".format( job_id, img_abs_path, elapsed ) ) if photo.image_hash == "": util.logger.warning( "job {}: image hash is an empty string. File path: {}".format( job_id, photo.image_path ) ) else: util.logger.warning( "job {}: file {} exists already".format(job_id, image_path) ) except Exception as e: try: util.logger.exception( "job {}: could not load image {}. reason: {}".format( job_id, image_path, str(e) ) ) except: util.logger.exception( "job {}: could not load image {}".format(job_id, image_path) ) def rescan_image(user, image_path, job_id): try: if is_valid_media(open(image_path, "rb").read(2048)): photo = Photo.objects.filter(Q(image_path=image_path)).get() photo._generate_thumbnail() photo._extract_date_time_from_exif() except Exception as e: try: util.logger.exception( "job {}: could not load image {}. reason: {}".format( job_id, image_path, str(e) ) ) except: util.logger.exception( "job {}: could not load image {}".format(job_id, image_path) ) def walk_directory(directory, callback): for file in os.scandir(directory): fpath = os.path.join(directory, file) if not is_hidden(fpath) and not should_skip(fpath): if os.path.isdir(fpath): walk_directory(fpath, callback) else: callback.read_file(fpath) class file_counter: counter = 0 def read_file(self, path): self.counter += 1 class photo_scanner: def __init__(self, user, lrj, job_id, file_count): self.to_add_count = file_count self.job_id = job_id self.counter = 0 self.user = user self.lrj = lrj def read_file(self, path): # update progress self.counter += 1 self.lrj.result = { "progress": {"current": self.counter, "target": self.to_add_count} } self.lrj.save() # scan new or update existing image if Photo.objects.filter(image_path=path).exists(): rescan_image(self.user, path, self.job_id) else: handle_new_image(self.user, path, self.job_id) # job is currently not used, because the model.eval() doesn't execute when it is running as a job @job def scan_photos(user, job_id): if LongRunningJob.objects.filter(job_id=job_id).exists(): lrj = LongRunningJob.objects.get(job_id=job_id) lrj.started_at = datetime.datetime.now().replace(tzinfo=pytz.utc) lrj.save() else: lrj = LongRunningJob.objects.create( started_by=user, job_id=job_id, queued_at=datetime.datetime.now().replace(tzinfo=pytz.utc), started_at=datetime.datetime.now().replace(tzinfo=pytz.utc), job_type=LongRunningJob.JOB_SCAN_PHOTOS, ) lrj.save() photo_count_before = Photo.objects.count() try: fc = file_counter() # first walk and count sum of files walk_directory(user.scan_directory, fc) files_found = fc.counter ps = photo_scanner(user, lrj, job_id, files_found) walk_directory(user.scan_directory, ps) # now walk with photo-scannning util.logger.info( "Scanned {} files in : {}".format(files_found, user.scan_directory) ) build_image_similarity_index(user) except Exception: util.logger.exception("An error occured:") lrj.failed = True added_photo_count = Photo.objects.count() - photo_count_before util.logger.info("Added {} photos".format(added_photo_count)) lrj.finished = True lrj.finished_at = datetime.datetime.now().replace(tzinfo=pytz.utc) lrj.result["new_photo_count"] = added_photo_count lrj.save() return {"new_photo_count": added_photo_count, "status": lrj.failed == False}
[]
[]
[ "SKIP_PATTERNS" ]
[]
["SKIP_PATTERNS"]
python
1
0
structures/easy/glasses.go
// Copyright 2020 Iván Camilo Sanabria // // 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 // // https://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 main // hourglassSum calculate the maximum hourglass sum in the given arr. func hourglassSum(arr [][]int32) int32 { maximum := int32(-64) var i, j int var sum int32 // Iterate over rows of arr. for i = 0; i < 4; i++ { for j = 0; j < 4; j++ { // First row of the glass. sum = arr[i][j] sum += arr[i][j+1] sum += arr[i][j+2] // Second row of the glass. sum += arr[i+1][j+1] // Third row of the glass. sum += arr[i+2][j] sum += arr[i+2][j+1] sum += arr[i+2][j+2] if maximum < sum { maximum = sum } } } return maximum } // main function provided by hacker rank to execute the code on platform. To run locally uncomment the function. //func main() { // reader := bufio.NewReaderSize(os.Stdin, 1024*1024) // // stdout, err := os.Create(os.Getenv("OUTPUT_PATH")) // checkError(err) // // defer func(stdout *os.File) { // err := stdout.Close() // if err != nil { // fmt.Println("Error reading output path file.") // } // }(stdout) // // writer := bufio.NewWriterSize(stdout, 1024*1024) // // var arr [][]int32 // // for i := 0; i < 6; i++ { // arrRowTemp := strings.Split(readLine(reader), " ") // var arrRow []int32 // // for _, arrRowItem := range arrRowTemp { // arrItemTemp, err := strconv.ParseInt(arrRowItem, 10, 64) // checkError(err) // arrItem := int32(arrItemTemp) // arrRow = append(arrRow, arrItem) // } // // if len(arrRow) != 6 { // panic("Bad input") // } // // arr = append(arr, arrRow) // } // // result := hourglassSum(arr) // // _, _ = fmt.Fprintf(writer, "%d\n", result) // // _ = writer.Flush() //}
[ "\"OUTPUT_PATH\"" ]
[]
[ "OUTPUT_PATH" ]
[]
["OUTPUT_PATH"]
go
1
0
internal/parsesvcname/parsesvcname_test.go
package parsesvcname import ( "io" "io/ioutil" "os" "strings" "testing" ) // Provide a basic proto file to test that FromPaths returns the name of the // service in the file at the provided path. func TestFromPaths(t *testing.T) { protoStr := ` syntax = "proto3"; package echo; import "github.com/teamlint/baron/deftree/googlethirdparty/annotations.proto"; service BounceEcho { rpc Echo (EchoRequest) returns (EchoResponse) { option (google.api.http) = { get: "/echo" }; } } message EchoRequest { string In = 1; } message EchoResponse { string Out = 1; } ` protoDir, err := ioutil.TempDir("", "parsesvcname-test") if err != nil { t.Fatal("cannot create temp directory to store proto definition: ", err) } defer os.RemoveAll(protoDir) f, err := ioutil.TempFile(protoDir, "barontest") _, err = io.Copy(f, strings.NewReader(protoStr)) if err != nil { t.Fatal("couldn't copy contents of our proto file into the os.File: ", err) } path := f.Name() f.Close() svcname, err := FromPaths([]string{os.Getenv("GOPATH")}, []string{path}) if err != nil { t.Fatal("failed to get service name from path: ", err) } if got, want := svcname, "BounceEcho"; got != want { t.Fatalf("got != want; got = %q, want = %q", got, want) } } // Provide a basic protobuf file to FromReader to ensure it returns the service // name we expect. func TestFromReader(t *testing.T) { protoStr := ` syntax = "proto3"; package echo; import "github.com/teamlint/baron/deftree/googlethirdparty/annotations.proto"; service BounceEcho { rpc Echo (EchoRequest) returns (EchoResponse) { option (google.api.http) = { get: "/echo" }; } } message EchoRequest { string In = 1; } message EchoResponse { string Out = 1; } ` svcname, err := FromReaders([]string{os.Getenv("GOPATH")}, []io.Reader{strings.NewReader(protoStr)}) if err != nil { t.Fatal("failed to get service name from path: ", err) } if got, want := svcname, "BounceEcho"; got != want { t.Fatalf("got != want; got = %q, want = %q", got, want) } } // Ensure that passing a protobuf file that's not importing google annotations // will function properly. func TestNoAnnotations(t *testing.T) { protoStr := ` syntax = "proto3"; package echo; service BounceEcho { rpc Echo (EchoRequest) returns (EchoResponse) {} } message EchoRequest { string In = 1; } message EchoResponse { string Out = 1; } ` svcname, err := FromReaders([]string{os.Getenv("GOPATH")}, []io.Reader{strings.NewReader(protoStr)}) if err != nil { t.Fatal("failed to get service name from path: ", err) } if got, want := svcname, "BounceEcho"; got != want { t.Fatalf("got != want; got = %q, want = %q", got, want) } } // Test that having a service name which includes an underscore doesn't cause // problems. func TestUnderscoreService(t *testing.T) { protoStr := ` syntax = "proto3"; package echo; service foo_bar_test { rpc Echo (EchoRequest) returns (EchoResponse) {} } message EchoRequest { string In = 1; } message EchoResponse { string Out = 1; } ` svcname, err := FromReaders([]string{os.Getenv("GOPATH")}, []io.Reader{strings.NewReader(protoStr)}) if err != nil { t.Fatal("failed to get service name from path: ", err) } if got, want := svcname, "FooBarTest"; got != want { t.Fatalf("got != want; got = %q, want = %q", got, want) } } // Test that having a service name which starts with an underscore doesn't // cause problems. func TestLeadingUnderscoreService(t *testing.T) { protoStr := ` syntax = "proto3"; package echo; service _Foo_Bar { rpc Echo (EchoRequest) returns (EchoResponse) {} } message EchoRequest { string In = 1; } message EchoResponse { string Out = 1; } ` svcname, err := FromReaders([]string{os.Getenv("GOPATH")}, []io.Reader{strings.NewReader(protoStr)}) if err != nil { t.Fatal("failed to get service name from path: ", err) } if got, want := svcname, "XFoo_Bar"; got != want { t.Fatalf("got != want; got = %q, want = %q", got, want) } }
[ "\"GOPATH\"", "\"GOPATH\"", "\"GOPATH\"", "\"GOPATH\"", "\"GOPATH\"" ]
[]
[ "GOPATH" ]
[]
["GOPATH"]
go
1
0
node/tools/npm/utils.py
import json import os import subprocess import sys from node.tools.npm.runfiles import data_path SHRINKWRAP = 'npm-shrinkwrap.json' PUBLIC_NPM_REGISTRY_URL = "https://registry.npmjs.org" NODE_BIN_PATH = data_path('@nodejs//bin') NPM_PATH = data_path('@nodejs//bin/npm') class NodeToolsException(Exception): pass def get_dep_id(dep_name, dep_version): return '%s@%s' % (dep_name, dep_version) def get_dep_name(dep_id): assert '@' in dep_id return dep_id.rsplit('@', 1)[0] def get_dep_version(dep_id): assert '@' in dep_id return dep_id.split('@')[-1] def read_shrinkwrap(filename): with open(filename, 'r') as f: try: s = json.load(f) except ValueError as e: raise NodeToolsException( "Could not read shrinkwrap %s: %s" % (filename, e) ) return s def get_npm_registry_url(module_id): # type: (str) -> str ''' Returns the public npm registry url for module_id. npm urls look like this: https://registry.npmjs.org/rollup/-/rollup-0.41.5.tgz or this: https://registry.npmjs.org/@types/npm/-/npm-2.0.28.tgz ''' dep_name = get_dep_name(module_id) dep_name_last_part_only = dep_name.split('/')[-1] dep_version = get_dep_version(module_id) tmplStr = """ {npm_registry_url}/{dep_name}/-/{dep_name_last_part_only}-{dep_version}.tgz """ return tmplStr.format( npm_registry_url=PUBLIC_NPM_REGISTRY_URL, dep_name=dep_name, dep_name_last_part_only=dep_name_last_part_only, dep_version=dep_version, ) def run_npm(cmd, env=None, cwd=None): ''' Runs `npm`. Args: cmd: Additional args to npm. E.g. `['install']`. env: Additional env vars. Node is already added to the path. cwd: Set the working directory. ''' full_cmd = [NPM_PATH] + cmd full_env = { # Add node and npm to the path. 'PATH': NODE_BIN_PATH + ":/usr/bin:/bin", # Ignore scripts because we don't want to compile # native node modules or do anything weird. 'NPM_CONFIG_IGNORE_SCRIPTS': 'true', # Only direct dependencies will show up in the first # `node_modules` level, all transitive dependencies # will be flattened starting at the second level. # # This is needed because, when we combine different # npm_library targets, we don't want any potential # transitive dependencies to overlap. 'NPM_CONFIG_GLOBAL_STYLE': 'true', } if env: full_env = dict(full_env.items() + env.items()) if 'HTTP_PROXY' in os.environ: full_env['HTTP_PROXY'] = os.environ['HTTP_PROXY'] if 'HTTPS_PROXY' in os.environ: full_env['HTTPS_PROXY'] = os.environ['HTTPS_PROXY'] try: ret = subprocess.check_output( full_cmd, env=full_env, cwd=cwd, stderr=subprocess.STDOUT ).strip() except subprocess.CalledProcessError as e: sys.stderr.write(e.output) raise return ret
[]
[]
[ "HTTP_PROXY", "HTTPS_PROXY" ]
[]
["HTTP_PROXY", "HTTPS_PROXY"]
python
2
0
client.go
package namecheap import ( "bytes" "encoding/xml" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "strconv" "github.com/hashicorp/go-cleanhttp" ) var ( debug = os.Getenv("DEBUG") != "" ) const ( namecheapApiUrl = "https://api.namecheap.com/xml.response" sandboxApiUrl = "https://api.sandbox.namecheap.com/xml.response" ) // New returns a Client instance by reading environment variables func New() (*Client, error) { username := os.Getenv("NAMECHEAP_USERNAME") apiuser := os.Getenv("NAMECHEAP_API_USER") token := os.Getenv("NAMECHEAP_TOKEN") ip := os.Getenv("NAMECHEAP_IP") // TODO(adam): attempt local read? sbx := os.Getenv("NAMECHEAP_USE_SANDBOX") useSbx := sbx != "" && sbx != "false" return NewClient(username, apiuser, token, ip, useSbx) } // NewClient creates a Client instance from the provided configuration // typically users call New() with environment variables set instead. func NewClient(username string, apiuser string, token string, ip string, useSandbox bool) (*Client, error) { if username == "" || apiuser == "" || token == "" || ip == "" { return nil, fmt.Errorf("ERROR: missing configuration - username=%q, apiuser=%q, token=%d, ip=%q", username, apiuser, len(token), ip) } // TODO(adam): parse `ip`, ipv4 only? is ipv6 allowed? client := Client{ Token: token, ApiUser: apiuser, Username: username, Ip: ip, URL: namecheapApiUrl, Http: cleanhttp.DefaultClient(), } if useSandbox { client.URL = sandboxApiUrl } return &client, nil } // Client provides a client to the Namecheap API type Client struct { // Access Token Token string // ApiUser ApiUser string // TODO(adam): What's this for? difference with Username? // Username Username string // URL to the DO API to use URL string // IP that is whitelisted Ip string // HttpClient is the client to use. A client with // default values will be used if not provided. Http *http.Client } // NewRequest creates a new request with the params func (c *Client) NewRequest(body map[string]string) (*http.Request, error) { u, err := url.Parse(c.URL) if err != nil { return nil, fmt.Errorf("Error parsing base URL: %s", err) } body["Username"] = c.Username body["ApiKey"] = c.Token body["ApiUser"] = c.ApiUser body["ClientIp"] = c.Ip rBody := c.encodeBody(body) if debug { fmt.Printf("DEBUG: %q\n", string(rBody)) } if err != nil { return nil, fmt.Errorf("Error encoding request body: %s", err) } // Build the request req, err := http.NewRequest("POST", u.String(), bytes.NewBufferString(rBody)) if err != nil { return nil, fmt.Errorf("Error creating request: %s", err) } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Content-Length", strconv.Itoa(len(rBody))) return req, nil } func (c *Client) decode(reader io.Reader, obj interface{}) error { if debug { bs, err := ioutil.ReadAll(reader) if err != nil { return err } fmt.Printf("DEBUG: %q\n", string(bs)) reader = bytes.NewReader(bs) // refill `reader` } decoder := xml.NewDecoder(reader) err := decoder.Decode(&obj) if err != nil { return err } return nil } func (c *Client) encodeBody(body map[string]string) string { data := url.Values{} for key, val := range body { data.Set(key, val) } return data.Encode() }
[ "\"DEBUG\"", "\"NAMECHEAP_USERNAME\"", "\"NAMECHEAP_API_USER\"", "\"NAMECHEAP_TOKEN\"", "\"NAMECHEAP_IP\"", "\"NAMECHEAP_USE_SANDBOX\"" ]
[]
[ "NAMECHEAP_IP", "NAMECHEAP_TOKEN", "NAMECHEAP_USE_SANDBOX", "DEBUG", "NAMECHEAP_API_USER", "NAMECHEAP_USERNAME" ]
[]
["NAMECHEAP_IP", "NAMECHEAP_TOKEN", "NAMECHEAP_USE_SANDBOX", "DEBUG", "NAMECHEAP_API_USER", "NAMECHEAP_USERNAME"]
go
6
0
measure_response_matrix/core/pco_gui.py
__author__ = 'Polychronis Patapis' from PyQt4 import QtCore, QtGui from core.pco_definitions import PixelFly from threading import Thread import os, time, sys, pickle import pyqtgraph as pg from astropy.io import fits import numpy as np import matlab.engine from queue import Empty import pygame, os, time, pickle import win32api class CameraWidget(QtGui.QWidget): """ The CameraWidget class provides the user interface for the PCO PixelFly camera. It bases the connection to the camera through the pyPCOPixelFly.pco_definitions module. The basic framework of the class is PyQt4 an wrapper of the Qt framework and the pyqtgraph (url-here) module is essential for the use of this user interface. Dependencies: -- SC2_Cam.dll : the dynamic library that interfaces the camera hardware (please contain it in the same folder as the file). -- (Optional) App.ico : the application icon of pco (also needs to be in the same directory). Basic usage: Shortcuts: -- Ctrl + Q : Quits application -- Ctrl + R :Resets original scale to image Contact: Polychronis Patapis, [email protected] """ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.path = os.path.dirname(os.path.realpath("__file__")) self.save_dir = self.path self.camera = PixelFly(self.path) self.connected = False self.alive = False self.live_view_bool = False self.u = 1 self.time_unit_dict = dict(us=1, ms=2) self.save_settings = self.load_settings() # set background color to dark gray self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), QtCore.Qt.darkGray) self.setPalette(p) def create_gui(self, MainWindow): """ Creates user interface. Initializes all widgets of the application. :param MainWindow: The Main Application Window -> QtGui.MainWindow() :return: """ # central widget of the Main Window self.central_widget = QtGui.QWidget(MainWindow) # set background color to dark gray self.central_widget.setAutoFillBackground(True) p = self.central_widget.palette() p.setColor(self.central_widget.backgroundRole(), QtCore.Qt.darkGray) self.central_widget.setPalette(p) # Grid layout to place all widgets self.widget_layout = QtGui.QGridLayout() # Graphics Layout Widget to put the image and histogram self.gw = pg.GraphicsLayoutWidget() # make margins around image items zero self.gw.ci.layout.setContentsMargins(0,0,0,0) # Graphics Layout Widget to put the crosscut curve plot self.gw_crosscut = pg.GraphicsLayoutWidget() MainWindow.setCentralWidget(self.central_widget) # the controls_layout contains all controls of the camera (eg. connection, exposure time, recording..) self.controls_layout = QtGui.QGridLayout() self.controls_layout.setSpacing(20) # set spacing between widgets to 20 pixels # indicators_layout contains all indicators of the camera feed # The maximum count, the average count in the ROI region, buttons for ROI and crosscut, as well as # controls of the gray values if the image. self.indicators_layout = QtGui.QGridLayout() # ============================================================================================================== # CONTROL BUTTONS # ============================================================================================================== # Button to connect to the camera. Will turn red and display disconnect if it successfully connects. self.ConnectBtn = QtGui.QPushButton('CONNECT') self.controls_layout.addWidget(self.ConnectBtn, 0, 0) # layout for exposure time controls self.exsposure_time_layout = QtGui.QGridLayout() self.controls_layout.addItem(self.exsposure_time_layout, 2, 0, 4, 5) # 6 preset values of exposure time. They will be saved and reloaded through a python pickle file. preset_values = self.save_settings['exposure times'] time_label1 = QtGui.QLabel("1") time_label2 = QtGui.QLabel("2") time_label3 = QtGui.QLabel("3") time_label4 = QtGui.QLabel("4") time_label5 = QtGui.QLabel("5") time_label6 = QtGui.QLabel("6") self.exp_time1 = QtGui.QPushButton(preset_values[0]) self.exp_time2 = QtGui.QPushButton(preset_values[1]) self.exp_time3 = QtGui.QPushButton(preset_values[2]) self.exp_time4 = QtGui.QPushButton(preset_values[3]) self.exp_time5 = QtGui.QPushButton(preset_values[4]) self.exp_time6 = QtGui.QPushButton(preset_values[5]) exposure_frame_title = QtGui.QLabel("Exposure time controls") self.exsposure_time_layout.addWidget(exposure_frame_title, 0, 0, 1, 3) self.exsposure_time_layout.addWidget(time_label1, 1, 0, 1, 1) self.exsposure_time_layout.addWidget(time_label2, 2, 0, 1, 1) self.exsposure_time_layout.addWidget(time_label3, 3, 0, 1, 1) self.exsposure_time_layout.addWidget(time_label4, 1, 2, 1, 1) self.exsposure_time_layout.addWidget(time_label5, 2, 2, 1, 1) self.exsposure_time_layout.addWidget(time_label6, 3, 2, 1, 1) self.exsposure_time_layout.addWidget(self.exp_time1, 1,1, 1, 1) self.exsposure_time_layout.addWidget(self.exp_time2, 2,1, 1, 1) self.exsposure_time_layout.addWidget(self.exp_time3, 3,1, 1, 1) self.exsposure_time_layout.addWidget(self.exp_time4, 1,3, 1, 1) self.exsposure_time_layout.addWidget(self.exp_time5, 2,3, 1, 1) self.exsposure_time_layout.addWidget(self.exp_time6, 3,3, 1, 1) # Edit line widget to input exposure time. It accepts us and ms units with the option of setting a float for # the ms time unit (eg. 1.5 ms) self.exp_time_in = QtGui.QLineEdit() # time units list self.time_units = QtGui.QComboBox() # save the time in one of the preset values. self.save_time = QtGui.QComboBox() self.exsposure_time_layout.addWidget(self.exp_time_in, 4, 2, 1, 3) self.exsposure_time_layout.addWidget(self.time_units, 4, 5, 1, 2) self.exsposure_time_layout.addWidget(self.save_time, 4, 0, 1, 2) # layout to host the recording controls self.recording_layout = QtGui.QGridLayout() self.controls_layout.addItem(self.recording_layout, 6, 0, 3, 3) recording_label = QtGui.QLabel("Recording controls") self.recording_layout.addWidget(recording_label, 0, 0, 1, 3) # Live button puts the camera in live view. Has to be stopped before exiting. self.LiveBtn = QtGui.QPushButton('LIVE') # Records the specified number of frames and lets the user name the file while adding 000x at the end # of the file name in FITS data format. self.RecordBtn = QtGui.QPushButton('RECORD') # stops live view/recording and disarms the camera self.StopBtn = QtGui.QPushButton('STOP') # Label for number of frames to save frame_lab = QtGui.QLabel('# frames to record:') # Edit line that accepts integers of the number of frames to save. self.FramesLab = QtGui.QLineEdit() self.recording_layout.addWidget(self.LiveBtn, 1, 0, 1, 1) self.recording_layout.addWidget(self.RecordBtn, 1, 1, 1, 1) #self.recording_layout.addWidget(self.StopBtn, 2, 0) self.recording_layout.addWidget(frame_lab, 2, 0, 1, 1) self.recording_layout.addWidget(self.FramesLab, 2, 1) # Callbacks for all the control buttons self.exp_time1.clicked.connect(self.exp_time_callback) self.exp_time2.clicked.connect(self.exp_time_callback) self.exp_time3.clicked.connect(self.exp_time_callback) self.exp_time4.clicked.connect(self.exp_time_callback) self.exp_time5.clicked.connect(self.exp_time_callback) self.exp_time6.released.connect(self.exp_time_callback) self.exp_time_list = [self.exp_time1, self.exp_time2, self.exp_time3, self.exp_time4, self.exp_time5, self.exp_time6] # Add list options for time unit and save buttons. self.time_units.addItem("us") self.time_units.addItem("ms") self.time_units.activated[str].connect(self.onActivatedUnits) self.save_time.addItem("Save in") self.save_time.addItem("1") self.save_time.addItem("2") self.save_time.addItem("3") self.save_time.addItem("4") self.save_time.addItem("5") self.save_time.addItem("6") self.save_time.activated[str].connect(self.onActivatedSave) # Connect Enter/Return key press with callback for setting the exposure time. self.exp_time_in.returnPressed.connect(self.onReturnPress) # Connect callbacks for connect, live and stop buttons self.ConnectBtn.clicked.connect(self.connect_camera) self.ConnectBtn.setStyleSheet("background-color: darkCyan") self.FramesLab.setText('20') self.LiveBtn.clicked.connect(self.live_callback) #self.StopBtn.clicked.connect(self.stop_callback) self.RecordBtn.clicked.connect(self.record_callback) # layout to host the response matrix m self.ReponseMatrix_layout = QtGui.QGridLayout() self.controls_layout.addItem(self.ReponseMatrix_layout, 15, 0, 3, 3) # to start DM self.openDM_Btn = QtGui.QPushButton('open DM') # for response matrix self.ReponseMatrix_Btn = QtGui.QPushButton('RESPONSE MATRIX') # to close the DM after measurement self.closeDM_Btn = QtGui.QPushButton('close DM') # for the Zernike coefficient Enter_ZAmplitude = QtGui.QLabel("Amplitude:") self.Zernike_coef = QtGui.QLineEdit() self.Zernike_coef.setText("5") self.ReponseMatrix_layout.addWidget(Enter_ZAmplitude, 1, 0) self.ReponseMatrix_layout.addWidget(self.Zernike_coef, 1, 1) self.ReponseMatrix_layout.addWidget(self.ReponseMatrix_Btn, 3, 0) self.ReponseMatrix_layout.addWidget(self.closeDM_Btn, 2, 1) self.ReponseMatrix_layout.addWidget(self.openDM_Btn, 2, 0) self.ReponseMatrix_Btn.clicked.connect(self.Measure_ResponseMatrix) self.openDM_Btn.clicked.connect(self.open_DM) self.closeDM_Btn.clicked.connect(self.close_DM) # layout to host the SLM self.SLM_layout = QtGui.QGridLayout() self.controls_layout.addItem(self.SLM_layout, 10, 0, 3, 3) #to start DM self.activateSLM_Btn = QtGui.QPushButton('Initialize SLM') # to close the DM after measurement # self.closeSLM_Btn = QtGui.QPushButton('close SLM') # to create the phase map #self.createSLM_Btn = QtGui.QPushButton('create') # for the Zernike coefficient Enter_IoverD = QtGui.QLabel("file:") #self.Enter_IoverD .setText("D:\Xin LU\\real response matrix\\11X11\\Phase_shift_") self.file_address = QtGui.QLineEdit() self.file_address .setText("D:\Xin LU\\real response matrix\\9X9\\phase13_") self.SLM_layout.addWidget(Enter_IoverD, 1, 0) self.SLM_layout.addWidget(self.file_address , 1, 1) self.SLM_layout.addWidget(self.activateSLM_Btn, 2, 0) self.activateSLM_Btn.clicked.connect(self.activate_SLM) #self.closeSLM_Btn.clicked.connect(self.close_SLM) # ============================================================================================================== # IMAGE OPTIONS AND HANDLES # ============================================================================================================== # vb is a viewbox that contains the image item. self.vb = pg.ViewBox() # add the view box to the graphics layout self.gw.addItem(self.vb) # set the aspect while scaling to be locked, i.e. both axis scale the same. self.vb.setAspectLocked(lock=True, ratio=1) # invert Y axis -> PyQt <-> Numpy arrays convention self.vb.invertY() # Image Item is the image displaying item. Has a lot of options and the user can zoom in/out by pressing the # right mouse button and moving the mouse up/down. Furthermore by going over the image with the mouse will # indicate the coordinates and value. self.image = pg.ImageItem() self.vb.addItem(self.image) # Histogram of the displayed image. User can move the histogram axis and the gray values. self.hist = pg.HistogramLUTItem(self.image, fillHistogram=False) self.gw.addItem(self.hist) # initialize image container variable self.im = np.zeros((1392, 1040)) # set image to display self.image.setImage(self.im) # set initial gray levels self.image.setLevels([200, 16383]) self.hist.setHistogramRange(200, 16383) # Region Of Interest(ROI) widget that allows user to define a rectangle of tje image and the average count # within this will be displayed. #self.save_settings['ROI position']= () self.roi = pg.ROI(pos=self.save_settings['ROI position'], size=self.save_settings['ROI size']) self.roi.addScaleHandle([1, 1], [0, 0]) self.roi.alive = False self.vb.addItem(self.roi) self.roi.hide() # User can define line and place it on the image and the values profile will be plotted on the crosscut # graphics layout. self.line_roi = pg.LineSegmentROI([[680, 520], [720, 520]], pen='r') self.vb.addItem(self.line_roi) self.line_roi.hide() self.line_roi.alive = False # plot item to contain the crosscut curve crosscut_plot = pg.PlotItem() # crosscut curve that plot the data of the line self.crosscut_curve = pg.PlotCurveItem() self.gw_crosscut.addItem(crosscut_plot) crosscut_plot.addItem(self.crosscut_curve) self.gw_crosscut.hide() self.gw_crosscut.setFixedWidth(800) self.gw_crosscut.setFixedHeight(200) # make viewbox accept mouse hover events self.vb.acceptHoverEvents() # connect mouse moving event to callback self.vb.scene().sigMouseMoved.connect(self.mouseMoved) self.x, self.y = 0, 0 # mouse position # connect Ctrl + R key sequence to resetting the image to its original scale shortcut = QtGui.QShortcut(QtGui.QKeySequence('Ctrl+R'), MainWindow) shortcut.activated.connect(self.refresh_image) reset_btn = QtGui.QPushButton('Reset zoom') reset_btn.clicked.connect(self.refresh_image) # checkbox enabling log scale self.log_scale = QtGui.QCheckBox("Log scale") self.log_scale.stateChanged.connect(self.log_scale_callback) self.widget_layout.addWidget(self.gw, 0, 0, 6, 8) self.widget_layout.addWidget(self.gw_crosscut, 6, 3, 2, 6) self.widget_layout.addItem(self.controls_layout, 1, 8) self.widget_layout.addItem(self.indicators_layout, 7, 0, 2, 6) self.indicators_layout.addWidget(reset_btn, 2, 6, 1, 1) self.indicators_layout.addWidget(self.log_scale, 2, 7, 1, 1) # Indicator showing maxvalue of image being displayed self.max_indicator_lab = QtGui.QLabel('Max value') font = QtGui.QFont("Calibri", 18) self.max_indicator_lab.setFont(font) self.indicators_layout.addWidget(self.max_indicator_lab, 0,0,1,1) self.max_indicator = QtGui.QLabel(str(np.max(self.im))) self.max_indicator.setFont(font) self.indicators_layout.addWidget(self.max_indicator, 0,1,1,1) # Indicator showing average value within roi if it's selected self.roi_indicator = QtGui.QLabel('-') self.roi_indicator.setFont(QtGui.QFont("Calibri", 18)) roi_indicator_lab = QtGui.QLabel('ROI average counts:') roi_indicator_lab.setFont(QtGui.QFont("Calibri", 18)) self.indicators_layout.addWidget(roi_indicator_lab, 1, 0, 1, 1) self.indicators_layout.addWidget(self.roi_indicator, 1, 1, 1, 1) # Edit widget that allow setting the gray-levels self.gray_max = 16383 self.gray_min = 200 self.gray_max_edit = QtGui.QLineEdit(str(self.gray_max)) self.gray_min_edit = QtGui.QLineEdit(str(self.gray_min)) self.gray_min_lab = QtGui.QLabel('Min:') self.gray_max_lab = QtGui.QLabel('Max:') self.gray_min_edit.returnPressed.connect(self.set_gray_min) self.gray_max_edit.returnPressed.connect(self.set_gray_max) self.indicators_layout.addWidget(self.gray_min_lab, 2, 2, 1, 1) self.indicators_layout.addWidget(self.gray_max_lab, 2, 4, 1, 1) self.indicators_layout.addWidget(self.gray_min_edit, 2, 3, 1, 1) self.indicators_layout.addWidget(self.gray_max_edit, 2, 5, 1, 1) # Buttons for ROI and crosscut line roi_button = QtGui.QPushButton('ROI') crosscut_button = QtGui.QPushButton('Crosscut') self.indicators_layout.addWidget(roi_button, 2, 0, 1, 1) self.indicators_layout.addWidget(crosscut_button, 2, 1, 1, 1) roi_button.clicked.connect(self.roi_clicked) crosscut_button.clicked.connect(self.crosscut_clicked) ######################################### self.central_widget.setLayout(self.widget_layout) # ============================================================================================================== # MENU BAR # ============================================================================================================== self.menubar = QtGui.QMenuBar(MainWindow) #self.menubar.setGeometry(QtCore.QRect(0, 0, 1027, 35)) filemenu = self.menubar.addMenu('&File') exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.triggered.connect(self.closeEvent) filemenu.addAction(exitAction) MainWindow.setMenuBar(self.menubar) # ============================================================================================================== # STATUS BAR # ============================================================================================================== self.statusbar = QtGui.QStatusBar(MainWindow) font2 = QtGui.QFont("Calibri", 15) #self.statusbar.setGeometry(QtCore.QRect(0, 600, 1027, 35)) self.statusbar.setStyleSheet("background-color: darkCyan") self.connection_status_lab = QtGui.QLabel('Connection status: ') self.connection_status_lab.setFont(font2) self.connection_status = QtGui.QLabel('Disconnected ') self.connection_status.setFont(font2) self.statusbar.addPermanentWidget(self.connection_status_lab) self.statusbar.addPermanentWidget(self.connection_status) self.display_status_lab = QtGui.QLabel('Display status: ') self.display_status_lab.setFont(font2) self.display_status = QtGui.QLabel('Idle ') self.display_status.setFont(font2) self.statusbar.addPermanentWidget(self.display_status_lab) self.statusbar.addPermanentWidget(self.display_status) self.measurement_status_lab = QtGui.QLabel('Measurement status: ') self.measurement_status_lab.setFont(font2) self.measurement_status = QtGui.QLabel(' - ') self.measurement_status.setFont(font2) self.statusbar.addPermanentWidget(self.measurement_status_lab) self.statusbar.addPermanentWidget(self.measurement_status) self.mouse_pos_lab = QtGui.QLabel('Mouse position: ') self.mouse_pos_lab.setFont(font2) self.mouse_pos = QtGui.QLabel(' - ') self.mouse_pos.setFont(font2) self.statusbar.addPermanentWidget(self.mouse_pos_lab) self.statusbar.addPermanentWidget(self.mouse_pos) MainWindow.setStatusBar(self.statusbar) def log_scale_callback(self): if self.log_scale.isChecked(): self.image.setLevels([np.log(200), np.log(16383)]) self.hist.setHistogramRange(np.log(200), np.log(16383)) else: self.image.setLevels([200, 16383]) self.hist.setHistogramRange(200, 16383) return def refresh_image(self): """ Shortcut callback. If Ctrl+R is pressed the image scales back to its original range :return: """ self.vb.autoRange() self.image.update() return def load_settings(self): """ Load settings from previous session stored in gui_settings.p :return: """ fname = self.path + '\\pco_settings.p' if os.path.isfile(fname): return pickle.load(open(fname, 'rb')) else: sets = {'ROI position': [696, 520], 'ROI size': 50, 'line position': [[10, 64], [120, 64]], 'exposure times': ['500 us', '800 us', '1 ms', '10 ms', '50 ms', '100 ms']} return sets def save_settings_return(self): """ Save settings before exiting application :return: """ fname = self.path + '\\pco_settings.p' times = [] for btn in self.exp_time_list: times.append(btn.text()) self.save_settings['exposure times'] = times self.save_settings['ROI position'] = self.roi.pos() self.save_settings['ROI size'] = self.roi.size() pickle.dump(self.save_settings, open( fname, "wb" ) ) return def roi_clicked(self): """ Callback to press of the ROI button. A rectangular roi will appear on the image corner. If active the roi will disappear. :return: """ if self.roi.alive: self.roi.alive = False self.roi_indicator.setText('-') self.roi.hide() else: self.roi.alive = True self.roi.show() return def crosscut_clicked(self): """ Callback to press of the line crosscut button. A line roi will appear on the image corner. If active the roi will disappear. The crosscut curve will also appear. :return: """ if self.line_roi.alive: self.line_roi.alive = False self.gw_crosscut.hide() self.line_roi.hide() else: self.line_roi.alive = True self.gw_crosscut.show() self.line_roi.show() return def mouseMoved(self, event): """ Mouse move callback. It displays the position and value of the mouse on the image on the statusbar, in the right corner. :param event: Mouse move event :return: """ point = self.image.mapFromScene(event) self.x = int(point.x()) self.y = int(point.y()) # return if position out of image bounds if self.x < 0 or self.y < 0 or self.x > 1392 or self.y > 1040: return try: val = int(self.im[self.x, self.y]) self.mouse_pos.setText('%i , %i : %i'%(self.x, self.y, val)) except: pass return def roi_value(self): """ Get data from ROI region and calculate average. The value will be displayed in the roi indicator label. :return: """ data = self.roi.getArrayRegion(self.im, self.image) data_a, data_m, data_std = int(np.average(data)), int(np.max(data)), int(np.std(data)) self.roi_indicator.setText('%i, Max: %i, STD: %i'%(data_a, data_m, data_std)) return def line_roi_value(self): """ Get data from line crosscut and plot them in the crosscut curve. :return: """ data = self.line_roi.getArrayRegion(self.im, self.image) x_data = np.array(range(len(data))) self.crosscut_curve.setData(x_data, data) return def set_gray_max(self): """ Set max value of graylevel. For the 14bit image the value is held up to 16383 counts. :return: """ val = self.gray_max_edit.text() try: self.gray_max = int(val) if self.gray_max > 16383: self.gray_max = 16383 self.gray_max_edit.setText('16383') self.image.setLevels([self.gray_min, self.gray_max]) self.hist.setHistogramRange(self.gray_min, self.gray_max) except ValueError: pass return def set_gray_min(self): """ Set min value of graylevel. For the 14bit image the value is held down to 0 counts. :return: """ val = self.gray_min_edit.text() try: self.gray_min = int(val) if self.gray_min < 0: self.gray_min = 0 self.gray_min_edit.setText('0') self.image.setLevels([self.gray_min, self.gray_max]) self.hist.setHistogramRange(self.gray_min, self.gray_max) except ValueError: pass return def closeEvent(self, event): """ Callback when exiting application. Ensures that camera is disconnected smoothly. :return: """ if self.live_view_bool or self.alive: self.stop_callback() if self.connected: self.connect_camera() self.save_settings_return() QtGui.QApplication.closeAllWindows() QtGui.QApplication.instance().quit() return def onActivatedUnits(self, text): self.u = self.time_unit_dict[text] return def onActivatedSave(self, text): if text == "Save in": return which = int(text[-1])-1 what = str(self.t) + ' ' + self.time_units.currentText() self.exp_time_list[which].setText(what) return def onReturnPress(self): text = self.exp_time_in.text() t, u = 0, 0 try: if '.' in text or ',' in text and self.u == 2: t = int(float(text)*1000) u = 1 self.t = float(text) else: self.t = int(text) t = self.t u = self.u self.camera.exposure_time(t, u) except ValueError: pass return def connect_camera(self): """ Connect to camera. If camera connection returns error report it and set connected status to False. :return: """ if self.connected: err = self.camera.close_camera() self.connected = False self.ConnectBtn.setText('CONNECT') self.ConnectBtn.setStyleSheet("background-color: darkCyan") self.connection_status.setText('Disconnected') else: err = self.camera.open_camera() if not err: self.connection_status.setText('Error with connection') return self.connected = True self.ConnectBtn.setText('DISCONNECT') self.ConnectBtn.setStyleSheet("background-color: green") self.connection_status.setText('Connected') try: t, u = self.camera.get_exposure_time() self.exp_time_in.setText(str(t)) index = self.time_units.findText(u) if index >= 0: self.u = self.time_unit_dict[u] self.time_units.setCurrentIndex(index) except: pass return def exp_time_callback(self): """ Set exposure time :param event: button press event :return: """ which = self.sender().text() t, unit = which.split(sep=' ') unit_initial = unit try: if ('.' in t) or (',' in t) and (unit == 'ms'): self.t = int(float(t)*1000) unit = 'us' else: self.t = int(t) unit = self.time_unit_dict[unit] self.camera.exposure_time(self.t, unit) self.u = self.time_unit_dict[unit_initial] self.exp_time_in.setText(str(t)) index = self.time_units.findText(unit_initial) if index >= 0: self.time_units.setCurrentIndex(index) except: pass return def live_callback(self): """ Starts live view thread :return: """ if self.connected: if self.alive: self.stop_callback() self.LiveBtn.setStyleSheet('background-color: lightGray') self.LiveBtn.setChecked(False) else: self.alive = True self.LiveBtn.setStyleSheet('background-color: darkCyan') self.live_thread = Thread(target=self.live_thread_callback) self.live_thread.setDaemon(True) self.live_thread.start() QtCore.QTimer.singleShot(500, self.update_image) else: self.display_status.setText('Error with live display') return def live_thread_callback(self): """ Callback for thread that read images from buffer :return: """ try: # Arm camera self.camera.arm_camera() print('Camera armed') # Set recording status to 1 self.camera.start_recording() # Allocate buffers, default=2 buffers self.camera.allocate_buffer(3) self.camera._prepare_to_record_to_memory() self.display_status.setText('Live view.') self.record_live_thread = Thread(target=self.camera.record_to_memory_2) print('record thread created') self.record_live_thread.setDaemon(True) self.record_live_thread.start() print('record thread started') self.live_view_bool = True """ Remember to manage all exceptions here. Look it up in PixelFly() class """ except: self.stop_callback() return def open_DM(self): """ open DM for the response matrix measurement if self.driver_info['UBS_pointer']<0 , keeping doing so until it is >0 :return: """ self.eng = matlab.engine.start_matlab() # start the DM (self.error_code, self.driver_info) = self.eng.openDM(6.0, nargout=2) print(self.driver_info) if self.error_code != 0: print('DM error') self.eng.quit() elif self.driver_info['USB_pointer'] <= 0: print('USB_pointer is invalid!!') self.eng.quit() def activate_SLM(self): # get path that file is saved in self.path = os.path.dirname(os.path.realpath("__file__")) # find connected screens screens = win32api.EnumDisplayMonitors() if len(screens) < 2: raise UserWarning('No second screen connected') self.hdc = screens[1][0] # handle of second screen PYHANDLE self.dim = screens[1][2] # screen dimensions self.left = self.dim[0] self.top = self.dim[1] self.right = self.dim[2] self.bottom = self.dim[3] self.width = abs(self.right - self.left) self.height = abs(self.bottom - self.top) if self.width == 1024: self.SLM_type = "LC-2012" else: self.SLM_type = "Pluto" self.size = (self.width, self.height) self.dimensions = (self.width, self.height, 3) # set Windows ENVIRONMENTAL VARIABLE of SDL window position to the top-left corner # of the second screen os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (self.left, self.top) pygame.display.init() self.screen = pygame.display.set_mode(self.size) # create surface object self.surface = pygame.surfarray.make_surface(np.zeros(self.dimensions, dtype=np.uint8)) self.screen.blit(self.surface, (0, 0)) pygame.display.flip() # read generated phase map self.SLM_map = [] for index in range(4): file_name = self.file_address.text()+str(index)+'.fits' self.SLM_map.append(self.import_phase_map(file_name)) def import_phase_map(self, file): """ Imports an phase map stored in a file and saves it in an numpy array for use on the SLM :param file: A .txt or .fits file of a phase map :return: write an 8bit array of the correct dimensions in maps dict """ hdu = fits.open(file) p = hdu[0].data m = np.zeros((self.width, self.height, 3), dtype=np.uint8) m[:, :, 0] = p m[:, :, 1] = p m[:, :, 2] = p return m def draw(self, p): """ Draw array onto second screen. :param p: p is an uint8 numpy array with the correct dimensions :return: """ surface = pygame.surfarray.make_surface(p) self.screen.blit(surface, (0, 0)) pygame.display.flip() return def update_image(self): """ Takes images from camera queue and displays them. If roi or crosscut is enabled, it updates the respective values/plot. The consumer loop works using the QtCore.QTimer.singleShot() method, that fires the function every x ms until it is interrupted. :return: """ if not self.alive and (not self.camera.armed): if self.live_view_bool: self.live_view_bool = False time.sleep(0.1) self.record_live_thread.join() self.live_thread.join() del self.record_live_thread del self.live_thread self.display_status.setText('Idle') return try: # get newest frame from queue. Transpose it so that is fits the coordinates convention im = self.camera.q.get().T # check for log scale display if self.log_scale.isChecked(): self.im = np.log(im) else: self.im = im try: # get max value from queue max_val = self.camera.q_m.get() self.max_indicator.setText(str(max_val)) except Empty: pass # set new image data, with options autoLevels=False so that it doesn't change the grayvalues # autoRange=False so that it stays at the zoom level we want and autoHistogram=False so that it does # not interfere with the axis of the histogram self.image.setImage(self.im, autoLevels=False, autoRange=False, autoHistogramRange=False, autoDownsample=True) # if roi button is clicked if self.roi.alive: self.roi_value() # if crosscut line is clicked if self.line_roi.alive: self.line_roi_value() # mouse position value update if 0 <= self.x <= 1392 and 0 <= self.y <= 1040: val = im[self.x, self.y] self.mouse_pos.setText('%i , %i : %.1f' % (self.x, self.y, val)) # update image. Don't know if this is necessary.. self.image.update() except Empty: pass # Run single shot timer again QtCore.QTimer.singleShot(20, self.update_image) def Measure_ResponseMatrix(self): """ Record the images of the first 15 Zernike terms with Zernike_coefficient = self.Zernike_coef :return: """ if not self.connected: return # check if camera had already been armed if self.alive and self.live_view_bool: try: self.live_view_bool = False self.camera.live = False # stop loop that is producing frames #time.sleep(1) self.record_live_thread.join() self.live_thread.join() del self.record_live_thread del self.live_thread except: pass elif not self.alive: self.alive = True self.camera.arm_camera() self.camera.start_recording() self.camera.allocate_buffer() self.camera._prepare_to_record_to_memory() self.alive = True else: pass try: num_of_frames = int(self.FramesLab.text()) self.Z_coef = int(self.Zernike_coef.text()) except ValueError: return # probably there is a conflict between the camera and DM USB connections, so the 'USB_pointer' in the self.driver_info # is negative, we need to read the self.driver_info from DM_GUI #self.driver_info = np.load('current_DMdriver_info.npy').item() RM_filename = QtGui.QFileDialog.getSaveFileName(self, 'Save as..', self.save_dir) self.save_dir = os.path.dirname(RM_filename) for Zernike_term in range(1,28): # 11 for first 10 Zernike terms #Zernike_coefficient = [0] * 15 # initialize coefficient for the first 15 Zernike terms Zernike_coefficient =[0, 1.00143624463888, -51.5249359080095, -21.9775999768718, 0.717759222249538, 15.9050351311175, 27.0075244428022, -10.7205195257083, -2.01254461443215, -7.52510423390856, 10.8157068054894, -3.02134384531165, 8.75467126995794, -4.83968407700889, 10.0627952531622, 8.69361225696698, -0.00569977528614984, -0.147583443076208, -2.30484489161088, 0.982991691361985, -0.857744799462948, 4.92455332433157, -10.3405736785842, -0.702115323493294, 0.256143402391469, 2.20035061964973, 7.63689639452587, -2.43586089370370] # # for 11X11 # initialize coefficient for the first 15 Zernike terms to get a flat image for 11X11 pupil Zernike_coefficient[Zernike_term] = Zernike_coefficient[Zernike_term] - 25 for index_loop in range(0,9): Zernike_coefficient[Zernike_term] = Zernike_coefficient[Zernike_term] + self.Z_coef vars_str = str(-20+abs(index_loop * self.Z_coef)) if -1500 <= sum(Zernike_coefficient) <= 1500: Zernike_coefficientM = matlab.double(Zernike_coefficient) (Z_shape, Zvol_map) = self.eng.apply_zernike(Zernike_coefficientM, nargout=2) Zvol_map = [one for [one] in Zvol_map] Zvol_map_Mat = matlab.double(Zvol_map) self.error_code = self.eng.updateDM(self.driver_info, Zvol_map_Mat) if self.error_code == 0: time.sleep(0.1) else: return for phase_shift in range(0,2): # phase_shift <4 for phase shifting method # phase_shift <2 for standard Zernike method self.draw(self.SLM_map[phase_shift]) time.sleep(0.1) hdu = fits.HDUList() # initialize fits object record_data = [] record_data = self.camera.record_to_memory(num_of_frames) / 4 # :4 to make it 14 bit if record_data == []: self.stop_callback() return hdu.append(fits.PrimaryHDU(data=record_data)) # other header details will come in here hdu[0].header['EXPTIME'] = "%i %s" % (self.t, self.time_units.currentText()) if index_loop<4: hdu.writeto(RM_filename +'N'+ vars_str[1:]+'_Z'+ str(Zernike_term+1) + '_' + str(phase_shift) + 'Pi.fits') else: hdu.writeto(RM_filename + vars_str + '_Z' + str(Zernike_term+1) + '_' + str(phase_shift) + 'Pi.fits') self.stop_callback() print('DONE!!!') return None def close_DM(self): """ close DM after the response Matrix measurement """ if self.driver_info != None: self.error_code = self.eng.closeDM(self.driver_info) self.eng.quit() def record_callback(self): """ Record specified number of frames :return: """ if not self.connected: return # check if camera had already been armed if self.alive and self.live_view_bool: try: self.live_view_bool = False self.camera.live = False # stop loop that is producing frames time.sleep(0.1) self.record_live_thread.join() self.live_thread.join() del self.record_live_thread del self.live_thread except: pass elif not self.alive: self.alive = True self.camera.arm_camera() self.camera.start_recording() self.camera.allocate_buffer() self.camera._prepare_to_record_to_memory() self.alive = True else: pass hdu = fits.HDUList() # initialize fits object filename = QtGui.QFileDialog.getSaveFileName(self, 'Save as..', self.save_dir) self.save_dir = os.path.dirname(filename) print(filename) num_of_frames = 10 try: num_of_frames = int(self.FramesLab.text()) except ValueError: return self.measurement_status.setText('Recording %d frames..'%num_of_frames) record_data = [] record_data = self.camera.record_to_memory(num_of_frames)/4 # :4 to make it 14 bit if record_data == []: self.stop_callback() return self.measurement_status.setText('Exporting to FITS file') hdu.append(fits.PrimaryHDU(data=record_data)) # other header details will come in here hdu[0].header['EXPTIME'] = "%i %s" % (self.t, self.time_units.currentText()) hdu.writeto(filename+'.fits') self.measurement_status.setText('Recording finished.') self.stop_callback() return None def stop_callback(self): """ Stops live preview :return: """ self.alive = False if self.live_view_bool: self.live_view_bool = False self.camera.live = False # stop loop that is producing frames time.sleep(0.1) self.record_live_thread.join() self.live_thread.join() del self.record_live_thread del self.live_thread # disarm camera self.camera.disarm_camera() self.display_status.setText('Idle') self.measurement_status.setText('') return if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = QtGui.QMainWindow() window.setWindowTitle('PCO.PixelFly -ETH Zurich- ') try: icon = QtGui.QIcon('App.ico') window.setWindowIcon(icon) except: pass pco_ui = CameraWidget(parent=None) pco_ui.create_gui(window) window.show() sys.exit(app.exec_())
[]
[]
[ "SDL_VIDEO_WINDOW_POS" ]
[]
["SDL_VIDEO_WINDOW_POS"]
python
1
0
vendor/github.com/qiniu/api.v7/examples/rs_list_files.go
package main import ( "fmt" "os" "github.com/qiniu/api.v7/auth/qbox" "github.com/qiniu/api.v7/storage" ) var ( accessKey = os.Getenv("QINIU_ACCESS_KEY") secretKey = os.Getenv("QINIU_SECRET_KEY") bucket = os.Getenv("QINIU_TEST_BUCKET") ) func main() { mac := qbox.NewMac(accessKey, secretKey) cfg := storage.Config{ // 是否使用https域名进行资源管理 UseHTTPS: false, } // 指定空间所在的区域,如果不指定将自动探测 // 如果没有特殊需求,默认不需要指定 //cfg.Zone=&storage.ZoneHuabei bucketManager := storage.NewBucketManager(mac, &cfg) limit := 1000 prefix := "qiniu" delimiter := "" //初始列举marker为空 marker := "" for { entries, _, nextMarker, hashNext, err := bucketManager.ListFiles(bucket, prefix, delimiter, marker, limit) if err != nil { fmt.Println("list error,", err) break } //print entries for _, entry := range entries { fmt.Println(entry.Key) } if hashNext { marker = nextMarker } else { //list end break } } }
[ "\"QINIU_ACCESS_KEY\"", "\"QINIU_SECRET_KEY\"", "\"QINIU_TEST_BUCKET\"" ]
[]
[ "QINIU_ACCESS_KEY", "QINIU_SECRET_KEY", "QINIU_TEST_BUCKET" ]
[]
["QINIU_ACCESS_KEY", "QINIU_SECRET_KEY", "QINIU_TEST_BUCKET"]
go
3
0
backend/conduit/settings/docker.py
import json import os from conduit.settings.defaults import * DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True' STATIC_ROOT = '/data/static/' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DATABASE_NAME'], 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': os.environ['DATABASE_HOST'], 'PORT': os.environ.get('DATABASE_PORT', '5432'), } } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'django.file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/data/django.log', }, 'django.security.file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/data/django.security.log', }, }, 'loggers': { 'django.request': { 'handlers': ['django.file'], 'level': 'DEBUG', 'propagate': True, }, 'django.security': { 'handlers': ['django.security.file'], 'level': 'DEBUG', 'propagate': True, }, 'django.db.backends': { 'handlers': [], 'level': 'DEBUG', 'propagate': True, }, }, } CORS_ORIGIN_WHITELIST = tuple(json.loads(os.environ.get( 'DJANGO_CORS_ORIGIN_WHITELIST', '[]' )))
[]
[]
[ "DATABASE_PASSWORD", "DATABASE_HOST", "DATABASE_NAME", "DJANGO_DEBUG", "DATABASE_USER", "DATABASE_PORT", "DJANGO_CORS_ORIGIN_WHITELIST" ]
[]
["DATABASE_PASSWORD", "DATABASE_HOST", "DATABASE_NAME", "DJANGO_DEBUG", "DATABASE_USER", "DATABASE_PORT", "DJANGO_CORS_ORIGIN_WHITELIST"]
python
7
0
tseries_crossval.py
import numpy as np import sys import os import math os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TF info import tensorflow as tf #import matplotlib.pyplot as plt # Define constants stride = 15 #1 second @ 15 Hz sampling window = 30*15 #30 seconds window considered folder = sys.argv[1] if not os.path.exists(folder): print("Unable to open folder containing data, check that folder exists \n") exit(0) total_files = 488 total_sum = 0 for i in range(1,total_files + 1): file_no = 'output' + str(i) + '.txt' full_path = os.path.join(folder, file_no) #print(full_path) f = open(full_path,'r') d=[[float(x) for x in line.split()] for line in f] f.close() N = len(d) total_sum = total_sum + N M = len(d[0]) measurements = int((M-window)/6) dataset = np.zeros((total_sum,measurements,6)) vectors = np.zeros((total_sum,window),dtype=np.uint8) windows_in_recording = np.zeros((total_files), dtype=np.uint32) total_windows = 0 for i in range(1,total_files + 1): file_no = 'output' + str(i) + '.txt' full_path = os.path.join(folder, file_no) f = open(full_path,'r') d=[[float(x) for x in line.split()] for line in f] f.close() # Need to recalculate the number of windows each time N = len(d) labels = np.zeros(shape = (N,window), dtype=np.uint8) # np.uint8 -> each sample is labeled from 0 to 5 data = np.zeros(shape = (N,measurements,6)) data_max = np.zeros((6)) # Create placeholders data_min = np.zeros((6)) temp_3 = np.zeros((6)) temp_4 = np.zeros((6)) for j in range(N): temp = d[j] temp_1 = temp[0:window] temp_2 = temp[window:M] labels[j,:] = temp_1 for k in range(measurements): # Read data for l in range(6): data[j,k,l] = temp_2[(6*k) + l] for j in range(N): if(j == 1): data_max = np.amax(data[j,:,:], axis=0) data_min = np.amin(data[j,:,:], axis=0) else: temp_3 = np.amax(data[j,:,:], axis=0) temp_4 = np.amin(data[j,:,:], axis=0) for k in range(6): if(temp_3[k] >= data_max[k]): data_max[k] = temp_3[k] if(temp_4[k] <= data_min[k]): data_min[k] = temp_4[k] # Normalize each recording (meal) for j in range(N): for k in range(measurements): data[j,k,:] = data[j,k,:] - data_min # Vector subtraction data[j,k,:] = data[j,k,:]/(data_max - data_min) # Element-wise division dataset[total_windows:total_windows + N, :, :] = data vectors[total_windows:total_windows + N,:] = labels total_windows = total_windows + N windows_in_recording[i-1] = total_windows #Calculates all windows till this meal -> That is what we want! # Clear variables from memory del data, labels, d, temp_1, temp_2, temp_3, temp_4 # Print out to verify #f = open('segments_data.txt','w') #for j in range(measurements): # for k in range(6): # f.write("%f " % (dataset[0,j,k])) # f.write("\n") # --> correct way of newline in Python! #f.close() #f = open('segments_labels.txt','w') #for j in range(total_windows): # for k in range(window): # f.write("%u " % (vectors[j,k])) # f.write("\n") #f.close() # Cross-validation starts here, split data into five parts, use validation_split (keras) for simplicity part_1 = windows_in_recording[math.floor((0.2*total_files)) -1] part_2 = windows_in_recording[math.floor((0.4*total_files)) -1] part_3 = windows_in_recording[math.floor((0.6*total_files)) -1] part_4 = windows_in_recording[math.floor((0.8*total_files)) -1] for iter in range(5): if(iter == 0): tst_data = dataset[0:part_1,:,:] trn_data = dataset[part_1:total_windows,:,:] tst_vcts = vectors[0:part_1,:] trn_vcts = vectors[part_1:total_windows,:] elif(iter == 1): tst_data = dataset[part_1:part_2,:,:] temp_1 = dataset[0:part_1,:,:] temp_2 = dataset[part_2:total_windows,:,:] trn_data = np.concatenate((temp_1, temp_2), axis=0) tst_vcts = vectors[part_1:part_2,:] temp_3 = vectors[0:part_1,:] temp_4 = vectors[part_2:total_windows,:] trn_vcts = np.concatenate((temp_3, temp_4), axis=0) elif(iter == 2): tst_data = dataset[part_2:part_3,:,:] temp_1 = dataset[0:part_2,:,:] temp_2 = dataset[part_3:total_windows,:,:] trn_data = np.concatenate((temp_1, temp_2), axis=0) tst_vcts = vectors[part_2:part_3,:] temp_3 = vectors[0:part_2,:] temp_4 = vectors[part_3:total_windows,:] trn_vcts = np.concatenate((temp_3, temp_4), axis=0) elif(iter == 3): tst_data = dataset[part_3:part_4,:,:] temp_1 = dataset[0:part_3,:,:] temp_2 = dataset[part_4:total_windows,:,:] trn_data = np.concatenate((temp_1, temp_2), axis=0) tst_vcts = vectors[part_3:part_4,:] temp_3 = vectors[0:part_3,:] temp_4 = vectors[part_4:total_windows,:] trn_vcts = np.concatenate((temp_3, temp_4), axis=0) elif(iter == 4): tst_data = dataset[part_4:total_windows,:,:] trn_data = dataset[0:part_4,:,:] tst_vcts = vectors[part_4:total_windows,:] trn_vcts = vectors[0:part_4,:] # Reshape labels -> needed for keras compatibility trn_size = trn_data.shape[0] trn_vcts = np.reshape(trn_vcts, newshape=(trn_size, 1, window)) # Each vector is of size 1 x training_window => 1 x N image of labels # Neural network training starts here print("Creating model", iter, "here") inputs = tf.keras.layers.Input(shape=(measurements, 6)) reshape = tf.keras.layers.Reshape((1, measurements, 6))(inputs) # Data is a 1 x 450 'image' of 6 channels # Downstream --> Encoder conv_1 = tf.keras.layers.Conv2D(filters=8, kernel_size=(1,15), strides=1, padding='same', activation='linear')(reshape) bn_1 = tf.keras.layers.BatchNormalization(axis=3)(conv_1) act_1 = tf.keras.layers.ReLU()(bn_1) pool_1 = tf.keras.layers.MaxPool2D(pool_size=(1,2))(act_1) conv_2 = tf.keras.layers.Conv2D(filters=16, kernel_size=(1,7), strides=1, padding='same', activation='linear')(pool_1) bn_2 = tf.keras.layers.BatchNormalization(axis=3)(conv_2) act_2 = tf.keras.layers.ReLU()(bn_2) pool_2 = tf.keras.layers.MaxPool2D(pool_size=(1,2))(act_2) conv_3 = tf.keras.layers.Conv2D(filters=32, kernel_size=(1,5), strides=1, padding='same', activation='linear')(pool_2) bn_3 = tf.keras.layers.BatchNormalization(axis=3)(conv_3) act_3 = tf.keras.layers.ReLU()(bn_3) pool_3 = tf.keras.layers.MaxPool2D(pool_size=(1,2))(act_3) # Upstream --> Decoder up_conv1 = tf.keras.layers.Conv2DTranspose(filters=32, kernel_size=(1,5),padding='same',strides=(1,2),activation='linear')(pool_3) bn_4 = tf.keras.layers.BatchNormalization(axis=3)(up_conv1) act_4 = tf.keras.layers.ReLU()(bn_4) concat = tf.keras.layers.Concatenate() cc_1 = concat([act_4, pool_2]) up_conv2 = tf.keras.layers.Conv2DTranspose(filters=16, kernel_size=(1,7),padding='same',strides=(1,2),activation='linear')(cc_1) bn_5 = tf.keras.layers.BatchNormalization(axis=3)(up_conv2) act_5 = tf.keras.layers.ReLU()(bn_5) pad_1 = tf.keras.layers.ZeroPadding2D(padding=((0,0),(0,1)))(act_5) cc_2 = concat([pad_1, pool_1]) # Final Layer pen_ult = tf.keras.layers.Conv2DTranspose(filters=6,kernel_size=(1,3),strides=(1,2),activation='softmax')(cc_2) outputs = tf.keras.layers.Cropping2D(cropping=((0,0),(0,1)))(pen_ult) model = tf.keras.Model(inputs=inputs, outputs=outputs) model.compile(optimizer = 'adam', loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits='True'), metrics=[tf.keras.losses.SparseCategoricalCrossentropy(from_logits='True')]) if(iter == 0): model.summary() # Store training sequence to .txt file training_log = 'crossval_fold_' + str(iter) + '.txt' csv_logger = tf.keras.callbacks.CSVLogger(training_log, append = True, separator=' ') print("Training for fold", iter) metrics = model.fit(trn_data, trn_vcts, epochs=200, validation_split= 0.2, verbose=2, callbacks=[csv_logger]) print("Saving model for fold", iter) model_ID = 'crossval_modelID_' + str(iter) + '.h5' tf.keras.models.save_model(model,model_ID) #del model -> Most likely not needed.... ##print("Predict") ##op = model.predict(dataset[0:10,:,:]) ##print(op.shape) ##temp = op[0,:,:,:] ##temp = np.reshape(temp,(window, 6)) ##for i in range(window): ## print(temp[i,:], np.argmax(temp[i,:]))
[]
[]
[ "TF_CPP_MIN_LOG_LEVEL" ]
[]
["TF_CPP_MIN_LOG_LEVEL"]
python
1
0
cmd/runmqdevserver/main.go
/* © Copyright IBM Corporation 2018, 2021 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 main import ( "fmt" "io/ioutil" "os" "syscall" "github.com/ibm-messaging/mq-container/internal/htpasswd" "github.com/ibm-messaging/mq-container/pkg/containerruntimelogger" "github.com/ibm-messaging/mq-container/pkg/logger" "github.com/ibm-messaging/mq-container/pkg/name" ) var log *logger.Logger func getLogFormat() string { return os.Getenv("LOG_FORMAT") } func getDebug() bool { debug := os.Getenv("DEBUG") if debug == "true" || debug == "1" { return true } return false } func configureLogger() error { var err error f := getLogFormat() d := getDebug() n, err := name.GetQueueManagerName() if err != nil { return err } switch f { case "json": log, err = logger.NewLogger(os.Stderr, d, true, n) if err != nil { return err } case "basic": log, err = logger.NewLogger(os.Stderr, d, false, n) if err != nil { return err } default: log, err = logger.NewLogger(os.Stdout, d, false, n) return fmt.Errorf("invalid value for LOG_FORMAT: %v", f) } return nil } func logTerminationf(format string, args ...interface{}) { logTermination(fmt.Sprintf(format, args...)) } // TODO: Duplicated code func logTermination(args ...interface{}) { msg := fmt.Sprint(args...) // Write the message to the termination log. This is not the default place // that Kubernetes will look for termination information. log.Debugf("Writing termination message: %v", msg) err := ioutil.WriteFile("/run/termination-log", []byte(msg), 0660) if err != nil { log.Debug(err) } log.Error(msg) } func doMain() error { err := configureLogger() if err != nil { logTermination(err) return err } err = containerruntimelogger.LogContainerDetails(log) if err != nil { logTermination(err) return err } adminPassword, set := os.LookupEnv("MQ_ADMIN_PASSWORD") if !set { adminPassword = "passw0rd" err = os.Setenv("MQ_ADMIN_PASSWORD", adminPassword) if err != nil { logTerminationf("Error setting admin password variable: %v", err) return err } } err = htpasswd.SetPassword("admin", adminPassword, false) if err != nil { logTerminationf("Error setting admin password: %v", err) return err } appPassword, set := os.LookupEnv("MQ_APP_PASSWORD") if set { err = htpasswd.SetPassword("app", appPassword, false) if err != nil { logTerminationf("Error setting app password: %v", err) return err } } err = updateMQSC(set) if err != nil { logTerminationf("Error updating MQSC: %v", err) return err } return nil } var osExit = os.Exit func main() { err := doMain() if err != nil { osExit(1) } else { // Replace this process with runmqserver // #nosec G204 err = syscall.Exec("/usr/local/bin/runmqserver", []string{"runmqserver", "-nologruntime", "-dev"}, os.Environ()) if err != nil { log.Errorf("Error replacing this process with runmqserver: %v", err) } } }
[ "\"LOG_FORMAT\"", "\"DEBUG\"" ]
[]
[ "LOG_FORMAT", "DEBUG" ]
[]
["LOG_FORMAT", "DEBUG"]
go
2
0
mllabis/notebook-server/pkg/commons/utils/k8s_client.go
/* * Copyright 2020 WeBank * * 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 utils import ( "context" "encoding/json" "errors" "fmt" "github.com/kubernetes-client/go/kubernetes/client" "github.com/kubernetes-client/go/kubernetes/config" "github.com/sirupsen/logrus" "github.com/spf13/viper" "io/ioutil" "net/http" "os" "strconv" stringsUtil "strings" "sync" "time" cfg "webank/AIDE/notebook-server/pkg/commons/config" "webank/AIDE/notebook-server/pkg/commons/constants" "webank/AIDE/notebook-server/pkg/commons/logger" "webank/AIDE/notebook-server/pkg/models" ) type NotebookControllerClient struct { k8sClient *client.APIClient } var ncClientInitOnce sync.Once var ncClient *NotebookControllerClient // TODO move these configs to a configmap const ( MistakenTokenHeader = "Authentication" CorrectTokenHeader = "Authorization" TokenValuePrefix = "Bearer " SATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" NBApiGroup = "kubeflow.org" NBApiVersion = "v1alpha1" NBApiPlural = "notebooks" ) var PlatformNamespace = viper.GetString(cfg.PlatformNamespace) func GetNBCClient() *NotebookControllerClient { ncClientInitOnce.Do(func() { config, err := config.InClusterConfig() if err != nil { panic(err.Error()) } tokenValue := config.DefaultHeader[MistakenTokenHeader] if len(tokenValue) == 0 { tv, err := ioutil.ReadFile(SATokenPath) if err != nil { panic(err.Error()) } tokenValue = TokenValuePrefix + string(tv) } defaultHeader := map[string]string{CorrectTokenHeader: tokenValue} config.DefaultHeader = defaultHeader // creates the clientset ncClient = &NotebookControllerClient{} ncClient.k8sClient = client.NewAPIClient(config) }) return ncClient } // create a notebook in a namespace func (*NotebookControllerClient) CreateNotebook(notebook *models.NewNotebookRequest, userId string, gid string, uid string, token string) error { /*** 0. get a nb template for k8s request && get cluster message from namespaces ***/ nbForK8s := createK8sNBTemplate() nbContainer := nbForK8s.Spec.Template.Spec.Containers[0] /*** 1. volumes ***/ var nbVolumes []client.V1Volume var localPath string if nil != notebook.WorkspaceVolume { localPath = *notebook.WorkspaceVolume.LocalPath if len(userId) >len(localPath){ gid = viper.GetString(cfg.MLSSGroupId) }else if userId != localPath[len(localPath)-len(userId):]{ gid = viper.GetString(cfg.MLSSGroupId) } subPath := notebook.WorkspaceVolume.SubPath nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "workdir", Value: subPath, }) if subPath != "" && subPath != "/" { if !stringsUtil.HasPrefix(subPath, "/") && !stringsUtil.HasSuffix(localPath, "/") { localPath = localPath + "/" + subPath } else if stringsUtil.HasPrefix(subPath, "/") && stringsUtil.HasSuffix(localPath, "/") { localPath = localPath + subPath[1:] } else { localPath = localPath + subPath } logger.Logger().Debugf("k8s createNotebook workPath: %v", localPath+subPath) } nbVolumes = append(nbVolumes, client.V1Volume{ Name: "workdir", HostPath: &client.V1HostPathVolumeSource{ Path: localPath, }, }) // persist jupyter config //nbVolumes = append(nbVolumes, // client.V1Volume{ // Name: "notebook-config", // HostPath: &client.V1HostPathVolumeSource{ // Path: localPath + "/notebook-config/.jupyter", // }, // }) // //nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ // Name: "notebook-config", // MountPath: "/.jupyter", //}) } if nil != notebook.DataVolume { localPath := *notebook.DataVolume.LocalPath // if local path directory is end with user Id, this directory will be considered as a common directory. if len(userId) >len(localPath){ gid = viper.GetString(cfg.MLSSGroupId) }else if userId != localPath[len(localPath)-len(userId):]{ gid = viper.GetString(cfg.MLSSGroupId) } subPath := notebook.DataVolume.SubPath nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: fmt.Sprint("datadir"), Value: subPath, }) if subPath != "" && subPath != "/" { if !stringsUtil.HasPrefix(subPath, "/") && !stringsUtil.HasSuffix(localPath, "/") { localPath = localPath + "/" + subPath } else if stringsUtil.HasPrefix(subPath, "/") && stringsUtil.HasSuffix(localPath, "/") { localPath = localPath + subPath[1:] } else { localPath = localPath + subPath } logger.Logger().Debugf("k8s createNotebook workPath: %v", localPath+subPath) } dvForNb := client.V1Volume{ Name: fmt.Sprint("datadir"), HostPath: &client.V1HostPathVolumeSource{ Path: localPath, }, } nbVolumes = append(nbVolumes, dvForNb) } if viper.GetString(cfg.HadoopEnable) == "true" { nbVolumes = append(nbVolumes, client.V1Volume{ Name: "bdap-appcom-config", HostPath: &client.V1HostPathVolumeSource{ Path: viper.GetString(cfg.ConfigPath), }, }, client.V1Volume{ Name: "bdap-appcom-commonlib", HostPath: &client.V1HostPathVolumeSource{ Path: viper.GetString(cfg.CommonlibPath), }, }, client.V1Volume{ Name: "bdap-appcom-install", HostPath: &client.V1HostPathVolumeSource{ Path: viper.GetString(cfg.InstallPath), }, }, client.V1Volume{ Name: "jdk", HostPath: &client.V1HostPathVolumeSource{ Path: viper.GetString(cfg.JavaPath), }, }) // mount HADOOP Install File nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "bdap-appcom-config", MountPath: viper.GetString(cfg.ConfigPath), }) nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "bdap-appcom-install", MountPath: viper.GetString(cfg.InstallPath), }) nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "bdap-appcom-commonlib", MountPath: viper.GetString(cfg.CommonlibPath), }) nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "jdk", MountPath: viper.GetString(cfg.JavaPath), }) } nbVolumes = append(nbVolumes, client.V1Volume{ Name: "config-json", ConfigMap: &client.V1ConfigMapVolumeSource{ DefaultMode: 0755, Name: *notebook.Name + "-" + "yarn-resource-setting", }, }, client.V1Volume{ Name: "linkismagic-json", ConfigMap: &client.V1ConfigMapVolumeSource{ DefaultMode: 0755, Name: *notebook.Name + "-" + "yarn-resource-setting", }, }) nbForK8s.Spec.Template.Spec.Volumes = append(nbForK8s.Spec.Template.Spec.Volumes, nbVolumes...) /*** 3. container ***/ startWorkspace := "" if nil == notebook.DataVolume { startWorkspace = "/workspace" } nbContainer.Command = []string{"/etc/config/start-sh"} nbContainer.Args = []string{"jupyter lab --notebook-dir=/home/" + userId + startWorkspace + " --ip=0.0.0.0 --no-browser --allow-root --port=8888 --NotebookApp.token='' " + "--NotebookApp.password='' --NotebookApp.allow_origin='*' --NotebookApp.base_url=${NB_PREFIX}"} var extraResourceMap = make(map[string]string) if notebook.ExtraResources != "" { err := json.Unmarshal([]byte(notebook.ExtraResources), &extraResourceMap) if nil != err { logger.Logger().Errorf("Error parsing extra resources: %s", notebook.ExtraResources) logger.Logger().Errorf(err.Error()) return err } } var limitMap = make(map[string]string) limitMap["cpu"] = fmt.Sprint(*(notebook.CPU)) MemoryAmount := notebook.Memory.MemoryAmount float := fmt.Sprintf("%.1f", *MemoryAmount) s := notebook.Memory.MemoryUnit limitMap["memory"] = fmt.Sprint(float, s) if extraResourceMap["nvidia.com/gpu"] != "" && extraResourceMap["nvidia.com/gpu"] != "0" { limitMap["nvidia.com/gpu"] = extraResourceMap["nvidia.com/gpu"] } else { nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "NVIDIA_VISIBLE_DEVICES", Value: "", }) } logger.Logger().Infof("CreateNotebook limitMap: %s", limitMap) nbContainer.Resources = &client.V1ResourceRequirements{ Requests: limitMap, Limits: limitMap, } nbContainer.Image = *(notebook.Image.ImageName) if nil != notebook.WorkspaceVolume { nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "workdir", MountPath: "/workspace", }) } if nil != notebook.DataVolume { mountPath := *notebook.DataVolume.MountPath if !stringsUtil.HasPrefix(mountPath, "/") && !stringsUtil.HasSuffix(mountPath, "/") { if stringsUtil.Contains(mountPath, "/") { return errors.New("mountPath can only have level 1 directories") } } else if stringsUtil.HasPrefix(mountPath, "/") && !stringsUtil.HasSuffix(mountPath, "/") { if stringsUtil.Contains(mountPath[1:], "/") { return errors.New("mountPath can only have level 1 directories") } } else if !stringsUtil.HasPrefix(mountPath, "/") && stringsUtil.HasSuffix(mountPath, "/") { if stringsUtil.Index(mountPath, "/") < len(mountPath)-1 { return errors.New("mountPath can only have level 1 directories") } } else if stringsUtil.HasPrefix(mountPath, "/") && stringsUtil.HasSuffix(mountPath, "/") { if stringsUtil.Contains(mountPath[1:(len(mountPath) - 1)], "/") { return errors.New("mountPath can only have level 1 directories") } } if stringsUtil.HasPrefix(mountPath, "/") { mountPath = "data-" + mountPath[1:] } else { mountPath = "data-" + mountPath } dvmForNb := client.V1VolumeMount{ Name: fmt.Sprint("datadir"), MountPath: mountPath, } nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, dvmForNb) } nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "Driver_Host", ValueFrom: &client.V1EnvVarSource{ FieldRef: &client.V1ObjectFieldSelector{ FieldPath: "spec.nodeName", }, }, }) logger.Logger().Debugf("create notebook for gid: %v", gid) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "NB_GID", Value: gid, }) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "NB_UID", Value: uid, }) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "NB_USER", Value: userId, }) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "GRANT_SUDO", Value: "no", }) nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "config-json", MountPath: "/etc/sparkmagic/", }) nbContainer.VolumeMounts = append(nbContainer.VolumeMounts, client.V1VolumeMount{ Name: "linkismagic-json", MountPath: "/etc/linkismagic/", }) //create NodePort Service notebookService, nodePortArray, err := createK8sNBServiceTemplate(notebook) if nil != err { logger.Logger().Errorf(err.Error()) return err } nbForK8s.Service = *notebookService nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "Spark_Driver_Port", Value: strconv.Itoa(nodePortArray[0]), }) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "Spark_Driver_BlockManager_Port", Value: strconv.Itoa(nodePortArray[1]), }) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "Linkis_Token", Value: viper.GetString(cfg.LinkisToken), }) nbContainer.Env = append(nbContainer.Env, client.V1EnvVar{ Name: "GUARDIAN_TOKEN", Value: token, }) nbForK8s.Spec.Template.Spec.Containers[0] = nbContainer /*** 4. fill in other info ***/ nbForK8s.Metadata.Name = *(notebook.Name) nbForK8s.Metadata.Namespace = *(notebook.Namespace) userIdLabel := PlatformNamespace + "-UserId" workDirLabel := PlatformNamespace + "-WorkdDir" //set notebook create time in label nowTimeStr := strconv.FormatInt(time.Now().Unix(), 10) //nbForK8s.Metadata.Labels = map[string]string{"MLSS-UserId": userId} var workDirPath string if nil != notebook.DataVolume { workDirPath = *notebook.DataVolume.LocalPath } else { workDirPath = *notebook.WorkspaceVolume.LocalPath } logger.Logger().Info("localPath is ", localPath) nbForK8s.Metadata.Labels = map[string]string{ userIdLabel: userId, workDirLabel: stringsUtil.Replace(workDirPath[1:], "/", "_", -1), constants.CreateTime: nowTimeStr, } _, resp, err := ncClient.k8sClient.CustomObjectsApi.CreateNamespacedCustomObject(context.Background(), NBApiGroup, NBApiVersion, nbForK8s.Metadata.Namespace, NBApiPlural, nbForK8s, nil) if nil != err { logger.Logger().Errorf("Error creating notebook: %+v", err.Error()) return err } if resp != nil { logger.Logger().Debugf("response from k8s: %+v", resp) } return err } // delete notebook in a namespace func (*NotebookControllerClient) DeleteNotebook(nb string, ns string) error { _, resp, err := ncClient.k8sClient.CustomObjectsApi.DeleteNamespacedCustomObject(context.Background(), NBApiGroup, NBApiVersion, ns, NBApiPlural, nb, client.V1DeleteOptions{}, nil) if err != nil { logger.Logger().Errorf(""+ " deleting notebook: %+v", err.Error()) return err } if resp == nil { logger.Logger().Error("empty response") } err = deleteK8sNBConfigMap(ns, nb+"-"+"yarn-resource-setting") if err != nil { logger.Logger().Errorf(""+ " deleting notebook configmap: %+v", err.Error()) return err } return nil } // get notebooks in a namespace, or of a user, or of a user in a namespace func (*NotebookControllerClient) GetNotebooks(ns string, userId string, workDir string) (interface{}, error) { //createK8sNBConfigMap("ns-ns-bdap-common-common-dev-csf",logr) var optionals = make(map[string]interface{}) userIdLabelKey := PlatformNamespace + "-UserId=" workDirLabel := "" //optionals["labelSelector"] = fmt.Sprint("MLSS-UserId=", userId) if workDir != "" { workDir = stringsUtil.Replace(workDir[1:], "/", "_", -1) workDirLabel := fmt.Sprint(PlatformNamespace+"-WorkDir=", workDir) optionals["labelSelector"] = fmt.Sprint(userIdLabelKey, userId) + "," + workDirLabel logger.Logger().Info("labelselector:", optionals["labelSelector"]) } else { optionals["labelSelector"] = fmt.Sprint(userIdLabelKey, userId) logger.Logger().Info("workdir is nil label is %s", optionals["labelSelector"]) } var list, resp interface{} var err error if len(ns) == 0 && len(userId) == 0 { optionals["labelSelector"] = workDirLabel list, resp, err = ncClient.k8sClient.CustomObjectsApi.ListClusterCustomObject(context.Background(), NBApiGroup, NBApiVersion, NBApiPlural, optionals) } else if len(ns) == 0 && len(userId) != 0 { // get user notebooks in all namespaces logger.Logger().Debugf("len(ns) == 0 && len(userId)") list, resp, err = ncClient.k8sClient.CustomObjectsApi.ListClusterCustomObject(context.Background(), NBApiGroup, NBApiVersion, NBApiPlural, optionals) } else if ns == "null" && userId == "null" { optionals["labelSelector"] = PlatformNamespace + "-UserId" + workDirLabel list, resp, err = ncClient.k8sClient.CustomObjectsApi.ListClusterCustomObject(context.Background(), NBApiGroup, NBApiVersion, NBApiPlural, optionals) } else { if len(userId) == 0 && len(ns) != 0 { optionals = nil } list, resp, err = ncClient.k8sClient.CustomObjectsApi.ListNamespacedCustomObject(context.Background(), NBApiGroup, NBApiVersion, ns, NBApiPlural, optionals) } if err != nil { logger.Logger().Error(err.Error()) return nil, err } if resp == nil { logger.Logger().Error("emtpy response") return nil, nil } return list, nil } // Get namespaces func (*NotebookControllerClient) GetNamespaces() []string { list, response, err := ncClient.k8sClient.CoreV1Api.ListNamespace(context.Background(), nil) if err != nil { logrus.Error(err.Error()) return nil } if response == nil { logrus.Error("empty response") return nil } var namespaceList []string for _, namespace := range list.Items { namespaceList = append(namespaceList, namespace.Metadata.Name) } return namespaceList } func (*NotebookControllerClient) listNamespacedResourceQuota(ns string) ([]client.V1ResourceQuota, error) { list, response, err := ncClient.k8sClient.CoreV1Api.ListNamespacedResourceQuota(context.Background(), ns, nil) if err != nil { logrus.Error(err.Error()) return nil, err } if response == nil { logrus.Error("empty response") return nil, err } logrus.Infof("listNamespacedResourceQuota,ns: %v, list: %v", ns, list) return list.Items, nil } func (*NotebookControllerClient) listNamespaceNodes(ns string) ([]client.V1Node, error) { v1Namespace, _, readErr := ncClient.k8sClient.CoreV1Api.ReadNamespace(context.Background(), ns, nil) if readErr != nil { logrus.Error(readErr.Error()) return nil, readErr } namespaceAnnotations := v1Namespace.Metadata.Annotations logrus.Debugf("listNamespaceNodes for namespaceAnnotations: %v", namespaceAnnotations) selector := namespaceAnnotations["scheduler.alpha.kubernetes.io/node-selector"] var localVarOptionals = make(map[string]interface{}) localVarOptionals["labelSelector"] = selector list, response, err := ncClient.k8sClient.CoreV1Api.ListNode(context.Background(), localVarOptionals) if err != nil { logrus.Error(err.Error()) return nil, err } if response == nil { logrus.Error("empty response") return nil, err } logrus.Debugf("listNamespaceNodes by namespace: %v, list.items.length: %v", ns, len(list.Items)) return list.Items, nil } func createK8sNBTemplate() *models.K8sNotebook { nb := &models.K8sNotebook{ ApiVersion: NBApiGroup + "/" + NBApiVersion, Kind: "Notebook", Metadata: client.V1ObjectMeta{ Name: "", Namespace: "", //Labels: nil, }, Spec: models.NBSpec{ Template: models.NBTemplate{ Spec: models.NBDetailedSpec{ ServiceAccountName: "jupyter-notebook", Containers: []client.V1Container{ { Name: "notebook-container", VolumeMounts: []client.V1VolumeMount{ { Name: "dshm", MountPath: "/dev/shm", }, { Name: "start-sh", MountPath: "/etc/config", }, { Name: "timezone-volume", MountPath: "/etc/localtime", }}, Env: nil, Command: []string{"/etc/config/start-sh"}, SecurityContext: &client.V1SecurityContext{ RunAsGroup: int64(0), RunAsUser: int64(0), AllowPrivilegeEscalation: true, Privileged: false, }, }, }, TtlSecondsAfterFinished: 300, Volumes: []client.V1Volume{ { Name: "dshm", EmptyDir: &client.V1EmptyDirVolumeSource{ Medium: "Memory", }}, { Name: "start-sh", ConfigMap: &client.V1ConfigMapVolumeSource{ DefaultMode: 0777, Name: "notebook-entrypoint-files", }, }, { Name: "timezone-volume", HostPath: &client.V1HostPathVolumeSource{ Path: "/usr/share/zoneinfo/Asia/Shanghai", }}, }, // FIXME not working SecurityContext: client.V1SecurityContext{ RunAsGroup: int64(0), RunAsUser: int64(0), AllowPrivilegeEscalation: true, Privileged: false, }, }, }, }, } return nb } func createK8sNBServiceTemplate(notebook *models.NewNotebookRequest) (*client.V1Service, [2]int, error) { ServiceName := *(notebook.Name) + "-service" nbService := &client.V1Service{ Metadata: &client.V1ObjectMeta{ Name: ServiceName, Namespace: *(notebook.Namespace), }, Spec: &client.V1ServiceSpec{}, } nbServiceSelector := make(map[string]string) nbServiceSelector["notebook-name"] = *notebook.Name nbService.Metadata.Namespace = *notebook.Namespace nbService.Spec.Type_ = "NodePort" startPort, err := strconv.Atoi(os.Getenv("START_PORT")) if nil != err { logger.Logger().Errorf("parse START_PORT failed: %s", os.Getenv("START_PORT")) return nil, [2]int{0, 0}, err } endPort, err := strconv.Atoi(os.Getenv("END_PORT")) if nil != err { logger.Logger().Errorf("parse END_PORT failed: %s", os.Getenv("END_PORT")) return nil, [2]int{0, 0}, err } _, nodePortArray := getNodePort(startPort, endPort) logger.Logger().Info("Service NodePort:" + strconv.Itoa(nodePortArray[0]) + " and " + strconv.Itoa(nodePortArray[1])) nbService.Spec.Ports = []client.V1ServicePort{{ Name: "sparkcontextport", NodePort: int32(nodePortArray[0]), Port: int32(nodePortArray[0]), Protocol: "TCP", }, { Name: "sparkblockmanagerport", NodePort: int32(nodePortArray[1]), Port: int32(nodePortArray[1]), Protocol: "TCP", }, } nbService.Spec.Selector = nbServiceSelector return nbService, nodePortArray, nil } func getNodePort(startPort int, endPort int) (error, [2]int) { clusterService, _, err := ncClient.k8sClient.CoreV1Api.ListServiceForAllNamespaces(context.Background(), nil) portLen := (endPort - startPort) + 1 portArray := make([]bool, portLen, portLen) nodePortArray := [2]int{-1, -1} if err != nil { logrus.Error(err.Error()) return err, nodePortArray } for _, serviceItem := range clusterService.Items { if serviceItem.Spec.Type_ == "NodePort" { usedNodeportList := serviceItem.Spec.Ports for _, usedNodeportItem := range usedNodeportList { usedNodeport := int(usedNodeportItem.NodePort) if usedNodeport >= startPort && usedNodeport <= endPort { logger.Logger().Info("NodePort:" + strconv.Itoa(usedNodeport) + " is allocated") portArray[usedNodeport-startPort] = true } } } } flag := 0 for i, value := range portArray { if value != true { nodePortArray[flag] = i + startPort flag = flag + 1 if flag >= 2 { break } } } return err, nodePortArray } func (*NotebookControllerClient) CreateYarnResourceConfigMap(notebook *models.NewNotebookRequest, userId string) error { configmap, _, err := ncClient.k8sClient. CoreV1Api.ReadNamespacedConfigMap(context.Background(), "yarn-resource-setting", *notebook.Namespace, nil) if err != nil { logger.Logger().Errorf(err.Error()) return err } var yarnConfigmap map[string]interface{} err = json.Unmarshal([]byte(configmap.Data["config.json"]), &yarnConfigmap) if err != nil { logger.Logger().Info("json yarn configmap error") logrus.Error(err.Error()) return err } var linkismagicCM map[string]interface{} err = json.Unmarshal([]byte(configmap.Data["linkismagic.json"]), &linkismagicCM) if err != nil { logger.Logger().Error("json linkismagic configmap error:%v", err.Error()) return err } yarnConfigmap["session_configs"].(map[string]interface{})["proxyUser"] = userId // if yarn resource is not set, set default values. if "" != notebook.Queue { yarnConfigmap["session_configs"].(map[string]interface{})["queue"] = notebook.Queue linkismagicCM["session_configs"].(map[string]interface{})["wds.linkis.yarnqueue"] = notebook.Queue // default setting yarnConfigmap["session_configs"].(map[string]interface{})["driverMemory"] = "2g" yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.cores"] = "2" yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.instances"] = "2" yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.memory"] = "2g" linkismagicCM["session_configs"].(map[string]interface{})["spark.driver.memory"] = "2" linkismagicCM["session_configs"].(map[string]interface{})["spark.executor.instances"] = "2" linkismagicCM["session_configs"].(map[string]interface{})["spark.executor.memory"] = "2" } if "" != notebook.DriverMemory { yarnConfigmap["session_configs"].(map[string]interface{})["driverMemory"] = notebook.DriverMemory + "g" linkismagicCM["session_configs"].(map[string]interface{})["spark.driver.memory"] = notebook.DriverMemory } if "" != notebook.ExecutorCores { yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.cores"] = notebook.ExecutorCores } if "" != notebook.Executors { yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.instances"] = notebook.Executors linkismagicCM["session_configs"].(map[string]interface{})["spark.executor.instances"] = notebook.Executors } if "" != notebook.ExecutorMemory { yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.memory"] = notebook.ExecutorMemory + "g" linkismagicCM["session_configs"].(map[string]interface{})["spark.executor.memory"] = notebook.ExecutorMemory } configByte, _ := json.Marshal(yarnConfigmap) linkismagicCMByte, _ := json.Marshal(linkismagicCM) configJsonStr := string(configByte) linkismagicStr := string(linkismagicCMByte) nsConfigmap := client.V1ConfigMap{ Metadata: &client.V1ObjectMeta{ Name: *notebook.Name + "-" + "yarn-resource-setting", Namespace: *notebook.Namespace, }, Data: map[string]string{ "config.json": configJsonStr, "linkismagic.json": linkismagicStr, }, } _, _, err = ncClient.k8sClient.CoreV1Api.CreateNamespacedConfigMap(context.Background(), *notebook.Namespace, nsConfigmap, nil) logger.Logger().Info("Create Configmap yarn resource setting for notebook " + *notebook.Namespace) if err != nil { logrus.Error(err.Error()) return err } return err } func (*NotebookControllerClient) PatchYarnSettingConfigMap(notebook *models.PatchNotebookRequest) error { namespace := *notebook.Namespace nbName := *notebook.Name configmap, _, err := ncClient.k8sClient.CoreV1Api.ReadNamespacedConfigMap(context.Background(), nbName+"-"+"yarn-resource-setting", namespace, nil) if err != nil { logrus.Error("get configmap errror:" + err.Error()) return err } //Unmarshal Yarn Config & LinkisMagic Config var yarnConfigmap map[string]interface{} var linkismagicConfigmap map[string]interface{} err = json.Unmarshal([]byte(configmap.Data["config.json"]), &yarnConfigmap) if err != nil { logrus.Error("unmarshal yarn json erro" + err.Error()) return err } err = json.Unmarshal([]byte(configmap.Data["linkismagic.json"]), &linkismagicConfigmap) if err != nil { logrus.Error("unmarshal linkismagic json error" + err.Error()) return err } // Update resource Msg in Yarn Configmap Map if "" != notebook.Queue { yarnConfigmap["session_configs"].(map[string]interface{})["queue"] = notebook.Queue linkismagicConfigmap["session_configs"].(map[string]interface{})["wds.linkis.yarnqueue"] = notebook.Queue } if "" != notebook.DriverMemory { yarnConfigmap["session_configs"].(map[string]interface{})["driverMemory"] = notebook.DriverMemory linkismagicConfigmap["session_configs"].(map[string]interface{})["spark.driver.memory"] = notebook.DriverMemory[0 : len(notebook.ExecutorMemory)-1] } if "" != notebook.ExecutorCores { yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.cores"] = notebook.ExecutorCores } if "" != notebook.Executors { yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.instances"] = notebook.Executors linkismagicConfigmap["session_configs"].(map[string]interface{})["spark.executor.instances"] = notebook.Executors } if "" != notebook.ExecutorMemory { yarnConfigmap["session_configs"].(map[string]interface{})["conf"].(map[string]interface{})["spark.executor.memory"] = notebook.ExecutorMemory linkismagicConfigmap["session_configs"].(map[string]interface{})["spark.executor.memory"] = notebook.ExecutorMemory[0 : len(notebook.ExecutorMemory)-1] } configByte, err := json.Marshal(yarnConfigmap) if err != nil { logrus.Error("marshal yarnConfigmap error" + err.Error()) return err } linkismagicByte, err := json.Marshal(linkismagicConfigmap) if err != nil { logrus.Error("marshal linkismagic error" + err.Error()) return err } //set update k8s config oprMap configJsonStr := string(configByte) lmConfigJsonStr := string(linkismagicByte) logger.Logger().Debugf("read configmap from configJsonStr" + configJsonStr) oprMap := []map[string]interface{}{ {"op": "replace", "path": "/data", "value": map[string]interface{}{ "config.json": configJsonStr, "linkismagic.json": lmConfigJsonStr, }}, } _, _, err = ncClient.k8sClient.CoreV1Api.PatchNamespacedConfigMap(context.Background(), nbName+"-"+"yarn-resource-setting", namespace, oprMap, nil) if err != nil { logrus.Error("PatchNamespacedConfigMap" + err.Error()) return err } return err } func deleteK8sNBConfigMap(namespace string, name string) error { logger.Logger().Info("Delete configmap " + name + " in namespace " + namespace) _, resp, err := ncClient.k8sClient.CoreV1Api.DeleteNamespacedConfigMap(context.Background(), name, namespace, client.V1DeleteOptions{}, nil) if err != nil { logrus.Error(err.Error()) return err } if resp == nil { logger.Logger().Error("empty response") } return err } func (*NotebookControllerClient) GetNBConfigMaps(namespace string) (*map[string]interface{}, error) { var list client.V1ConfigMapList var response *http.Response var err error configs := map[string]interface{}{} if "" == namespace || "null" == namespace { logger.Logger().Infof("ListConfigMapForAllNamespaces:%v", namespace) list, response, err = ncClient.k8sClient.CoreV1Api.ListConfigMapForAllNamespaces(context.Background(), nil) } else { logger.Logger().Infof("ListNamespacedConfigMap namespsace:%v", namespace) list, response, err = ncClient.k8sClient.CoreV1Api.ListNamespacedConfigMap(context.Background(), namespace, nil) } if err != nil { logger.Logger().Error(err.Error()) return &configs, err } if response == nil { logger.Logger().Error("emtpy response") return nil, nil } logger.Logger().Infof("configmap length:%v", len(list.Items)) for _, configmap := range list.Items { logger.Logger().Infof("configmap name:%v", configmap.Metadata.Name) if !stringsUtil.Contains(configmap.Metadata.Name, "yarn-resource-setting") { continue } var yarnConfigmap map[string]interface{} err = json.Unmarshal([]byte(configmap.Data["config.json"]), &yarnConfigmap) if err != nil { logger.Logger().Errorf("configmap "+configmap.Metadata.Name+" unmarshal error:%v", err.Error()) } configs[configmap.Metadata.Namespace+"-"+configmap.Metadata.Name] = yarnConfigmap } return &configs, err } func (*NotebookControllerClient) DeleteNBYarnConfigMap(namespace string, nbName string) error { err := deleteK8sNBConfigMap(namespace, nbName+"-"+"yarn-resource-setting") return err }
[ "\"START_PORT\"", "\"START_PORT\"", "\"END_PORT\"", "\"END_PORT\"" ]
[]
[ "START_PORT", "END_PORT" ]
[]
["START_PORT", "END_PORT"]
go
2
0
vendor/k8s.io/client-go/tools/clientcmd/client_config.go
/* Copyright 2014 The Kubernetes Authors. 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 clientcmd import ( "fmt" "io" "io/ioutil" "net/url" "os" "strings" "github.com/golang/glog" "github.com/imdario/mergo" "k8s.io/client-go/pkg/api" "k8s.io/client-go/rest" clientauth "k8s.io/client-go/tools/auth" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" ) var ( // ClusterDefaults has the same behavior as the old EnvVar and DefaultCluster fields // DEPRECATED will be replaced ClusterDefaults = clientcmdapi.Cluster{Server: getDefaultServer()} // DefaultClientConfig represents the legacy behavior of this package for defaulting // DEPRECATED will be replace DefaultClientConfig = DirectClientConfig{*clientcmdapi.NewConfig(), "", &ConfigOverrides{ ClusterDefaults: ClusterDefaults, }, nil, NewDefaultClientConfigLoadingRules(), promptedCredentials{}} ) // getDefaultServer returns a default setting for DefaultClientConfig // DEPRECATED func getDefaultServer() string { if server := os.Getenv("KUBERNETES_MASTER"); len(server) > 0 { return server } return "http://localhost:8080" } // ClientConfig is used to make it easy to get an api server client type ClientConfig interface { // RawConfig returns the merged result of all overrides RawConfig() (clientcmdapi.Config, error) // ClientConfig returns a complete client config ClientConfig() (*rest.Config, error) // Namespace returns the namespace resulting from the merged // result of all overrides and a boolean indicating if it was // overridden Namespace() (string, bool, error) // ConfigAccess returns the rules for loading/persisting the config. ConfigAccess() ConfigAccess } type PersistAuthProviderConfigForUser func(user string) rest.AuthProviderConfigPersister type promptedCredentials struct { username string password string } // DirectClientConfig is a ClientConfig interface that is backed by a clientcmdapi.Config, options overrides, and an optional fallbackReader for auth information type DirectClientConfig struct { config clientcmdapi.Config contextName string overrides *ConfigOverrides fallbackReader io.Reader configAccess ConfigAccess // promptedCredentials store the credentials input by the user promptedCredentials promptedCredentials } // NewDefaultClientConfig creates a DirectClientConfig using the config.CurrentContext as the context name func NewDefaultClientConfig(config clientcmdapi.Config, overrides *ConfigOverrides) ClientConfig { return &DirectClientConfig{config, config.CurrentContext, overrides, nil, NewDefaultClientConfigLoadingRules(), promptedCredentials{}} } // NewNonInteractiveClientConfig creates a DirectClientConfig using the passed context name and does not have a fallback reader for auth information func NewNonInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, configAccess ConfigAccess) ClientConfig { return &DirectClientConfig{config, contextName, overrides, nil, configAccess, promptedCredentials{}} } // NewInteractiveClientConfig creates a DirectClientConfig using the passed context name and a reader in case auth information is not provided via files or flags func NewInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, fallbackReader io.Reader, configAccess ConfigAccess) ClientConfig { return &DirectClientConfig{config, contextName, overrides, fallbackReader, configAccess, promptedCredentials{}} } func (config *DirectClientConfig) RawConfig() (clientcmdapi.Config, error) { return config.config, nil } // ClientConfig implements ClientConfig func (config *DirectClientConfig) ClientConfig() (*rest.Config, error) { // check that getAuthInfo, getContext, and getCluster do not return an error. // Do this before checking if the curent config is usable in the event that an // AuthInfo, Context, or Cluster config with user-defined names are not found. // This provides a user with the immediate cause for error if one is found configAuthInfo, err := config.getAuthInfo() if err != nil { return nil, err } _, err = config.getContext() if err != nil { return nil, err } configClusterInfo, err := config.getCluster() if err != nil { return nil, err } if err := config.ConfirmUsable(); err != nil { return nil, err } clientConfig := &rest.Config{} clientConfig.Host = configClusterInfo.Server if len(config.overrides.Timeout) > 0 { timeout, err := ParseTimeout(config.overrides.Timeout) if err != nil { return nil, err } clientConfig.Timeout = timeout } if u, err := url.ParseRequestURI(clientConfig.Host); err == nil && u.Opaque == "" && len(u.Path) > 1 { u.RawQuery = "" u.Fragment = "" clientConfig.Host = u.String() } if len(configAuthInfo.Impersonate) > 0 { clientConfig.Impersonate = rest.ImpersonationConfig{UserName: configAuthInfo.Impersonate} } // only try to read the auth information if we are secure if rest.IsConfigTransportTLS(*clientConfig) { var err error // mergo is a first write wins for map value and a last writing wins for interface values // NOTE: This behavior changed with https://github.com/imdario/mergo/commit/d304790b2ed594794496464fadd89d2bb266600a. // Our mergo.Merge version is older than this change. var persister rest.AuthProviderConfigPersister if config.configAccess != nil { authInfoName, _ := config.getAuthInfoName() persister = PersisterForUser(config.configAccess, authInfoName) } userAuthPartialConfig, err := config.getUserIdentificationPartialConfig(configAuthInfo, config.fallbackReader, persister) if err != nil { return nil, err } mergo.Merge(clientConfig, userAuthPartialConfig) serverAuthPartialConfig, err := getServerIdentificationPartialConfig(configAuthInfo, configClusterInfo) if err != nil { return nil, err } mergo.Merge(clientConfig, serverAuthPartialConfig) } return clientConfig, nil } // clientauth.Info object contain both user identification and server identification. We want different precedence orders for // both, so we have to split the objects and merge them separately // we want this order of precedence for the server identification // 1. configClusterInfo (the final result of command line flags and merged .kubeconfig files) // 2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority) // 3. load the ~/.kubernetes_auth file as a default func getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, configClusterInfo clientcmdapi.Cluster) (*rest.Config, error) { mergedConfig := &rest.Config{} // configClusterInfo holds the information identify the server provided by .kubeconfig configClientConfig := &rest.Config{} configClientConfig.CAFile = configClusterInfo.CertificateAuthority configClientConfig.CAData = configClusterInfo.CertificateAuthorityData configClientConfig.Insecure = configClusterInfo.InsecureSkipTLSVerify mergo.Merge(mergedConfig, configClientConfig) return mergedConfig, nil } // clientauth.Info object contain both user identification and server identification. We want different precedence orders for // both, so we have to split the objects and merge them separately // we want this order of precedence for user identifcation // 1. configAuthInfo minus auth-path (the final result of command line flags and merged .kubeconfig files) // 2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority) // 3. if there is not enough information to idenfity the user, load try the ~/.kubernetes_auth file // 4. if there is not enough information to identify the user, prompt if possible func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig rest.AuthProviderConfigPersister) (*rest.Config, error) { mergedConfig := &rest.Config{} // blindly overwrite existing values based on precedence if len(configAuthInfo.Token) > 0 { mergedConfig.BearerToken = configAuthInfo.Token } else if len(configAuthInfo.TokenFile) > 0 { tokenBytes, err := ioutil.ReadFile(configAuthInfo.TokenFile) if err != nil { return nil, err } mergedConfig.BearerToken = string(tokenBytes) } if len(configAuthInfo.Impersonate) > 0 { mergedConfig.Impersonate = rest.ImpersonationConfig{UserName: configAuthInfo.Impersonate} } if len(configAuthInfo.ClientCertificate) > 0 || len(configAuthInfo.ClientCertificateData) > 0 { mergedConfig.CertFile = configAuthInfo.ClientCertificate mergedConfig.CertData = configAuthInfo.ClientCertificateData mergedConfig.KeyFile = configAuthInfo.ClientKey mergedConfig.KeyData = configAuthInfo.ClientKeyData } if len(configAuthInfo.Username) > 0 || len(configAuthInfo.Password) > 0 { mergedConfig.Username = configAuthInfo.Username mergedConfig.Password = configAuthInfo.Password } if configAuthInfo.AuthProvider != nil { mergedConfig.AuthProvider = configAuthInfo.AuthProvider mergedConfig.AuthConfigPersister = persistAuthConfig } // if there still isn't enough information to authenticate the user, try prompting if !canIdentifyUser(*mergedConfig) && (fallbackReader != nil) { if len(config.promptedCredentials.username) > 0 && len(config.promptedCredentials.password) > 0 { mergedConfig.Username = config.promptedCredentials.username mergedConfig.Password = config.promptedCredentials.password return mergedConfig, nil } prompter := NewPromptingAuthLoader(fallbackReader) promptedAuthInfo, err := prompter.Prompt() if err != nil { return nil, err } promptedConfig := makeUserIdentificationConfig(*promptedAuthInfo) previouslyMergedConfig := mergedConfig mergedConfig = &rest.Config{} mergo.Merge(mergedConfig, promptedConfig) mergo.Merge(mergedConfig, previouslyMergedConfig) config.promptedCredentials.username = mergedConfig.Username config.promptedCredentials.password = mergedConfig.Password } return mergedConfig, nil } // makeUserIdentificationFieldsConfig returns a client.Config capable of being merged using mergo for only user identification information func makeUserIdentificationConfig(info clientauth.Info) *rest.Config { config := &rest.Config{} config.Username = info.User config.Password = info.Password config.CertFile = info.CertFile config.KeyFile = info.KeyFile config.BearerToken = info.BearerToken return config } // makeUserIdentificationFieldsConfig returns a client.Config capable of being merged using mergo for only server identification information func makeServerIdentificationConfig(info clientauth.Info) rest.Config { config := rest.Config{} config.CAFile = info.CAFile if info.Insecure != nil { config.Insecure = *info.Insecure } return config } func canIdentifyUser(config rest.Config) bool { return len(config.Username) > 0 || (len(config.CertFile) > 0 || len(config.CertData) > 0) || len(config.BearerToken) > 0 || config.AuthProvider != nil } // Namespace implements ClientConfig func (config *DirectClientConfig) Namespace() (string, bool, error) { if err := config.ConfirmUsable(); err != nil { return "", false, err } configContext, err := config.getContext() if err != nil { return "", false, err } if len(configContext.Namespace) == 0 { return api.NamespaceDefault, false, nil } overridden := false if config.overrides != nil && config.overrides.Context.Namespace != "" { overridden = true } return configContext.Namespace, overridden, nil } // ConfigAccess implements ClientConfig func (config *DirectClientConfig) ConfigAccess() ConfigAccess { return config.configAccess } // ConfirmUsable looks a particular context and determines if that particular part of the config is useable. There might still be errors in the config, // but no errors in the sections requested or referenced. It does not return early so that it can find as many errors as possible. func (config *DirectClientConfig) ConfirmUsable() error { validationErrors := make([]error, 0) var contextName string if len(config.contextName) != 0 { contextName = config.contextName } else { contextName = config.config.CurrentContext } if len(contextName) > 0 { _, exists := config.config.Contexts[contextName] if !exists { validationErrors = append(validationErrors, &errContextNotFound{contextName}) } } authInfoName, _ := config.getAuthInfoName() authInfo, _ := config.getAuthInfo() validationErrors = append(validationErrors, validateAuthInfo(authInfoName, authInfo)...) clusterName, _ := config.getClusterName() cluster, _ := config.getCluster() validationErrors = append(validationErrors, validateClusterInfo(clusterName, cluster)...) // when direct client config is specified, and our only error is that no server is defined, we should // return a standard "no config" error if len(validationErrors) == 1 && validationErrors[0] == ErrEmptyCluster { return newErrConfigurationInvalid([]error{ErrEmptyConfig}) } return newErrConfigurationInvalid(validationErrors) } // getContextName returns the default, or user-set context name, and a boolean that indicates // whether the default context name has been overwritten by a user-set flag, or left as its default value func (config *DirectClientConfig) getContextName() (string, bool) { if len(config.overrides.CurrentContext) != 0 { return config.overrides.CurrentContext, true } if len(config.contextName) != 0 { return config.contextName, false } return config.config.CurrentContext, false } // getAuthInfoName returns a string containing the current authinfo name for the current context, // and a boolean indicating whether the default authInfo name is overwritten by a user-set flag, or // left as its default value func (config *DirectClientConfig) getAuthInfoName() (string, bool) { if len(config.overrides.Context.AuthInfo) != 0 { return config.overrides.Context.AuthInfo, true } context, _ := config.getContext() return context.AuthInfo, false } // getClusterName returns a string containing the default, or user-set cluster name, and a boolean // indicating whether the default clusterName has been overwritten by a user-set flag, or left as // its default value func (config *DirectClientConfig) getClusterName() (string, bool) { if len(config.overrides.Context.Cluster) != 0 { return config.overrides.Context.Cluster, true } context, _ := config.getContext() return context.Cluster, false } // getContext returns the clientcmdapi.Context, or an error if a required context is not found. func (config *DirectClientConfig) getContext() (clientcmdapi.Context, error) { contexts := config.config.Contexts contextName, required := config.getContextName() var mergedContext clientcmdapi.Context if configContext, exists := contexts[contextName]; exists { mergo.Merge(&mergedContext, configContext) } else if required { return clientcmdapi.Context{}, fmt.Errorf("context %q does not exist", contextName) } mergo.Merge(&mergedContext, config.overrides.Context) return mergedContext, nil } // getAuthInfo returns the clientcmdapi.AuthInfo, or an error if a required auth info is not found. func (config *DirectClientConfig) getAuthInfo() (clientcmdapi.AuthInfo, error) { authInfos := config.config.AuthInfos authInfoName, required := config.getAuthInfoName() var mergedAuthInfo clientcmdapi.AuthInfo if configAuthInfo, exists := authInfos[authInfoName]; exists { mergo.Merge(&mergedAuthInfo, configAuthInfo) } else if required { return clientcmdapi.AuthInfo{}, fmt.Errorf("auth info %q does not exist", authInfoName) } mergo.Merge(&mergedAuthInfo, config.overrides.AuthInfo) return mergedAuthInfo, nil } // getCluster returns the clientcmdapi.Cluster, or an error if a required cluster is not found. func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) { clusterInfos := config.config.Clusters clusterInfoName, required := config.getClusterName() var mergedClusterInfo clientcmdapi.Cluster mergo.Merge(&mergedClusterInfo, config.overrides.ClusterDefaults) if configClusterInfo, exists := clusterInfos[clusterInfoName]; exists { mergo.Merge(&mergedClusterInfo, configClusterInfo) } else if required { return clientcmdapi.Cluster{}, fmt.Errorf("cluster %q does not exist", clusterInfoName) } mergo.Merge(&mergedClusterInfo, config.overrides.ClusterInfo) // An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data // otherwise, a kubeconfig containing a CA reference would return an error that "CA and insecure-skip-tls-verify couldn't both be set" caLen := len(config.overrides.ClusterInfo.CertificateAuthority) caDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData) if config.overrides.ClusterInfo.InsecureSkipTLSVerify && caLen == 0 && caDataLen == 0 { mergedClusterInfo.CertificateAuthority = "" mergedClusterInfo.CertificateAuthorityData = nil } return mergedClusterInfo, nil } // inClusterClientConfig makes a config that will work from within a kubernetes cluster container environment. type inClusterClientConfig struct{} var _ ClientConfig = inClusterClientConfig{} func (inClusterClientConfig) RawConfig() (clientcmdapi.Config, error) { return clientcmdapi.Config{}, fmt.Errorf("inCluster environment config doesn't support multiple clusters") } func (inClusterClientConfig) ClientConfig() (*rest.Config, error) { return rest.InClusterConfig() } func (inClusterClientConfig) Namespace() (string, bool, error) { // This way assumes you've set the POD_NAMESPACE environment variable using the downward API. // This check has to be done first for backwards compatibility with the way InClusterConfig was originally set up if ns := os.Getenv("POD_NAMESPACE"); ns != "" { return ns, true, nil } // Fall back to the namespace associated with the service account token, if available if data, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil { if ns := strings.TrimSpace(string(data)); len(ns) > 0 { return ns, true, nil } } return "default", false, nil } func (inClusterClientConfig) ConfigAccess() ConfigAccess { return NewDefaultClientConfigLoadingRules() } // Possible returns true if loading an inside-kubernetes-cluster is possible. func (inClusterClientConfig) Possible() bool { fi, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token") return os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "" && err == nil && !fi.IsDir() } // BuildConfigFromFlags is a helper function that builds configs from a master // url or a kubeconfig filepath. These are passed in as command line flags for cluster // components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath // are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback // to the default config. func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*rest.Config, error) { if kubeconfigPath == "" && masterUrl == "" { glog.Warningf("Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.") kubeconfig, err := rest.InClusterConfig() if err == nil { return kubeconfig, nil } glog.Warning("error creating inClusterConfig, falling back to default config: ", err) } return NewNonInteractiveDeferredLoadingClientConfig( &ClientConfigLoadingRules{ExplicitPath: kubeconfigPath}, &ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig() } // BuildConfigFromKubeconfigGetter is a helper function that builds configs from a master // url and a kubeconfigGetter. func BuildConfigFromKubeconfigGetter(masterUrl string, kubeconfigGetter KubeconfigGetter) (*rest.Config, error) { // TODO: We do not need a DeferredLoader here. Refactor code and see if we can use DirectClientConfig here. cc := NewNonInteractiveDeferredLoadingClientConfig( &ClientConfigGetter{kubeconfigGetter: kubeconfigGetter}, &ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}) return cc.ClientConfig() }
[ "\"KUBERNETES_MASTER\"", "\"POD_NAMESPACE\"", "\"KUBERNETES_SERVICE_HOST\"", "\"KUBERNETES_SERVICE_PORT\"" ]
[]
[ "POD_NAMESPACE", "KUBERNETES_SERVICE_HOST", "KUBERNETES_SERVICE_PORT", "KUBERNETES_MASTER" ]
[]
["POD_NAMESPACE", "KUBERNETES_SERVICE_HOST", "KUBERNETES_SERVICE_PORT", "KUBERNETES_MASTER"]
go
4
0
tensorflow_estimator/python/estimator/keras_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Tests for training routines.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import math import os import tempfile from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow.core.protobuf import config_pb2 from tensorflow.python import keras from tensorflow.python.feature_column import dense_features from tensorflow.python.feature_column import dense_features_v2 from tensorflow.python.framework import test_util from tensorflow.python.keras import optimizers as optimizer_v1 from tensorflow.python.keras import testing_utils from tensorflow.python.keras.layers import recurrent_v2 as rnn_v2 from tensorflow.python.keras.optimizer_v2 import gradient_descent as optimizer_v2 from tensorflow.python.keras.utils import np_utils from tensorflow.python.ops.parsing_ops import gen_parsing_ops from tensorflow.python.saved_model import utils_impl as saved_model_utils from tensorflow.python.training import saver as saver_lib from tensorflow_estimator.python.estimator import keras as keras_lib from tensorflow_estimator.python.estimator import run_config as run_config_lib from tensorflow_estimator.python.estimator.export import export_lib from tensorflow_estimator.python.estimator.inputs import numpy_io from tensorflow_estimator.python.estimator.mode_keys import ModeKeys try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None _RANDOM_SEED = 1337 _TRAIN_SIZE = 200 _INPUT_SIZE = (10,) _NUM_CLASS = 2 _TMP_DIR = '/tmp' def simple_sequential_model(): model = keras.models.Sequential() model.add(keras.layers.Dense(16, activation='relu', input_shape=_INPUT_SIZE)) model.add(keras.layers.Dropout(0.1)) model.add(keras.layers.Dense(_NUM_CLASS, activation='softmax')) return model def simple_functional_model(activation='relu'): a = keras.layers.Input(shape=_INPUT_SIZE, name='input_layer') b = keras.layers.Dense(16, activation=activation)(a) b = keras.layers.Dropout(0.1)(b) b = keras.layers.Dense(_NUM_CLASS, activation='softmax')(b) model = keras.models.Model(inputs=[a], outputs=[b]) return model def simple_subclassed_model(): class SimpleModel(keras.Model): def __init__(self): super(SimpleModel, self).__init__() self.dense1 = keras.layers.Dense(16, activation='relu') self.dp = keras.layers.Dropout(0.1) self.dense2 = keras.layers.Dense(_NUM_CLASS, activation='softmax') def call(self, inputs): x = self.dense1(inputs) x = self.dp(x) return self.dense2(x) return SimpleModel() def gen_input_fn(x, y=None, batch_size=128, num_epochs=1, shuffle=False): def input_fn(): ds = tf.compat.v1.data.Dataset.from_tensor_slices(( x, y) if y is not None else x) if shuffle: ds = ds.shuffle(1000) return ds.repeat(num_epochs).batch(batch_size) return input_fn def get_multi_inputs_multi_outputs_data(): (a_train, c_train), (a_test, c_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(16,), num_classes=3, random_seed=_RANDOM_SEED) (b_train, d_train), (b_test, d_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(16,), num_classes=2, random_seed=_RANDOM_SEED) (m_train, _), (m_test, _) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(8,), num_classes=2, random_seed=_RANDOM_SEED) c_train = np_utils.to_categorical(c_train) c_test = np_utils.to_categorical(c_test) d_train = np_utils.to_categorical(d_train) d_test = np_utils.to_categorical(d_test) train_data = { 'input_a': a_train, 'input_b': b_train, 'input_m': m_train, 'output_c': c_train, 'output_d': d_train } test_data = { 'input_a': a_test, 'input_b': b_test, 'input_m': m_test, 'output_c': c_test, 'output_d': d_test } return (train_data, test_data) def get_resource_for_simple_model( model_type='sequential', is_evaluate=False, ): if model_type == 'sequential': model = simple_sequential_model() model.build() elif model_type == 'subclass': model = simple_subclassed_model() else: assert model_type == 'functional' model = simple_functional_model() if model_type == 'subclass': input_name = 'input_1' output_name = 'output_1' else: input_name = model.input_names[0] output_name = model.output_names[0] np.random.seed(_RANDOM_SEED) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=_INPUT_SIZE, num_classes=_NUM_CLASS) y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) train_input_fn = gen_input_fn( x=randomize_io_type(x_train, input_name), y=randomize_io_type(y_train, output_name), shuffle=False, num_epochs=None, batch_size=16) evaluate_input_fn = gen_input_fn( x=randomize_io_type(x_test, input_name), y=randomize_io_type(y_test, output_name), num_epochs=1, shuffle=False) predict_input_fn = gen_input_fn( x=randomize_io_type(x_test, input_name), num_epochs=1, shuffle=False) inference_input_fn = evaluate_input_fn if is_evaluate else predict_input_fn return model, (x_train, y_train), (x_test, y_test), train_input_fn, inference_input_fn def randomize_io_type(array, name): switch = np.random.random() if switch > 0.5: return array else: return {name: array} def multi_inputs_multi_outputs_model(): input_a = keras.layers.Input(shape=(16,), name='input_a') input_b = keras.layers.Input(shape=(16,), name='input_b') input_m = keras.layers.Input(shape=(8,), dtype='string', name='input_m') dense = keras.layers.Dense(8, name='dense_1') interm_a = dense(input_a) # Read m interm_m = keras.layers.Lambda(gen_parsing_ops.string_to_number)(input_m) interm_s = keras.layers.Lambda(lambda k: k[0] * k[1])([interm_m, interm_a]) interm_b = dense(input_b) merged = keras.layers.concatenate([interm_s, interm_b], name='merge') output_c = keras.layers.Dense(3, activation='softmax', name='dense_2')(merged) output_d = keras.layers.Dense(2, activation='softmax', name='dense_3')(merged) model = keras.models.Model( inputs=[input_a, input_b, input_m], outputs=[output_c, output_d]) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics={ 'dense_2': 'categorical_accuracy', 'dense_3': 'categorical_accuracy' }) return model class MyHook(tf.compat.v1.train.SessionRunHook): def begin(self): _ = tf.compat.v1.get_variable('temp', [1]) class TestKerasEstimator(tf.test.TestCase, parameterized.TestCase): def setUp(self): self._base_dir = os.path.join(self.get_temp_dir(), 'keras_estimator_test') tf.compat.v1.gfile.MakeDirs(self._base_dir) self._config = run_config_lib.RunConfig( tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir) super(TestKerasEstimator, self).setUp() def tearDown(self): # Make sure nothing is stuck in limbo. tf.compat.v1.summary.FileWriterCache.clear() if os.path.isdir(self._base_dir): tf.compat.v1.gfile.DeleteRecursively(self._base_dir) keras.backend.clear_session() super(TestKerasEstimator, self).tearDown() @parameterized.named_parameters( dict( testcase_name='functional', model_type='functional', checkpoint_format='saver'), dict( testcase_name='sequential', model_type='sequential', checkpoint_format='saver'), dict( testcase_name='subclass', model_type='subclass', optimizer='tf_rmsprop', checkpoint_format='saver'), dict( testcase_name='functional_object_ckpt', model_type='functional', checkpoint_format='checkpoint'), dict( testcase_name='sequential_object_ckpt_w_fit', model_type='sequential', checkpoint_format='checkpoint', fit_before_export=True, optimizer='tf_rmsprop'), dict( testcase_name='functional_w_fit', model_type='functional', fit_before_export=True, optimizer='tf_rmsprop', checkpoint_format='saver'), dict( testcase_name='subclass_w_fit', model_type='subclass', fit_before_export=True, optimizer='tf_rmsprop', checkpoint_format='saver'), # b/109935364 dict( testcase_name='hooks', model_type='subclass', hook=MyHook, optimizer='tf_rmsprop', checkpoint_format='saver'), dict( testcase_name='hooks_and_fit', model_type='subclass', hook=MyHook, fit_before_export=True, optimizer='tf_rmsprop', checkpoint_format='saver'), dict( testcase_name='tf_optimizer', model_type='subclass', hook=MyHook, optimizer='tf_rmsprop', fit_before_export=True, checkpoint_format='saver')) def test_train_keras_estimator(self, model_type, checkpoint_format=None, fit_before_export=False, optimizer='rmsprop', hook=None): hooks = [hook()] if hook else None tf_optimizer = False if optimizer == 'tf_rmsprop': tf_optimizer = True optimizer = tf.compat.v1.train.RMSPropOptimizer(1e-3) keras_model, (x_train, y_train), (_, _), train_input_fn, eval_input_fn = ( get_resource_for_simple_model(model_type=model_type, is_evaluate=True)) keras_model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) if fit_before_export: keras_model.fit(x_train, y_train, epochs=1) est_keras = keras_lib.model_to_estimator( keras_model=keras_model, config=self._config, checkpoint_format=checkpoint_format) est_keras.train( input_fn=train_input_fn, steps=_TRAIN_SIZE / 16, hooks=hooks) before_eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) est_keras.train( input_fn=train_input_fn, steps=_TRAIN_SIZE / 16, hooks=hooks) after_eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) self.assertLess(after_eval_results['loss'], before_eval_results['loss']) if checkpoint_format == 'object' and tf_optimizer: latest_checkpoint = tf.train.latest_checkpoint(est_keras.model_dir) keras_model.load_weights(latest_checkpoint) def test_train_with_dense_features(self): feature_dict = { 'sex': np.int64([1, 1, 1, 1, 0]), 'cp': np.int64([0, 3, 3, 2, 1]), 'slope': np.int64([3, 2, 0, 3, 1]), } label = np.int64([0, 1, 0, 0, 0]) train_input_fn = numpy_io.numpy_input_fn( x=feature_dict, y=label, num_epochs=1, shuffle=False) feature_columns = list() input_features = dict() for feature_name, data_array in feature_dict.items(): feature_columns.append( tf.feature_column.indicator_column( tf.feature_column.categorical_column_with_identity( key=feature_name, num_buckets=np.size(np.unique(data_array))))) input_features[feature_name] = keras.layers.Input( name=feature_name, shape=(np.size(np.unique(data_array)),), dtype=tf.dtypes.int64) x = dense_features.DenseFeatures(feature_columns)(input_features) x = keras.layers.Dense(16, activation='relu')(x) logits = keras.layers.Dense(1, activation='linear')(x) model = keras.Model(inputs=input_features, outputs=logits) model.compile( optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) estimator_model = keras_lib.model_to_estimator(keras_model=model) estimator_model.train(input_fn=train_input_fn, steps=5) # TODO(b/139845232): Enable after TF2 nightly's start. def DISABLED_test_train_with_dense_features_embedding(self): feature_dict = { 'sex': np.int64([1, 1, 1, 1, 0]), 'cp': np.int64([0, 3, 3, 2, 1]), 'slope': np.int64([3, 2, 0, 3, 1]), } label = np.int64([0, 1, 0, 0, 0]) train_input_fn = numpy_io.numpy_input_fn( x=feature_dict, y=label, num_epochs=1, shuffle=False) feature_columns = list() input_features = dict() for feature_name, data_array in feature_dict.items(): feature_columns.append( tf.feature_column.embedding_column( tf.feature_column.categorical_column_with_identity( key=feature_name, num_buckets=np.size(np.unique(data_array))), dimension=3)) input_features[feature_name] = keras.layers.Input( name=feature_name, shape=(np.size(np.unique(data_array)),), dtype=tf.dtypes.int64) df = dense_features.DenseFeatures(feature_columns) x = df(input_features) x = keras.layers.Dense(16, activation='relu')(x) logits = keras.layers.Dense(1, activation='linear')(x) model = keras.Model(inputs=input_features, outputs=logits) model.compile( optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) estimator_model = keras_lib.model_to_estimator(keras_model=model) estimator_model.train(input_fn=train_input_fn, steps=5) # We assert that we find the embedding_weights variables in the dependencies # for the DenseFeatures layer. dependency_names = [x.name for x in df._checkpoint_dependencies] self.assertNotIn('embedding_weights', dependency_names) self.assertIn('cp_embedding/embedding_weights', dependency_names) self.assertIn('sex_embedding/embedding_weights', dependency_names) self.assertIn('slope_embedding/embedding_weights', dependency_names) # TODO(b/139845232): Enable after TF2 nightly's start. def DISABLED_test_train_with_dense_features_v2(self): feature_dict = { 'sex': np.int64([1, 1, 1, 1, 0]), 'cp': np.int64([0, 3, 3, 2, 1]), 'slope': np.int64([3, 2, 0, 3, 1]), } label = np.int64([0, 1, 0, 0, 0]) train_input_fn = numpy_io.numpy_input_fn( x=feature_dict, y=label, num_epochs=1, shuffle=False) feature_columns = list() input_features = dict() for feature_name, data_array in feature_dict.items(): feature_columns.append( tf.feature_column.embedding_column( tf.feature_column.categorical_column_with_identity( key=feature_name, num_buckets=np.size(np.unique(data_array))), dimension=3)) input_features[feature_name] = keras.layers.Input( name=feature_name, shape=(np.size(np.unique(data_array)),), dtype=tf.dtypes.int64) df = dense_features_v2.DenseFeatures(feature_columns) x = df(input_features) x = keras.layers.Dense(16, activation='relu')(x) logits = keras.layers.Dense(1, activation='linear')(x) model = keras.Model(inputs=input_features, outputs=logits) model.compile( optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) estimator_model = keras_lib.model_to_estimator(keras_model=model) estimator_model.train(input_fn=train_input_fn, steps=5) # We assert that we find the embedding_weights variables in the dependencies # for the DenseFeatures layer. dependency_names = [x.name for x in df._checkpoint_dependencies] self.assertNotIn('embedding_weights', dependency_names) self.assertIn('cp_embedding/embedding_weights', dependency_names) self.assertIn('sex_embedding/embedding_weights', dependency_names) self.assertIn('slope_embedding/embedding_weights', dependency_names) def test_evaluate(self): keras_model, (x_train, y_train), ( x_test, y_test), _, eval_input_fn = get_resource_for_simple_model( model_type='functional', is_evaluate=True) metrics = [ 'binary_accuracy', 'binary_crossentropy', 'categorical_accuracy', 'categorical_crossentropy', 'cosine_proximity', 'hinge', 'kullback_leibler_divergence', 'mean_absolute_error', 'mean_absolute_percentage_error', 'mean_squared_error', 'mean_squared_logarithmic_error', 'poisson', 'squared_hinge', 'top_k_categorical_accuracy' ] keras_model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=metrics) keras_model.fit(x_train, y_train, epochs=1) keras_eval = keras_model.evaluate(x_test, y_test, batch_size=32) keras_est = keras_lib.model_to_estimator( keras_model=keras_model, config=self._config) est_eval = keras_est.evaluate(input_fn=eval_input_fn) metrics = ['loss'] + metrics # Check loss and all metrics match between keras and estimator. def shift(val): if val == 0: return 0 else: return val / 10**int(math.log10(abs(val))) for i, metric_name in enumerate(metrics): self.assertAlmostEqual( shift(keras_eval[i]), shift(est_eval[metric_name]), places=4, msg='%s mismatch, keras model: %s, estimator: %s' % (metric_name, keras_eval[i], est_eval[metric_name])) def test_predict(self): # Check that predict on a pretrained model yield the same result. keras_model, (x_train, y_train), ( x_test, _), _, pred_input_fn = get_resource_for_simple_model( model_type='sequential', is_evaluate=False) keras_model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) def test_multi_inputs_multi_outputs_with_input_fn_as_dict(self): train_data, test_data = get_multi_inputs_multi_outputs_data() def train_input_fn(): input_dict = { 'input_a': train_data['input_a'], 'input_b': train_data['input_b'], 'input_m': train_data['input_m'].astype(np.str) } output_dict = { 'dense_2': train_data['output_c'], 'dense_3': train_data['output_d'] } return input_dict, output_dict def eval_input_fn(): input_dict = { 'input_a': test_data['input_a'], 'input_b': test_data['input_b'], 'input_m': test_data['input_m'].astype(np.str) } output_dict = { 'dense_2': test_data['output_c'], 'dense_3': test_data['output_d'] } return input_dict, output_dict def pred_input_fn(): input_dict = { 'input_a': test_data['input_a'], 'input_b': test_data['input_b'], 'input_m': test_data['input_m'].astype(np.str) } return input_dict self.do_test_multi_inputs_multi_outputs_with_input_fn( train_input_fn, eval_input_fn, pred_input_fn) def test_multi_inputs_multi_outputs_with_input_fn_as_list(self): train_data, test_data = get_multi_inputs_multi_outputs_data() def train_input_fn(): input_list = [ train_data['input_a'], train_data['input_b'], train_data['input_m'].astype(np.str) ] output_list = [train_data['output_c'], train_data['output_d']] return input_list, output_list def eval_input_fn(): input_list = [ test_data['input_a'], test_data['input_b'], test_data['input_m'].astype(np.str) ] output_list = [test_data['output_c'], test_data['output_d']] return input_list, output_list def pred_input_fn(): input_list = [ test_data['input_a'], test_data['input_b'], test_data['input_m'].astype(np.str) ] return input_list self.do_test_multi_inputs_multi_outputs_with_input_fn( train_input_fn, eval_input_fn, pred_input_fn) def do_test_multi_inputs_multi_outputs_with_input_fn(self, train_input_fn, eval_input_fn, pred_input_fn): model = multi_inputs_multi_outputs_model() est_keras = keras_lib.model_to_estimator( keras_model=model, config=self._config) baseline_eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) est_keras.train(input_fn=train_input_fn, steps=_TRAIN_SIZE / 16) eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) self.assertLess(eval_results['loss'], baseline_eval_results['loss']) est_keras.predict(input_fn=pred_input_fn) def test_init_from_file(self): if h5py is None: return # Skip test if models cannot be saved. keras_model, (x_train, y_train), ( x_test, _), _, pred_input_fn = get_resource_for_simple_model( model_type='functional', is_evaluate=False) keras_model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['categorical_accuracy']) keras_model.fit(x_train, y_train, epochs=1) keras_pred = [np.argmax(y) for y in keras_model.predict(x_test)] fname = os.path.join(self._base_dir, 'keras_model.h5') keras.models.save_model(keras_model, fname) keras_est = keras_lib.model_to_estimator( keras_model_path=fname, config=self._config) est_pred = [ np.argmax(y[keras_model.output_names[0]]) for y in keras_est.predict(input_fn=pred_input_fn) ] self.assertAllEqual(est_pred, keras_pred) def test_keras_model_init_error(self): with self.assertRaisesRegexp(ValueError, 'Either'): keras_lib.model_to_estimator() keras_model = simple_sequential_model() with self.assertRaisesRegexp(ValueError, 'not both'): keras_lib.model_to_estimator( keras_model=keras_model, keras_model_path=tempfile.mkdtemp(dir=self._base_dir)) keras_model = simple_sequential_model() with self.assertRaisesRegexp(ValueError, 'compiled'): keras_lib.model_to_estimator(keras_model=keras_model) def test_invalid_ionames_error(self): (x_train, y_train), (_, _) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=100, input_shape=(10,), num_classes=2) y_train = np_utils.to_categorical(y_train) def invald_input_name_input_fn(): input_dict = {'invalid_input_name': x_train} return input_dict, y_train def invald_output_name_input_fn(): input_dict = {'input_layer': x_train} output_dict = {'invalid_output_name': y_train} return input_dict, output_dict model = simple_functional_model() model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) est_keras = keras_lib.model_to_estimator( keras_model=model, config=self._config) with self.assertRaisesRegexp( KeyError, 'features keys: .*invalid_input_name.*Missed keys: .*input_layer'): est_keras.train(input_fn=invald_input_name_input_fn, steps=100) with self.assertRaisesRegexp( KeyError, 'labels keys: .*invalid_output_name.*Missed keys: .*dense_1'): est_keras.train(input_fn=invald_output_name_input_fn, steps=100) def test_custom_objects(self): def relu6(x): return keras.backend.relu(x, max_value=6) keras_model = simple_functional_model(activation=relu6) keras_model.compile(loss='categorical_crossentropy', optimizer='adam') custom_objects = {'relu6': relu6} (x_train, y_train), _ = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(10,), num_classes=2) y_train = np_utils.to_categorical(y_train, 2) input_name = keras_model.input_names[0] output_name = keras_model.output_names[0] train_input_fn = gen_input_fn( x=randomize_io_type(x_train, input_name), y=randomize_io_type(y_train, output_name), shuffle=False, num_epochs=None, batch_size=16) with self.assertRaisesRegexp(ValueError, 'relu6'): est = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=tempfile.mkdtemp(dir=self._base_dir)) est.train(input_fn=train_input_fn, steps=1) est = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=tempfile.mkdtemp(dir=self._base_dir), custom_objects=custom_objects) est.train(input_fn=train_input_fn, steps=1) def test_tf_config(self): keras_model, (_, _), (_, _), _, _ = get_resource_for_simple_model() keras_model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['mse', keras.metrics.CategoricalAccuracy()]) tf_config = json.dumps({ 'cluster': { run_config_lib.TaskType.PS: ['localhost:1234'], run_config_lib.TaskType.WORKER: ['localhost:1236'], run_config_lib.TaskType.MASTER: ['localhost:1238'] }, 'task': { 'type': run_config_lib.TaskType.MASTER, 'index': 0 } }) with tf.compat.v1.test.mock.patch.dict('os.environ', {'TF_CONFIG': tf_config}): keras_lib.model_to_estimator( keras_model=keras_model, model_dir=tempfile.mkdtemp(dir=self._base_dir)) def test_gpu_config(self): with tf.Graph().as_default(): keras_model, (_, _), (_, _), _, _ = get_resource_for_simple_model() keras_model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['mse', keras.metrics.CategoricalAccuracy()]) gpu_options = config_pb2.GPUOptions(per_process_gpu_memory_fraction=0.3) sess_config = config_pb2.ConfigProto(gpu_options=gpu_options) self._config._session_config = sess_config keras_lib.model_to_estimator(keras_model=keras_model, config=self._config) self.assertEqual( keras.backend.get_session( )._config.gpu_options.per_process_gpu_memory_fraction, gpu_options.per_process_gpu_memory_fraction) def test_with_empty_config(self): keras_model, _, _, _, _ = get_resource_for_simple_model( model_type='sequential', is_evaluate=True) keras_model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['mse', keras.metrics.CategoricalAccuracy()]) est_keras = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=self._base_dir, config=run_config_lib.RunConfig()) self.assertEqual(run_config_lib.get_default_session_config(), est_keras._session_config) self.assertEqual(est_keras._session_config, est_keras._config.session_config) self.assertEqual(self._base_dir, est_keras._config.model_dir) self.assertEqual(self._base_dir, est_keras._model_dir) est_keras = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=self._base_dir, config=None) self.assertEqual(run_config_lib.get_default_session_config(), est_keras._session_config) self.assertEqual(est_keras._session_config, est_keras._config.session_config) self.assertEqual(self._base_dir, est_keras._config.model_dir) self.assertEqual(self._base_dir, est_keras._model_dir) def test_with_empty_config_and_empty_model_dir(self): keras_model, _, _, _, _ = get_resource_for_simple_model( model_type='sequential', is_evaluate=True) keras_model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['mse', keras.metrics.CategoricalAccuracy()]) with tf.compat.v1.test.mock.patch.object( tempfile, 'mkdtemp', return_value=_TMP_DIR): est_keras = keras_lib.model_to_estimator( keras_model=keras_model, config=run_config_lib.RunConfig()) self.assertEqual(est_keras._model_dir, _TMP_DIR) def test_with_conflicting_model_dir_and_config(self): keras_model, _, _, _, _ = get_resource_for_simple_model( model_type='sequential', is_evaluate=True) keras_model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['mse', keras.metrics.CategoricalAccuracy()]) with self.assertRaisesRegexp( ValueError, '`model_dir` are set both in ' 'constructor and `RunConfig`'): keras_lib.model_to_estimator( keras_model=keras_model, model_dir=self._base_dir, config=run_config_lib.RunConfig(model_dir=_TMP_DIR)) def test_pretrained_weights(self): keras_model, (_, _), (_, _), _, _ = get_resource_for_simple_model() keras_model.compile( loss='categorical_crossentropy', optimizer=tf.compat.v1.train.RMSPropOptimizer(1e-3), metrics=['mse', keras.metrics.CategoricalAccuracy()]) keras_model.train_on_batch( np.random.random((10,) + _INPUT_SIZE), np.random.random( (10, _NUM_CLASS))) weights = keras_model.get_weights() keras_model, (_, _), (_, _), _, _ = get_resource_for_simple_model() keras_model.set_weights(weights) if tf.executing_eagerly(): sgd_optimizer = optimizer_v2.SGD(lr=0.0001, momentum=0.9) else: sgd_optimizer = optimizer_v1.SGD(lr=0.0001, momentum=0.9) keras_model.compile( loss='categorical_crossentropy', optimizer=sgd_optimizer, metrics=['mse', keras.metrics.CategoricalAccuracy()]) keras_lib.model_to_estimator(keras_model=keras_model, config=self._config) def assert_increasing_global_step(self, optimizer): keras_model, _, _, train_input_fn, _ = get_resource_for_simple_model( model_type='sequential', is_evaluate=True) keras_model.compile( loss='categorical_crossentropy', optimizer=optimizer, metrics=['mse', keras.metrics.CategoricalAccuracy()]) with self.cached_session() as sess: keras_model_fn = keras_lib._create_keras_model_fn(keras_model) global_step = tf.compat.v1.train.create_global_step() features, labels = train_input_fn().make_one_shot_iterator().get_next() spec = keras_model_fn(features, labels, mode=ModeKeys.TRAIN) sess.run(tf.compat.v1.initializers.global_variables()) sess.run(tf.compat.v1.initializers.local_variables()) self.assertEqual(global_step.eval(), 0) # Sanity check sess.run(spec.train_op) self.assertEqual(global_step.eval(), 1) @test_util.run_v1_only('training_util.create_global_step is v1 only.') def test_model_fn_increments_global_step_tf_optimizer(self): self.assert_increasing_global_step( tf.compat.v1.train.RMSPropOptimizer(1e-3)) @test_util.run_v1_only('training_util.create_global_step is v1 only.') def test_model_fn_increments_global_step_keras_optimizer(self): self.assert_increasing_global_step('rmsprop') @parameterized.named_parameters( dict(testcase_name='object_ckpt', checkpoint_format='checkpoint'), dict(testcase_name='name_ckpt', checkpoint_format='saver')) def test_export_keras_estimator(self, checkpoint_format): keras_model, (x_train, y_train), ( _, _), train_input_fn, _ = get_resource_for_simple_model( model_type='sequential', is_evaluate=False) keras_model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) keras_model.fit(x_train, y_train, epochs=1) bias_value = keras.backend.get_value(keras_model.layers[0].bias) est_keras = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=tempfile.mkdtemp(dir=self._base_dir), checkpoint_format=checkpoint_format) def serving_input_receiver_fn(): feature_spec = { 'dense_input': tf.io.FixedLenFeature([1], dtype=tf.dtypes.float32) } return export_lib.build_parsing_serving_input_receiver_fn(feature_spec) # Try immediately exporting, testing that (1) exported values are the same, # and (2) estimator can be exported without saving a checkpoint into the # model directory. saved_model_dir = est_keras.export_saved_model( tempfile.mkdtemp(dir=self._base_dir), serving_input_receiver_fn()) variables_path = saved_model_utils.get_variables_path(saved_model_dir) variable_name = 'dense/bias' if checkpoint_format == 'checkpoint': names_to_keys = saver_lib.object_graph_key_mapping(variables_path) variable_name = names_to_keys[variable_name] self.assertAllClose(bias_value, tf.train.load_variable(variables_path, variable_name)) # Export the estimator after training a bit. est_keras.train(input_fn=train_input_fn, steps=_TRAIN_SIZE / 16) saved_model_dir = est_keras.export_saved_model( tempfile.mkdtemp(dir=self._base_dir), serving_input_receiver_fn()) variables_path = saved_model_utils.get_variables_path(saved_model_dir) self.assertNotAllClose( bias_value, tf.train.load_variable(variables_path, variable_name)) def test_export_subclassed_model_retains_model_state(self): keras_model, (x_train, y_train), ( _, _), train_input_fn, eval_input_fn = get_resource_for_simple_model( model_type='subclass', is_evaluate=True) keras_model.compile( optimizer=tf.compat.v1.train.RMSPropOptimizer(1e-3), loss='categorical_crossentropy', metrics=['accuracy']) keras_model.fit(x_train, y_train, epochs=1) iterations = keras.backend.get_value(keras_model.optimizer.iterations) optimizer = keras_model.optimizer est_keras = keras_lib.model_to_estimator( keras_model=keras_model, config=self._config, checkpoint_format='saver') est_keras.train(input_fn=train_input_fn, steps=_TRAIN_SIZE / 16) # Subclassed models resets the model object. Assert that attributes are # properly restored. iterations_after = keras.backend.get_value(keras_model.optimizer.iterations) self.assertEqual(optimizer, keras_model.optimizer) self.assertEqual(iterations, iterations_after) # TODO(b/132839451): model.fit results in an error after model_to_estimator. # keras_model.fit(x_train, y_train, epochs=1) def test_warm_start_from_keras_ckpt(self): keras_model, (x_train, y_train), ( _, _), train_input_fn, eval_input_fn = get_resource_for_simple_model( model_type='functional', is_evaluate=True) keras_model.compile( optimizer=tf.compat.v1.train.RMSPropOptimizer(1e-3), loss='categorical_crossentropy', metrics=['accuracy']) keras_model.fit(x_train, y_train, epochs=1) warm_start_path = os.path.join(self._config.model_dir, 'keras', 'warm_start.ckpt') keras_model.save_weights(warm_start_path) est_keras = keras_lib.model_to_estimator( keras_model=keras_model, config=self._config, checkpoint_format='saver') self.assertEqual(warm_start_path, est_keras._warm_start_settings.ckpt_to_initialize_from) before_eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) est_keras.train(input_fn=train_input_fn, steps=_TRAIN_SIZE / 16) after_eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) self.assertLess(after_eval_results['loss'], before_eval_results['loss']) def test_sample_weights(self): # Create simple pass-through model input_layer = keras.layers.Input(shape=1, name='input_layer') keras_model = keras.Model(inputs=input_layer, outputs=input_layer) keras_model.compile(loss='mean_absolute_error', optimizer='adam') features = [[0.], [0], [1], [1]] sample_weights = [0, .4, 1, 1] targets = [[0], [1], [0], [1]] expected_loss = keras_model.test_on_batch( tf.constant(features), tf.constant(targets), tf.constant(sample_weights)) def input_fn(): dataset = tf.compat.v1.data.Dataset.from_tensors(({ 'features': features, 'sample_weights': sample_weights }, targets)) return dataset est_keras = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=tempfile.mkdtemp(dir=self._base_dir)) eval_results = est_keras.evaluate(input_fn, steps=1) self.assertAllClose(expected_loss, eval_results['loss']) # Test multiple with outputs and sample weights. keras_model = keras.Model( inputs=input_layer, outputs=[input_layer, input_layer]) keras_model.compile(loss='mean_absolute_error', optimizer='adam') expected_loss = keras_model.test_on_batch( tf.constant(features), [tf.constant(targets), tf.constant(targets)], [tf.constant(sample_weights), tf.constant(sample_weights)])[0] def input_fn_multiple_targets(): dataset = tf.compat.v1.data.Dataset.from_tensors( (features, sample_weights, targets)) dataset = dataset.map(lambda x, y, z: ({ 'features': x, 'sample_weights': (y, y) }, (z, z))) return dataset est_keras = keras_lib.model_to_estimator( keras_model=keras_model, model_dir=tempfile.mkdtemp(dir=self._base_dir)) eval_results = est_keras.evaluate(input_fn_multiple_targets, steps=1) self.assertAllClose(expected_loss, eval_results['loss']) @parameterized.parameters([rnn_v2.LSTM, rnn_v2.GRU]) def test_model_to_estimator_with_rnn(self, layer): # See https://github.com/tensorflow/tensorflow/issues/27750 for details. timestep = 10 rnn_cell_size = 8 layers = [ keras.layers.Reshape([timestep, 1], input_shape=[ timestep, ]), layer(rnn_cell_size, return_sequences=True), layer(rnn_cell_size), keras.layers.Dense(1) ] model = keras.Sequential(layers) model.compile(loss='mse', optimizer='sgd') keras_lib.model_to_estimator( keras_model=model, checkpoint_format='checkpoint', model_dir=tempfile.mkdtemp(dir=self._base_dir)) if __name__ == '__main__': tf.test.main()
[]
[]
[]
[]
[]
python
0
0
nats-cast/server/server.go
package main import ( "fmt" "log" "net/http" "os" "github.com/gorilla/websocket" "github.com/nats-io/nats" ) func handleWebSocket(rw http.ResponseWriter, r *http.Request) { up := websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } ws, err := up.Upgrade(rw, r, nil) if err != nil { log.Println(err) return } defer ws.Close() ns, err := nats.Connect(os.Getenv("NATS_URI")) if err != nil { log.Println(err) ws.WriteMessage(websocket.TextMessage, []byte(err.Error())) return } defer ns.Close() for { _, msg, err := ws.ReadMessage() if _, is := err.(*websocket.CloseError); is { return } else if err != nil { log.Println(err) return } if err := ns.Publish("nats-cast", msg); err != nil { log.Println(err) return } } } func serveIndex(rw http.ResponseWriter, req *http.Request) { fmt.Fprintln(rw, indexHTML) } func main() { http.HandleFunc("/ws", handleWebSocket) http.HandleFunc("/", serveIndex) if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil { log.Fatal(err) } }
[ "\"NATS_URI\"", "\"PORT\"" ]
[]
[ "PORT", "NATS_URI" ]
[]
["PORT", "NATS_URI"]
go
2
0
registry/registry.go
package registry import ( "context" "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "net/http" "os" "os/signal" "strings" "syscall" "time" logrus_bugsnag "github.com/Shopify/logrus-bugsnag" logstash "github.com/bshuster-repo/logrus-logstash-hook" "github.com/bugsnag/bugsnag-go" "github.com/docker/go-metrics" gorhandlers "github.com/gorilla/handlers" "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/yvasiyarov/gorelic" "golang.org/x/crypto/acme" "golang.org/x/crypto/acme/autocert" "github.com/sivabalanams/distribution/v3/configuration" dcontext "github.com/sivabalanams/distribution/v3/context" "github.com/sivabalanams/distribution/v3/health" "github.com/sivabalanams/distribution/v3/registry/handlers" "github.com/sivabalanams/distribution/v3/registry/listener" "github.com/sivabalanams/distribution/v3/uuid" "github.com/sivabalanams/distribution/v3/version" ) // a map of TLS cipher suite names to constants in https://golang.org/pkg/crypto/tls/#pkg-constants var cipherSuites = map[string]uint16{ // TLS 1.0 - 1.2 cipher suites "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_RSA_WITH_AES_128_CBC_SHA256, "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, // TLS 1.3 cipher suites "TLS_AES_128_GCM_SHA256": tls.TLS_AES_128_GCM_SHA256, "TLS_AES_256_GCM_SHA384": tls.TLS_AES_256_GCM_SHA384, "TLS_CHACHA20_POLY1305_SHA256": tls.TLS_CHACHA20_POLY1305_SHA256, } // a list of default ciphersuites to utilize var defaultCipherSuites = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_AES_128_GCM_SHA256, tls.TLS_CHACHA20_POLY1305_SHA256, tls.TLS_AES_256_GCM_SHA384, } // maps tls version strings to constants var defaultTLSVersionStr = "tls1.2" var tlsVersions = map[string]uint16{ // user specified values "tls1.0": tls.VersionTLS10, "tls1.1": tls.VersionTLS11, "tls1.2": tls.VersionTLS12, "tls1.3": tls.VersionTLS13, } // this channel gets notified when process receives signal. It is global to ease unit testing var quit = make(chan os.Signal, 1) // ServeCmd is a cobra command for running the registry. var ServeCmd = &cobra.Command{ Use: "serve <config>", Short: "`serve` stores and distributes Docker images", Long: "`serve` stores and distributes Docker images.", Run: func(cmd *cobra.Command, args []string) { // setup context ctx := dcontext.WithVersion(dcontext.Background(), version.Version) config, err := resolveConfiguration(args) if err != nil { fmt.Fprintf(os.Stderr, "configuration error: %v\n", err) cmd.Usage() os.Exit(1) } if config.HTTP.Debug.Addr != "" { go func(addr string) { log.Infof("debug server listening %v", addr) if err := http.ListenAndServe(addr, nil); err != nil { log.Fatalf("error listening on debug interface: %v", err) } }(config.HTTP.Debug.Addr) } registry, err := NewRegistry(ctx, config) if err != nil { log.Fatalln(err) } if config.HTTP.Debug.Prometheus.Enabled { path := config.HTTP.Debug.Prometheus.Path if path == "" { path = "/metrics" } log.Info("providing prometheus metrics on ", path) http.Handle(path, metrics.Handler()) } if err = registry.ListenAndServe(); err != nil { log.Fatalln(err) } }, } // A Registry represents a complete instance of the registry. // TODO(aaronl): It might make sense for Registry to become an interface. type Registry struct { config *configuration.Configuration app *handlers.App server *http.Server } // NewRegistry creates a new registry from a context and configuration struct. func NewRegistry(ctx context.Context, config *configuration.Configuration) (*Registry, error) { var err error ctx, err = configureLogging(ctx, config) if err != nil { return nil, fmt.Errorf("error configuring logger: %v", err) } configureBugsnag(config) // inject a logger into the uuid library. warns us if there is a problem // with uuid generation under low entropy. uuid.Loggerf = dcontext.GetLogger(ctx).Warnf app := handlers.NewApp(ctx, config) // TODO(aaronl): The global scope of the health checks means NewRegistry // can only be called once per process. app.RegisterHealthChecks() handler := configureReporting(app) handler = alive("/", handler) handler = health.Handler(handler) handler = panicHandler(handler) if !config.Log.AccessLog.Disabled { handler = gorhandlers.CombinedLoggingHandler(os.Stdout, handler) } server := &http.Server{ Handler: handler, } return &Registry{ app: app, config: config, server: server, }, nil } // takes a list of cipher suites and converts it to a list of respective tls constants // if an empty list is provided, then the defaults will be used func getCipherSuites(names []string) ([]uint16, error) { if len(names) == 0 { return defaultCipherSuites, nil } cipherSuiteConsts := make([]uint16, len(names)) for i, name := range names { cipherSuiteConst, ok := cipherSuites[name] if !ok { return nil, fmt.Errorf("unknown TLS cipher suite '%s' specified for http.tls.cipherSuites", name) } cipherSuiteConsts[i] = cipherSuiteConst } return cipherSuiteConsts, nil } // takes a list of cipher suite ids and converts it to a list of respective names func getCipherSuiteNames(ids []uint16) []string { if len(ids) == 0 { return nil } names := make([]string, len(ids)) for i, id := range ids { names[i] = tls.CipherSuiteName(id) } return names } // ListenAndServe runs the registry's HTTP server. func (registry *Registry) ListenAndServe() error { config := registry.config ln, err := listener.NewListener(config.HTTP.Net, config.HTTP.Addr) if err != nil { return err } if config.HTTP.TLS.Certificate != "" || config.HTTP.TLS.LetsEncrypt.CacheFile != "" { if config.HTTP.TLS.MinimumTLS == "" { config.HTTP.TLS.MinimumTLS = defaultTLSVersionStr } tlsMinVersion, ok := tlsVersions[config.HTTP.TLS.MinimumTLS] if !ok { return fmt.Errorf("unknown minimum TLS level '%s' specified for http.tls.minimumtls", config.HTTP.TLS.MinimumTLS) } dcontext.GetLogger(registry.app).Infof("restricting TLS version to %s or higher", config.HTTP.TLS.MinimumTLS) tlsCipherSuites, err := getCipherSuites(config.HTTP.TLS.CipherSuites) if err != nil { return err } dcontext.GetLogger(registry.app).Infof("restricting TLS cipher suites to: %s", strings.Join(getCipherSuiteNames(tlsCipherSuites), ",")) tlsConf := &tls.Config{ ClientAuth: tls.NoClientCert, NextProtos: nextProtos(config), MinVersion: tlsMinVersion, PreferServerCipherSuites: true, CipherSuites: tlsCipherSuites, } if config.HTTP.TLS.LetsEncrypt.CacheFile != "" { if config.HTTP.TLS.Certificate != "" { return fmt.Errorf("cannot specify both certificate and Let's Encrypt") } m := &autocert.Manager{ HostPolicy: autocert.HostWhitelist(config.HTTP.TLS.LetsEncrypt.Hosts...), Cache: autocert.DirCache(config.HTTP.TLS.LetsEncrypt.CacheFile), Email: config.HTTP.TLS.LetsEncrypt.Email, Prompt: autocert.AcceptTOS, } tlsConf.GetCertificate = m.GetCertificate tlsConf.NextProtos = append(tlsConf.NextProtos, acme.ALPNProto) } else { tlsConf.Certificates = make([]tls.Certificate, 1) tlsConf.Certificates[0], err = tls.LoadX509KeyPair(config.HTTP.TLS.Certificate, config.HTTP.TLS.Key) if err != nil { return err } } if len(config.HTTP.TLS.ClientCAs) != 0 { pool := x509.NewCertPool() for _, ca := range config.HTTP.TLS.ClientCAs { caPem, err := ioutil.ReadFile(ca) if err != nil { return err } if ok := pool.AppendCertsFromPEM(caPem); !ok { return fmt.Errorf("could not add CA to pool") } } for _, subj := range pool.Subjects() { dcontext.GetLogger(registry.app).Debugf("CA Subject: %s", string(subj)) } tlsConf.ClientAuth = tls.RequireAndVerifyClientCert tlsConf.ClientCAs = pool } ln = tls.NewListener(ln, tlsConf) dcontext.GetLogger(registry.app).Infof("listening on %v, tls", ln.Addr()) } else { dcontext.GetLogger(registry.app).Infof("listening on %v", ln.Addr()) } if config.HTTP.DrainTimeout == 0 { return registry.server.Serve(ln) } // setup channel to get notified on SIGTERM signal signal.Notify(quit, syscall.SIGTERM) serveErr := make(chan error) // Start serving in goroutine and listen for stop signal in main thread go func() { serveErr <- registry.server.Serve(ln) }() select { case err := <-serveErr: return err case <-quit: dcontext.GetLogger(registry.app).Info("stopping server gracefully. Draining connections for ", config.HTTP.DrainTimeout) // shutdown the server with a grace period of configured timeout c, cancel := context.WithTimeout(context.Background(), config.HTTP.DrainTimeout) defer cancel() return registry.server.Shutdown(c) } } func configureReporting(app *handlers.App) http.Handler { var handler http.Handler = app if app.Config.Reporting.Bugsnag.APIKey != "" { handler = bugsnag.Handler(handler) } if app.Config.Reporting.NewRelic.LicenseKey != "" { agent := gorelic.NewAgent() agent.NewrelicLicense = app.Config.Reporting.NewRelic.LicenseKey if app.Config.Reporting.NewRelic.Name != "" { agent.NewrelicName = app.Config.Reporting.NewRelic.Name } agent.CollectHTTPStat = true agent.Verbose = app.Config.Reporting.NewRelic.Verbose agent.Run() handler = agent.WrapHTTPHandler(handler) } return handler } // configureLogging prepares the context with a logger using the // configuration. func configureLogging(ctx context.Context, config *configuration.Configuration) (context.Context, error) { log.SetLevel(logLevel(config.Log.Level)) formatter := config.Log.Formatter if formatter == "" { formatter = "text" // default formatter } switch formatter { case "json": log.SetFormatter(&log.JSONFormatter{ TimestampFormat: time.RFC3339Nano, DisableHTMLEscape: true, }) case "text": log.SetFormatter(&log.TextFormatter{ TimestampFormat: time.RFC3339Nano, }) case "logstash": log.SetFormatter(&logstash.LogstashFormatter{ Formatter: &logrus.JSONFormatter{TimestampFormat: time.RFC3339Nano}, }) default: // just let the library use default on empty string. if config.Log.Formatter != "" { return ctx, fmt.Errorf("unsupported logging formatter: %q", config.Log.Formatter) } } if config.Log.Formatter != "" { log.Debugf("using %q logging formatter", config.Log.Formatter) } if len(config.Log.Fields) > 0 { // build up the static fields, if present. var fields []interface{} for k := range config.Log.Fields { fields = append(fields, k) } ctx = dcontext.WithValues(ctx, config.Log.Fields) ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, fields...)) } dcontext.SetDefaultLogger(dcontext.GetLogger(ctx)) return ctx, nil } func logLevel(level configuration.Loglevel) log.Level { l, err := log.ParseLevel(string(level)) if err != nil { l = log.InfoLevel log.Warnf("error parsing level %q: %v, using %q ", level, err, l) } return l } // configureBugsnag configures bugsnag reporting, if enabled func configureBugsnag(config *configuration.Configuration) { if config.Reporting.Bugsnag.APIKey == "" { return } bugsnagConfig := bugsnag.Configuration{ APIKey: config.Reporting.Bugsnag.APIKey, } if config.Reporting.Bugsnag.ReleaseStage != "" { bugsnagConfig.ReleaseStage = config.Reporting.Bugsnag.ReleaseStage } if config.Reporting.Bugsnag.Endpoint != "" { bugsnagConfig.Endpoint = config.Reporting.Bugsnag.Endpoint } bugsnag.Configure(bugsnagConfig) // configure logrus bugsnag hook hook, err := logrus_bugsnag.NewBugsnagHook() if err != nil { log.Fatalln(err) } log.AddHook(hook) } // panicHandler add an HTTP handler to web app. The handler recover the happening // panic. logrus.Panic transmits panic message to pre-config log hooks, which is // defined in config.yml. func panicHandler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { log.Panic(fmt.Sprintf("%v", err)) } }() handler.ServeHTTP(w, r) }) } // alive simply wraps the handler with a route that always returns an http 200 // response when the path is matched. If the path is not matched, the request // is passed to the provided handler. There is no guarantee of anything but // that the server is up. Wrap with other handlers (such as health.Handler) // for greater affect. func alive(path string, handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == path { w.Header().Set("Cache-Control", "no-cache") w.WriteHeader(http.StatusOK) return } handler.ServeHTTP(w, r) }) } func resolveConfiguration(args []string) (*configuration.Configuration, error) { var configurationPath string if len(args) > 0 { configurationPath = args[0] } else if os.Getenv("REGISTRY_CONFIGURATION_PATH") != "" { configurationPath = os.Getenv("REGISTRY_CONFIGURATION_PATH") } if configurationPath == "" { return nil, fmt.Errorf("configuration path unspecified") } fp, err := os.Open(configurationPath) if err != nil { return nil, err } defer fp.Close() config, err := configuration.Parse(fp) if err != nil { return nil, fmt.Errorf("error parsing %s: %v", configurationPath, err) } return config, nil } func nextProtos(config *configuration.Configuration) []string { switch config.HTTP.HTTP2.Disabled { case true: return []string{"http/1.1"} default: return []string{"h2", "http/1.1"} } }
[ "\"REGISTRY_CONFIGURATION_PATH\"", "\"REGISTRY_CONFIGURATION_PATH\"" ]
[]
[ "REGISTRY_CONFIGURATION_PATH" ]
[]
["REGISTRY_CONFIGURATION_PATH"]
go
1
0
contrib/devtools/security-check.py
#!/usr/bin/python2 ''' Perform basic ELF security checks on a series of executables. Exit status will be 0 if successful, and the program will be silent. Otherwise the exit status will be 1 and it will log which executables failed which checks. Needs `readelf` (for ELF) and `objdump` (for PE). ''' from __future__ import division,print_function import subprocess import sys import os READELF_CMD = os.getenv('READELF', '/usr/bin/readelf') OBJDUMP_CMD = os.getenv('OBJDUMP', '/usr/bin/objdump') def check_ELF_PIE(executable): ''' Check for position independent executable (PIE), allowing for address space randomization. ''' p = subprocess.Popen([READELF_CMD, '-h', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') ok = False for line in stdout.split('\n'): line = line.split() if len(line)>=2 and line[0] == 'Type:' and line[1] == 'DYN': ok = True return ok def get_ELF_program_headers(executable): '''Return type and flags for ELF program headers''' p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') in_headers = False count = 0 headers = [] for line in stdout.split('\n'): if line.startswith('Program Headers:'): in_headers = True if line == '': in_headers = False if in_headers: if count == 1: # header line ofs_typ = line.find('Type') ofs_offset = line.find('Offset') ofs_flags = line.find('Flg') ofs_align = line.find('Align') if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1: raise ValueError('Cannot parse elfread -lW output') elif count > 1: typ = line[ofs_typ:ofs_offset].rstrip() flags = line[ofs_flags:ofs_align].rstrip() headers.append((typ, flags)) count += 1 return headers def check_ELF_NX(executable): ''' Check that no sections are writable and executable (including the stack) ''' have_wx = False have_gnu_stack = False for (typ, flags) in get_ELF_program_headers(executable): if typ == 'GNU_STACK': have_gnu_stack = True if 'W' in flags and 'E' in flags: # section is both writable and executable have_wx = True return have_gnu_stack and not have_wx def check_ELF_RELRO(executable): ''' Check for read-only relocations. GNU_RELRO program header must exist Dynamic section must have BIND_NOW flag ''' have_gnu_relro = False for (typ, flags) in get_ELF_program_headers(executable): # Note: not checking flags == 'R': here as linkers set the permission differently # This does not affect security: the permission flags of the GNU_RELRO program header are ignored, the PT_LOAD header determines the effective permissions. # However, the dynamic linker need to write to this area so these are RW. # Glibc itself takes care of mprotecting this area R after relocations are finished. # See also http://permalink.gmane.org/gmane.comp.gnu.binutils/71347 if typ == 'GNU_RELRO': have_gnu_relro = True have_bindnow = False p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') for line in stdout.split('\n'): tokens = line.split() if len(tokens)>1 and tokens[1] == '(BIND_NOW)' or (len(tokens)>2 and tokens[1] == '(FLAGS)' and 'BIND_NOW' in tokens[2]): have_bindnow = True return have_gnu_relro and have_bindnow def check_ELF_Canary(executable): ''' Check for use of stack canary ''' p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') ok = False for line in stdout.split('\n'): if '__stack_chk_fail' in line: ok = True return ok def get_PE_dll_characteristics(executable): ''' Get PE DllCharacteristics bits ''' p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') for line in stdout.split('\n'): tokens = line.split() if len(tokens)>=2 and tokens[0] == 'DllCharacteristics': return int(tokens[1],16) return 0 def check_PE_PIE(executable): '''PIE: DllCharacteristics bit 0x40 signifies dynamicbase (ASLR)''' return bool(get_PE_dll_characteristics(executable) & 0x40) def check_PE_NX(executable): '''NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)''' return bool(get_PE_dll_characteristics(executable) & 0x100) CHECKS = { 'ELF': [ ('PIE', check_ELF_PIE), ('NX', check_ELF_NX), ('RELRO', check_ELF_RELRO), ('Canary', check_ELF_Canary) ], 'PE': [ ('PIE', check_PE_PIE), ('NX', check_PE_NX) ] } def identify_executable(executable): with open(filename, 'rb') as f: magic = f.read(4) if magic.startswith(b'MZ'): return 'PE' elif magic.startswith(b'\x7fELF'): return 'ELF' return None if __name__ == '__main__': retval = 0 for filename in sys.argv[1:]: try: etype = identify_executable(filename) if etype is None: print('%s: unknown format' % filename) retval = 1 continue failed = [] for (name, func) in CHECKS[etype]: if not func(filename): failed.append(name) if failed: print('%s: failed %s' % (filename, ' '.join(failed))) retval = 1 except IOError: print('%s: cannot open' % filename) retval = 1 exit(retval)
[]
[]
[ "OBJDUMP", "READELF" ]
[]
["OBJDUMP", "READELF"]
python
2
0
bccsp/pkcs11/impl_test.go
/* Copyright IBM Corp. 2016 All Rights Reserved. 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 pkcs11 import ( "bytes" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/sha512" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "fmt" "hash" "math/big" "net" "os" "strings" "testing" "time" "github.com/hyperledger/fabric/bccsp" "github.com/hyperledger/fabric/bccsp/signer" "github.com/hyperledger/fabric/bccsp/sw" "github.com/hyperledger/fabric/bccsp/utils" "github.com/op/go-logging" "github.com/stretchr/testify/assert" "golang.org/x/crypto/sha3" ) var ( currentKS bccsp.KeyStore currentBCCSP bccsp.BCCSP currentTestConfig testConfig ) type testConfig struct { securityLevel int hashFamily string softVerify bool noKeyImport bool } func TestMain(m *testing.M) { // Activate DEBUG level to cover listAttrs function logging.SetLevel(logging.DEBUG, "bccsp_p11") ks, err := sw.NewFileBasedKeyStore(nil, os.TempDir(), false) if err != nil { fmt.Printf("Failed initiliazing KeyStore [%s]", err) os.Exit(-1) } currentKS = ks lib, pin, label := FindPKCS11Lib() tests := []testConfig{ {256, "SHA2", true, true}, {256, "SHA3", false, true}, {384, "SHA2", false, true}, {384, "SHA3", false, true}, {384, "SHA3", true, true}, } if strings.Contains(lib, "softhsm") { tests = append(tests, []testConfig{ {256, "SHA2", true, false}, }...) } opts := PKCS11Opts{ Library: lib, Label: label, Pin: pin, } for _, config := range tests { var err error currentTestConfig = config opts.HashFamily = config.hashFamily opts.SecLevel = config.securityLevel opts.SoftVerify = config.softVerify opts.Sensitive = config.noKeyImport currentBCCSP, err = New(opts, currentKS) if err != nil { fmt.Printf("Failed initiliazing BCCSP at [%+v]: [%s]", opts, err) os.Exit(-1) } ret := m.Run() if ret != 0 { fmt.Printf("Failed testing at [%+v]", opts) os.Exit(-1) } } os.Exit(0) } func TestNew(t *testing.T) { opts := PKCS11Opts{ HashFamily: "SHA2", SecLevel: 256, SoftVerify: false, Sensitive: true, Library: "lib", Label: "ForFabric", Pin: "98765432", } // Setup PKCS11 library and provide initial set of values lib, _, _ := FindPKCS11Lib() opts.Library = lib // Test for nil keystore _, err := New(opts, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid bccsp.KeyStore instance. It must be different from nil.") // Test for invalid PKCS11 loadLib opts.Library = "" _, err = New(opts, currentKS) assert.Error(t, err) assert.Contains(t, err.Error(), "Failed initializing PKCS11 library") } func TestFindPKCS11LibEnvVars(t *testing.T) { const ( dummy_PKCS11_LIB = "/usr/lib/pkcs11" dummy_PKCS11_PIN = "98765432" dummy_PKCS11_LABEL = "testing" ) // Set environment variables used for test and preserve // original values for restoration after test completion orig_PKCS11_LIB := os.Getenv("PKCS11_LIB") os.Setenv("PKCS11_LIB", dummy_PKCS11_LIB) orig_PKCS11_PIN := os.Getenv("PKCS11_PIN") os.Setenv("PKCS11_PIN", dummy_PKCS11_PIN) orig_PKCS11_LABEL := os.Getenv("PKCS11_LABEL") os.Setenv("PKCS11_LABEL", dummy_PKCS11_LABEL) lib, pin, label := FindPKCS11Lib() assert.EqualValues(t, dummy_PKCS11_LIB, lib, "FindPKCS11Lib did not return expected library") assert.EqualValues(t, dummy_PKCS11_PIN, pin, "FindPKCS11Lib did not return expected pin") assert.EqualValues(t, dummy_PKCS11_LABEL, label, "FindPKCS11Lib did not return expected label") os.Setenv("PKCS11_LIB", orig_PKCS11_LIB) os.Setenv("PKCS11_PIN", orig_PKCS11_PIN) os.Setenv("PKCS11_LABEL", orig_PKCS11_LABEL) } func TestInvalidNewParameter(t *testing.T) { lib, pin, label := FindPKCS11Lib() opts := PKCS11Opts{ Library: lib, Label: label, Pin: pin, SoftVerify: true, Sensitive: true, } opts.HashFamily = "SHA2" opts.SecLevel = 0 r, err := New(opts, currentKS) if err == nil { t.Fatal("Error should be different from nil in this case") } if r != nil { t.Fatal("Return value should be equal to nil in this case") } opts.HashFamily = "SHA8" opts.SecLevel = 256 r, err = New(opts, currentKS) if err == nil { t.Fatal("Error should be different from nil in this case") } if r != nil { t.Fatal("Return value should be equal to nil in this case") } opts.HashFamily = "SHA2" opts.SecLevel = 256 r, err = New(opts, nil) if err == nil { t.Fatal("Error should be different from nil in this case") } if r != nil { t.Fatal("Return value should be equal to nil in this case") } opts.HashFamily = "SHA3" opts.SecLevel = 0 r, err = New(opts, nil) if err == nil { t.Fatal("Error should be different from nil in this case") } if r != nil { t.Fatal("Return value should be equal to nil in this case") } } func TestInvalidSKI(t *testing.T) { k, err := currentBCCSP.GetKey(nil) if err == nil { t.Fatal("Error should be different from nil in this case") } if k != nil { t.Fatal("Return value should be equal to nil in this case") } k, err = currentBCCSP.GetKey([]byte{0, 1, 2, 3, 4, 5, 6}) if err == nil { t.Fatal("Error should be different from nil in this case") } if k != nil { t.Fatal("Return value should be equal to nil in this case") } } func TestKeyGenECDSAOpts(t *testing.T) { // Curve P256 k, err := currentBCCSP.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA P256 key [%s]", err) } if k == nil { t.Fatal("Failed generating ECDSA P256 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating ECDSA P256 key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating ECDSA P256 key. Key should be asymmetric") } ecdsaKey := k.(*ecdsaPrivateKey).pub if elliptic.P256() != ecdsaKey.pub.Curve { t.Fatal("P256 generated key in invalid. The curve must be P256.") } // Curve P384 k, err = currentBCCSP.KeyGen(&bccsp.ECDSAP384KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA P384 key [%s]", err) } if k == nil { t.Fatal("Failed generating ECDSA P384 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating ECDSA P384 key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating ECDSA P384 key. Key should be asymmetric") } ecdsaKey = k.(*ecdsaPrivateKey).pub if elliptic.P384() != ecdsaKey.pub.Curve { t.Fatal("P256 generated key in invalid. The curve must be P384.") } } func TestKeyGenRSAOpts(t *testing.T) { // 1024 k, err := currentBCCSP.KeyGen(&bccsp.RSA1024KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA 1024 key [%s]", err) } if k == nil { t.Fatal("Failed generating RSA 1024 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating RSA 1024 key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating RSA 1024 key. Key should be asymmetric") } // 2048 k, err = currentBCCSP.KeyGen(&bccsp.RSA2048KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA 2048 key [%s]", err) } if k == nil { t.Fatal("Failed generating RSA 2048 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating RSA 2048 key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating RSA 2048 key. Key should be asymmetric") } } func TestKeyGenAESOpts(t *testing.T) { // AES 128 k, err := currentBCCSP.KeyGen(&bccsp.AES128KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES 128 key [%s]", err) } if k == nil { t.Fatal("Failed generating AES 128 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating AES 128 key. Key should be private") } if !k.Symmetric() { t.Fatal("Failed generating AES 128 key. Key should be symmetric") } // AES 192 k, err = currentBCCSP.KeyGen(&bccsp.AES192KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES 192 key [%s]", err) } if k == nil { t.Fatal("Failed generating AES 192 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating AES 192 key. Key should be private") } if !k.Symmetric() { t.Fatal("Failed generating AES 192 key. Key should be symmetric") } // AES 256 k, err = currentBCCSP.KeyGen(&bccsp.AES256KeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES 256 key [%s]", err) } if k == nil { t.Fatal("Failed generating AES 256 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating AES 256 key. Key should be private") } if !k.Symmetric() { t.Fatal("Failed generating AES 256 key. Key should be symmetric") } } func TestHashOpts(t *testing.T) { msg := []byte("abcd") // SHA256 digest1, err := currentBCCSP.Hash(msg, &bccsp.SHA256Opts{}) if err != nil { t.Fatalf("Failed computing SHA256 [%s]", err) } h := sha256.New() h.Write(msg) digest2 := h.Sum(nil) if !bytes.Equal(digest1, digest2) { t.Fatalf("Different SHA256 computed. [%x][%x]", digest1, digest2) } // SHA384 digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA384Opts{}) if err != nil { t.Fatalf("Failed computing SHA384 [%s]", err) } h = sha512.New384() h.Write(msg) digest2 = h.Sum(nil) if !bytes.Equal(digest1, digest2) { t.Fatalf("Different SHA384 computed. [%x][%x]", digest1, digest2) } // SHA3_256O digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_256Opts{}) if err != nil { t.Fatalf("Failed computing SHA3_256 [%s]", err) } h = sha3.New256() h.Write(msg) digest2 = h.Sum(nil) if !bytes.Equal(digest1, digest2) { t.Fatalf("Different SHA3_256 computed. [%x][%x]", digest1, digest2) } // SHA3_384 digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_384Opts{}) if err != nil { t.Fatalf("Failed computing SHA3_384 [%s]", err) } h = sha3.New384() h.Write(msg) digest2 = h.Sum(nil) if !bytes.Equal(digest1, digest2) { t.Fatalf("Different SHA3_384 computed. [%x][%x]", digest1, digest2) } } func TestECDSAKeyGenEphemeral(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: true}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } if k == nil { t.Fatal("Failed generating ECDSA key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating ECDSA key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating ECDSA key. Key should be asymmetric") } raw, err := k.Bytes() if err == nil { t.Fatal("Failed marshalling to bytes. Marshalling must fail.") } if len(raw) != 0 { t.Fatal("Failed marshalling to bytes. Output should be 0 bytes") } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting corresponding public key [%s]", err) } if pk == nil { t.Fatal("Public key must be different from nil.") } } func TestECDSAPrivateKeySKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } ski := k.SKI() if len(ski) == 0 { t.Fatal("SKI not valid. Zero length.") } } func TestECDSAKeyGenNonEphemeral(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } if k == nil { t.Fatal("Failed generating ECDSA key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating ECDSA key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating ECDSA key. Key should be asymmetric") } } func TestECDSAGetKeyBySKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } k2, err := currentBCCSP.GetKey(k.SKI()) if err != nil { t.Fatalf("Failed getting ECDSA key [%s]", err) } if k2 == nil { t.Fatal("Failed getting ECDSA key. Key must be different from nil") } if !k2.Private() { t.Fatal("Failed getting ECDSA key. Key should be private") } if k2.Symmetric() { t.Fatal("Failed getting ECDSA key. Key should be asymmetric") } // Check that the SKIs are the same if !bytes.Equal(k.SKI(), k2.SKI()) { t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI()) } } func TestECDSAPublicKeyFromPrivateKey(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public key from private ECDSA key [%s]", err) } if pk == nil { t.Fatal("Failed getting public key from private ECDSA key. Key must be different from nil") } if pk.Private() { t.Fatal("Failed generating ECDSA key. Key should be public") } if pk.Symmetric() { t.Fatal("Failed generating ECDSA key. Key should be asymmetric") } } func TestECDSAPublicKeyBytes(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public key from private ECDSA key [%s]", err) } raw, err := pk.Bytes() if err != nil { t.Fatalf("Failed marshalling ECDSA public key [%s]", err) } if len(raw) == 0 { t.Fatal("Failed marshalling ECDSA public key. Zero length") } } func TestECDSAPublicKeySKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public key from private ECDSA key [%s]", err) } ski := pk.SKI() if len(ski) == 0 { t.Fatal("SKI not valid. Zero length.") } } func TestECDSAKeyReRand(t *testing.T) { if currentBCCSP.(*impl).noPrivImport { t.Skip("Key import turned off. Skipping Derivation tests as they currently require Key Import.") } k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } if k == nil { t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key must be different from nil") } reRandomizedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}}) if err != nil { t.Fatalf("Failed re-randomizing ECDSA key [%s]", err) } if !reRandomizedKey.Private() { t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key should be private") } if reRandomizedKey.Symmetric() { t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key should be asymmetric") } k2, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public ECDSA key from private [%s]", err) } if k2 == nil { t.Fatal("Failed re-randomizing ECDSA key. Re-randomized Key must be different from nil") } reRandomizedKey2, err := currentBCCSP.KeyDeriv(k2, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}}) if err != nil { t.Fatalf("Failed re-randomizing ECDSA key [%s]", err) } if reRandomizedKey2.Private() { t.Fatal("Re-randomized public Key must remain public") } if reRandomizedKey2.Symmetric() { t.Fatal("Re-randomized ECDSA asymmetric key must remain asymmetric") } if false == bytes.Equal(reRandomizedKey.SKI(), reRandomizedKey2.SKI()) { t.Fatal("Re-randomized ECDSA Private- or Public-Keys must end up having the same SKI") } } func TestECDSASign(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } if len(signature) == 0 { t.Fatal("Failed generating ECDSA key. Signature must be different from nil") } _, err = currentBCCSP.Sign(nil, digest, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid Key. It must not be nil.") _, err = currentBCCSP.Sign(k, nil, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid digest. Cannot be empty.") } func TestECDSAVerify(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } valid, err := currentBCCSP.Verify(k, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting corresponding public key [%s]", err) } valid, err = currentBCCSP.Verify(pk, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } _, err = currentBCCSP.Verify(nil, signature, digest, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid Key. It must not be nil.") _, err = currentBCCSP.Verify(pk, nil, digest, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid signature. Cannot be empty.") _, err = currentBCCSP.Verify(pk, signature, nil, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid digest. Cannot be empty.") // Import the exported public key pkRaw, err := pk.Bytes() if err != nil { t.Fatalf("Failed getting ECDSA raw public key [%s]", err) } // Store public key _, err = currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed storing corresponding public key [%s]", err) } pk2, err := currentBCCSP.GetKey(pk.SKI()) if err != nil { t.Fatalf("Failed retrieving corresponding public key [%s]", err) } valid, err = currentBCCSP.Verify(pk2, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } } func TestECDSAKeyDeriv(t *testing.T) { if currentBCCSP.(*impl).noPrivImport { t.Skip("Key import turned off. Skipping Derivation tests as they currently require Key Import.") } k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } reRandomizedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}}) if err != nil { t.Fatalf("Failed re-randomizing ECDSA key [%s]", err) } _, err = currentBCCSP.KeyDeriv(nil, &bccsp.ECDSAReRandKeyOpts{Temporary: false, Expansion: []byte{1}}) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid Key. It must not be nil.") _, err = currentBCCSP.KeyDeriv(k, nil) assert.Error(t, err) assert.Contains(t, err.Error(), "Invalid Opts parameter. It must not be nil.") msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(reRandomizedKey, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } valid, err := currentBCCSP.Verify(reRandomizedKey, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } } func TestECDSAKeyImportFromExportedKey(t *testing.T) { // Generate an ECDSA key k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } // Export the public key pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting ECDSA public key [%s]", err) } pkRaw, err := pk.Bytes() if err != nil { t.Fatalf("Failed getting ECDSA raw public key [%s]", err) } // Import the exported public key pk2, err := currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing ECDSA public key [%s]", err) } if pk2 == nil { t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.") } // Sign and verify with the imported public key msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } valid, err := currentBCCSP.Verify(pk2, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } } func TestECDSAKeyImportFromECDSAPublicKey(t *testing.T) { // Generate an ECDSA key k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } // Export the public key pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting ECDSA public key [%s]", err) } pkRaw, err := pk.Bytes() if err != nil { t.Fatalf("Failed getting ECDSA raw public key [%s]", err) } pub, err := utils.DERToPublicKey(pkRaw) if err != nil { t.Fatalf("Failed converting raw to ecdsa.PublicKey [%s]", err) } // Import the ecdsa.PublicKey pk2, err := currentBCCSP.KeyImport(pub, &bccsp.ECDSAGoPublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing ECDSA public key [%s]", err) } if pk2 == nil { t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.") } // Sign and verify with the imported public key msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } valid, err := currentBCCSP.Verify(pk2, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } } func TestECDSAKeyImportFromECDSAPrivateKey(t *testing.T) { if currentBCCSP.(*impl).noPrivImport { t.Skip("Key import turned off. Skipping Derivation tests as they currently require Key Import.") } // Generate an ECDSA key, default is P256 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } // Import the ecdsa.PrivateKey priv, err := utils.PrivateKeyToDER(key) if err != nil { t.Fatalf("Failed converting raw to ecdsa.PrivateKey [%s]", err) } sk, err := currentBCCSP.KeyImport(priv, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing ECDSA private key [%s]", err) } if sk == nil { t.Fatal("Failed importing ECDSA private key. Return BCCSP key cannot be nil.") } // Import the ecdsa.PublicKey pub, err := utils.PublicKeyToDER(&key.PublicKey) if err != nil { t.Fatalf("Failed converting raw to ecdsa.PublicKey [%s]", err) } pk, err := currentBCCSP.KeyImport(pub, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing ECDSA public key [%s]", err) } if pk == nil { t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.") } // Sign and verify with the imported public key msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(sk, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } valid, err := currentBCCSP.Verify(pk, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } } func TestKeyImportFromX509ECDSAPublicKey(t *testing.T) { // Generate an ECDSA key k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } // Generate a self-signed certificate testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth} testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}} extraExtensionData := []byte("extra extension") commonName := "test.example.com" template := x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: commonName, Organization: []string{"Σ Acme Co"}, Country: []string{"US"}, ExtraNames: []pkix.AttributeTypeAndValue{ { Type: []int{2, 5, 4, 42}, Value: "Gopher", }, // This should override the Country, above. { Type: []int{2, 5, 4, 6}, Value: "NL", }, }, }, NotBefore: time.Now().Add(-1 * time.Hour), NotAfter: time.Now().Add(1 * time.Hour), SignatureAlgorithm: x509.ECDSAWithSHA256, SubjectKeyId: []byte{1, 2, 3, 4}, KeyUsage: x509.KeyUsageCertSign, ExtKeyUsage: testExtKeyUsage, UnknownExtKeyUsage: testUnknownExtKeyUsage, BasicConstraintsValid: true, IsCA: true, OCSPServer: []string{"http://ocurrentBCCSP.example.com"}, IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"}, DNSNames: []string{"test.example.com"}, EmailAddresses: []string{"[email protected]"}, IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}}, PermittedDNSDomains: []string{".example.com", "example.com"}, CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"}, ExtraExtensions: []pkix.Extension{ { Id: []int{1, 2, 3, 4}, Value: extraExtensionData, }, }, } cryptoSigner, err := signer.New(currentBCCSP, k) if err != nil { t.Fatalf("Failed initializing CyrptoSigner [%s]", err) } // Export the public key pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting ECDSA public key [%s]", err) } pkRaw, err := pk.Bytes() if err != nil { t.Fatalf("Failed getting ECDSA raw public key [%s]", err) } pub, err := utils.DERToPublicKey(pkRaw) if err != nil { t.Fatalf("Failed converting raw to ECDSA.PublicKey [%s]", err) } certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner) if err != nil { t.Fatalf("Failed generating self-signed certificate [%s]", err) } cert, err := utils.DERToX509Certificate(certRaw) if err != nil { t.Fatalf("Failed generating X509 certificate object from raw [%s]", err) } // Import the certificate's public key pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing ECDSA public key [%s]", err) } if pk2 == nil { t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.") } // Sign and verify with the imported public key msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } valid, err := currentBCCSP.Verify(pk2, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } } func TestECDSASignatureEncoding(t *testing.T) { v := []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0xff, 0xf1} _, err := asn1.Unmarshal(v, &ecdsaSignature{}) if err == nil { t.Fatalf("Unmarshalling should fail for [% x]", v) } t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err) v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0x00, 0x01} _, err = asn1.Unmarshal(v, &ecdsaSignature{}) if err == nil { t.Fatalf("Unmarshalling should fail for [% x]", v) } t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err) v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x01} _, err = asn1.Unmarshal(v, &ecdsaSignature{}) if err == nil { t.Fatalf("Unmarshalling should fail for [% x]", v) } t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err) v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x8F} _, err = asn1.Unmarshal(v, &ecdsaSignature{}) if err == nil { t.Fatalf("Unmarshalling should fail for [% x]", v) } t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err) v = []byte{0x30, 0x0A, 0x02, 0x01, 0x8F, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00, 0x8F} _, err = asn1.Unmarshal(v, &ecdsaSignature{}) if err == nil { t.Fatalf("Unmarshalling should fail for [% x]", v) } t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err) } func TestECDSALowS(t *testing.T) { // Ensure that signature with low-S are generated k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating ECDSA key [%s]", err) } msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, nil) if err != nil { t.Fatalf("Failed generating ECDSA signature [%s]", err) } R, S, err := unmarshalECDSASignature(signature) if err != nil { t.Fatalf("Failed unmarshalling signature [%s]", err) } if S.Cmp(curveHalfOrders[k.(*ecdsaPrivateKey).pub.pub.Curve]) >= 0 { t.Fatal("Invalid signature. It must have low-S") } valid, err := currentBCCSP.Verify(k, signature, digest, nil) if err != nil { t.Fatalf("Failed verifying ECDSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying ECDSA signature. Signature not valid.") } // Ensure that signature with high-S are rejected. for { R, S, err = currentBCCSP.(*impl).signP11ECDSA(k.SKI(), digest) if err != nil { t.Fatalf("Failed generating signature [%s]", err) } if S.Cmp(curveHalfOrders[k.(*ecdsaPrivateKey).pub.pub.Curve]) > 0 { break } } sig, err := marshalECDSASignature(R, S) if err != nil { t.Fatalf("Failing unmarshalling signature [%s]", err) } valid, err = currentBCCSP.Verify(k, sig, digest, nil) if err == nil { t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S") } if valid { t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S") } } func TestAESKeyGen(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES_256 key [%s]", err) } if k == nil { t.Fatal("Failed generating AES_256 key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating AES_256 key. Key should be private") } if !k.Symmetric() { t.Fatal("Failed generating AES_256 key. Key should be symmetric") } pk, err := k.PublicKey() if err == nil { t.Fatal("Error should be different from nil in this case") } if pk != nil { t.Fatal("Return value should be equal to nil in this case") } } func TestAESEncrypt(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES_256 key [%s]", err) } ct, err := currentBCCSP.Encrypt(k, []byte("Hello World"), &bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed encrypting [%s]", err) } if len(ct) == 0 { t.Fatal("Failed encrypting. Nil ciphertext") } } func TestAESDecrypt(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES_256 key [%s]", err) } msg := []byte("Hello World") ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed encrypting [%s]", err) } pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed decrypting [%s]", err) } if len(ct) == 0 { t.Fatal("Failed decrypting. Nil plaintext") } if !bytes.Equal(msg, pt) { t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt) } } func TestHMACTruncated256KeyDerivOverAES256Key(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES_256 key [%s]", err) } hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACTruncated256AESDeriveKeyOpts{Temporary: false, Arg: []byte{1}}) if err != nil { t.Fatalf("Failed HMACing AES_256 key [%s]", err) } if k == nil { t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil") } if !hmcaedKey.Private() { t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private") } if !hmcaedKey.Symmetric() { t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric") } raw, err := hmcaedKey.Bytes() if err == nil { t.Fatal("Failed marshalling to bytes. Operation must be forbidden") } if len(raw) != 0 { t.Fatal("Failed marshalling to bytes. Operation must return 0 bytes") } msg := []byte("Hello World") ct, err := currentBCCSP.Encrypt(hmcaedKey, msg, &bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed encrypting [%s]", err) } pt, err := currentBCCSP.Decrypt(hmcaedKey, ct, bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed decrypting [%s]", err) } if len(ct) == 0 { t.Fatal("Failed decrypting. Nil plaintext") } if !bytes.Equal(msg, pt) { t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt) } } func TestHMACKeyDerivOverAES256Key(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES_256 key [%s]", err) } hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Temporary: false, Arg: []byte{1}}) if err != nil { t.Fatalf("Failed HMACing AES_256 key [%s]", err) } if k == nil { t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil") } if !hmcaedKey.Private() { t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private") } if !hmcaedKey.Symmetric() { t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric") } raw, err := hmcaedKey.Bytes() if err != nil { t.Fatalf("Failed marshalling to bytes [%s]", err) } if len(raw) == 0 { t.Fatal("Failed marshalling to bytes. 0 bytes") } } func TestAES256KeyImport(t *testing.T) { raw, err := sw.GetRandomBytes(32) if err != nil { t.Fatalf("Failed generating AES key [%s]", err) } k, err := currentBCCSP.KeyImport(raw, &bccsp.AES256ImportKeyOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing AES_256 key [%s]", err) } if k == nil { t.Fatal("Failed importing AES_256 key. Imported Key must be different from nil") } if !k.Private() { t.Fatal("Failed HMACing AES_256 key. Imported Key should be private") } if !k.Symmetric() { t.Fatal("Failed HMACing AES_256 key. Imported Key should be asymmetric") } raw, err = k.Bytes() if err == nil { t.Fatal("Failed marshalling to bytes. Marshalling must fail.") } if len(raw) != 0 { t.Fatal("Failed marshalling to bytes. Output should be 0 bytes") } msg := []byte("Hello World") ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed encrypting [%s]", err) } pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{}) if err != nil { t.Fatalf("Failed decrypting [%s]", err) } if len(ct) == 0 { t.Fatal("Failed decrypting. Nil plaintext") } if !bytes.Equal(msg, pt) { t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt) } } func TestAES256KeyImportBadPaths(t *testing.T) { _, err := currentBCCSP.KeyImport(nil, &bccsp.AES256ImportKeyOpts{Temporary: false}) if err == nil { t.Fatal("Failed importing key. Must fail on importing nil key") } _, err = currentBCCSP.KeyImport([]byte{1}, &bccsp.AES256ImportKeyOpts{Temporary: false}) if err == nil { t.Fatal("Failed importing key. Must fail on importing a key with an invalid length") } } func TestAES256KeyGenSKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating AES_256 key [%s]", err) } k2, err := currentBCCSP.GetKey(k.SKI()) if err != nil { t.Fatalf("Failed getting AES_256 key [%s]", err) } if k2 == nil { t.Fatal("Failed getting AES_256 key. Key must be different from nil") } if !k2.Private() { t.Fatal("Failed getting AES_256 key. Key should be private") } if !k2.Symmetric() { t.Fatal("Failed getting AES_256 key. Key should be symmetric") } // Check that the SKIs are the same if !bytes.Equal(k.SKI(), k2.SKI()) { t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI()) } } func TestSHA(t *testing.T) { for i := 0; i < 100; i++ { b, err := sw.GetRandomBytes(i) if err != nil { t.Fatalf("Failed getting random bytes [%s]", err) } h1, err := currentBCCSP.Hash(b, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing SHA [%s]", err) } var h hash.Hash switch currentTestConfig.hashFamily { case "SHA2": switch currentTestConfig.securityLevel { case 256: h = sha256.New() case 384: h = sha512.New384() default: t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel) } case "SHA3": switch currentTestConfig.securityLevel { case 256: h = sha3.New256() case 384: h = sha3.New384() default: t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel) } default: t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily) } h.Write(b) h2 := h.Sum(nil) if !bytes.Equal(h1, h2) { t.Fatalf("Discrempancy found in HASH result [%x], [%x]!=[%x]", b, h1, h2) } } } func TestRSAKeyGenEphemeral(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: true}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } if k == nil { t.Fatal("Failed generating RSA key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating RSA key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating RSA key. Key should be asymmetric") } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed generating RSA corresponding public key [%s]", err) } if pk == nil { t.Fatal("PK must be different from nil") } b, err := k.Bytes() if err == nil { t.Fatal("Secret keys cannot be exported. It must fail in this case") } if len(b) != 0 { t.Fatal("Secret keys cannot be exported. It must be nil") } } func TestRSAPrivateKeySKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } ski := k.SKI() if len(ski) == 0 { t.Fatal("SKI not valid. Zero length.") } } func TestRSAKeyGenNonEphemeral(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } if k == nil { t.Fatal("Failed generating RSA key. Key must be different from nil") } if !k.Private() { t.Fatal("Failed generating RSA key. Key should be private") } if k.Symmetric() { t.Fatal("Failed generating RSA key. Key should be asymmetric") } } func TestRSAGetKeyBySKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } k2, err := currentBCCSP.GetKey(k.SKI()) if err != nil { t.Fatalf("Failed getting RSA key [%s]", err) } if k2 == nil { t.Fatal("Failed getting RSA key. Key must be different from nil") } if !k2.Private() { t.Fatal("Failed getting RSA key. Key should be private") } if k2.Symmetric() { t.Fatal("Failed getting RSA key. Key should be asymmetric") } // Check that the SKIs are the same if !bytes.Equal(k.SKI(), k2.SKI()) { t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI()) } } func TestRSAPublicKeyFromPrivateKey(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public key from private RSA key [%s]", err) } if pk == nil { t.Fatal("Failed getting public key from private RSA key. Key must be different from nil") } if pk.Private() { t.Fatal("Failed generating RSA key. Key should be public") } if pk.Symmetric() { t.Fatal("Failed generating RSA key. Key should be asymmetric") } } func TestRSAPublicKeyBytes(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public key from private RSA key [%s]", err) } raw, err := pk.Bytes() if err != nil { t.Fatalf("Failed marshalling RSA public key [%s]", err) } if len(raw) == 0 { t.Fatal("Failed marshalling RSA public key. Zero length") } } func TestRSAPublicKeySKI(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting public key from private RSA key [%s]", err) } ski := pk.SKI() if len(ski) == 0 { t.Fatal("SKI not valid. Zero length.") } } func TestRSASign(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed generating RSA signature [%s]", err) } if len(signature) == 0 { t.Fatal("Failed generating RSA key. Signature must be different from nil") } } func TestRSAVerify(t *testing.T) { k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed generating RSA signature [%s]", err) } valid, err := currentBCCSP.Verify(k, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed verifying RSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying RSA signature. Signature not valid.") } pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting corresponding public key [%s]", err) } valid, err = currentBCCSP.Verify(pk, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed verifying RSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying RSA signature. Signature not valid.") } // Store public key err = currentKS.StoreKey(pk) if err != nil { t.Fatalf("Failed storing corresponding public key [%s]", err) } pk2, err := currentKS.GetKey(pk.SKI()) if err != nil { t.Fatalf("Failed retrieving corresponding public key [%s]", err) } valid, err = currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed verifying RSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying RSA signature. Signature not valid.") } } func TestRSAKeyImportFromRSAPublicKey(t *testing.T) { // Generate an RSA key k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } // Export the public key pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting RSA public key [%s]", err) } pkRaw, err := pk.Bytes() if err != nil { t.Fatalf("Failed getting RSA raw public key [%s]", err) } pub, err := utils.DERToPublicKey(pkRaw) if err != nil { t.Fatalf("Failed converting raw to RSA.PublicKey [%s]", err) } // Import the RSA.PublicKey pk2, err := currentBCCSP.KeyImport(pub, &bccsp.RSAGoPublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing RSA public key [%s]", err) } if pk2 == nil { t.Fatal("Failed importing RSA public key. Return BCCSP key cannot be nil.") } // Sign and verify with the imported public key msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed generating RSA signature [%s]", err) } valid, err := currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed verifying RSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying RSA signature. Signature not valid.") } } func TestKeyImportFromX509RSAPublicKey(t *testing.T) { // Generate an RSA key k, err := currentBCCSP.KeyGen(&bccsp.RSAKeyGenOpts{Temporary: false}) if err != nil { t.Fatalf("Failed generating RSA key [%s]", err) } // Generate a self-signed certificate testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth} testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}} extraExtensionData := []byte("extra extension") commonName := "test.example.com" template := x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: commonName, Organization: []string{"Σ Acme Co"}, Country: []string{"US"}, ExtraNames: []pkix.AttributeTypeAndValue{ { Type: []int{2, 5, 4, 42}, Value: "Gopher", }, // This should override the Country, above. { Type: []int{2, 5, 4, 6}, Value: "NL", }, }, }, NotBefore: time.Now().Add(-1 * time.Hour), NotAfter: time.Now().Add(1 * time.Hour), SignatureAlgorithm: x509.SHA256WithRSA, SubjectKeyId: []byte{1, 2, 3, 4}, KeyUsage: x509.KeyUsageCertSign, ExtKeyUsage: testExtKeyUsage, UnknownExtKeyUsage: testUnknownExtKeyUsage, BasicConstraintsValid: true, IsCA: true, OCSPServer: []string{"http://ocurrentBCCSP.example.com"}, IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"}, DNSNames: []string{"test.example.com"}, EmailAddresses: []string{"[email protected]"}, IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}}, PermittedDNSDomains: []string{".example.com", "example.com"}, CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"}, ExtraExtensions: []pkix.Extension{ { Id: []int{1, 2, 3, 4}, Value: extraExtensionData, }, }, } cryptoSigner, err := signer.New(currentBCCSP, k) if err != nil { t.Fatalf("Failed initializing CyrptoSigner [%s]", err) } // Export the public key pk, err := k.PublicKey() if err != nil { t.Fatalf("Failed getting RSA public key [%s]", err) } pkRaw, err := pk.Bytes() if err != nil { t.Fatalf("Failed getting RSA raw public key [%s]", err) } pub, err := utils.DERToPublicKey(pkRaw) if err != nil { t.Fatalf("Failed converting raw to RSA.PublicKey [%s]", err) } certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner) if err != nil { t.Fatalf("Failed generating self-signed certificate [%s]", err) } cert, err := utils.DERToX509Certificate(certRaw) if err != nil { t.Fatalf("Failed generating X509 certificate object from raw [%s]", err) } // Import the certificate's public key pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false}) if err != nil { t.Fatalf("Failed importing RSA public key [%s]", err) } if pk2 == nil { t.Fatal("Failed importing RSA public key. Return BCCSP key cannot be nil.") } // Sign and verify with the imported public key msg := []byte("Hello World") digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{}) if err != nil { t.Fatalf("Failed computing HASH [%s]", err) } signature, err := currentBCCSP.Sign(k, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed generating RSA signature [%s]", err) } valid, err := currentBCCSP.Verify(pk2, signature, digest, &rsa.PSSOptions{SaltLength: 32, Hash: getCryptoHashIndex(t)}) if err != nil { t.Fatalf("Failed verifying RSA signature [%s]", err) } if !valid { t.Fatal("Failed verifying RSA signature. Signature not valid.") } } func getCryptoHashIndex(t *testing.T) crypto.Hash { switch currentTestConfig.hashFamily { case "SHA2": switch currentTestConfig.securityLevel { case 256: return crypto.SHA256 case 384: return crypto.SHA384 default: t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel) } case "SHA3": switch currentTestConfig.securityLevel { case 256: return crypto.SHA3_256 case 384: return crypto.SHA3_384 default: t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel) } default: t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily) } return crypto.SHA3_256 }
[ "\"PKCS11_LIB\"", "\"PKCS11_PIN\"", "\"PKCS11_LABEL\"" ]
[]
[ "PKCS11_PIN", "PKCS11_LIB", "PKCS11_LABEL" ]
[]
["PKCS11_PIN", "PKCS11_LIB", "PKCS11_LABEL"]
go
3
0
statistik_api.py
""" Work in progress: - Does a database dump of all cases / persons in database - When restarted, only updates cases / persons that have been changed since last use - Potentially useful for automated statistics """ import sormasapi import config import time import os import json from pprint import pprint def initialize_json(filename, save_interval = 100): print("Getting all data... might take a while") casedict = {} uuids = sormasapi.get_all_case_uuids() print(str(len(uuids)) + " Fälle insgesamt") if os.path.exists(filename): with open(filename) as jsonfile: casedict = json.load(jsonfile) print(str(len(casedict)) + " Fälle aus Datei geladen") i = 0 for uuid in uuids: if uuid not in casedict: case = sormasapi.query("cases",uuid) casedict[uuid] = case i+=1 if i == save_interval: i=0 print(str(len(casedict))), with open(filename, "w") as outfile: json.dump(casedict, outfile) def initialize_person_json(): pass def load_and_update_json(filename, override_date=""): # 1) Reads json dump # 2) Updates all cases updated since last dump # 3) Adds new cases # override_date: force update since date / datetime (dd.mm.yyyy / dd.mm.yyyy HH:SS) casedict = {} with open(filename) as jsonfile: casedict = json.load(jsonfile) changedate = max([casedict[key]["changeDate"] for key in casedict]) if override_date: changedate = sormasapi.datestring_to_int(override_date) new_cases = sormasapi.get_since("cases", dateint = changedate) for case in new_cases: casedict[case["uuid"]] = case with open(filename, "w") as outfile: json.dump(casedict, outfile) print("Done") return casedict def if __name__== "__main__": os.environ['HTTPS_PROXY'] = config.proxy start_time = time.time() filename = "all_cases.json" #initialize_json(filename) casedict = load_and_update_json(filename) print(len(casedict)) print("--- %s seconds ---" % (time.time() - start_time))
[]
[]
[ "HTTPS_PROXY" ]
[]
["HTTPS_PROXY"]
python
1
0
main.go
package main import ( "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sns" "github.com/docker/libcompose/cli/command" "github.com/kballard/go-shellquote" "github.com/mozillazg/go-unidecode" rancherApp "github.com/ouzklcn/rancher-compose/app" "github.com/ouzklcn/rancher-compose/version" "github.com/sirupsen/logrus" "github.com/urfave/cli" "os" "reflect" ) func beforeApp(c *cli.Context) error { if c.GlobalBool("verbose") { logrus.SetLevel(logrus.DebugLevel) } return nil } func afterApp(c *cli.Context) error { snsArn := c.GlobalString("callback-sns-arn") snsCallbackTemplate := c.GlobalString("callback-message") snsRegion := os.Getenv("AWS_REGION") if snsArn != "" && snsCallbackTemplate != "" && snsRegion != "" { sess, err := session.NewSession(&aws.Config{Region: aws.String(snsRegion)}) if err != nil { return err } service := sns.New(sess) params := &sns.PublishInput{ Message: aws.String(snsCallbackTemplate), TopicArn: aws.String(snsArn), } if _, err := service.Publish(params); err != nil { return err } } return nil } func main() { lambda.Start(HandleRequest) } func HandleRequest(snsEvent events.SNSEvent) { logrus.Infof("%#v", snsEvent) factory := &rancherApp.ProjectFactory{} deleter := rancherApp.ProjectDeleter{} app := cli.NewApp() app.Name = "rancher-compose" app.Usage = "Docker-compose to Rancher" app.Version = version.VERSION app.Author = "Rancher Labs, Inc." app.Email = "" app.Before = beforeApp app.After = afterApp app.Flags = []cli.Flag{ cli.BoolFlag{ Name: "verbose,debug", }, cli.StringSliceFlag{ Name: "file,f", Usage: "Specify one or more alternate compose files (default: docker-compose.yml)", Value: &cli.StringSlice{"/tmp/docker-compose.yml"}, EnvVar: "COMPOSE_FILE", Hidden: true, }, cli.StringFlag{ Name: "project-name,p", Usage: "Specify an alternate project name (default: directory name)", EnvVar: "COMPOSE_PROJECT_NAME", }, cli.StringFlag{ Name: "url", Usage: "Specify the Rancher API endpoint URL", EnvVar: "RANCHER_URL", }, cli.StringFlag{ Name: "access-key", Usage: "Specify Rancher API access key", EnvVar: "RANCHER_ACCESS_KEY", }, cli.StringFlag{ Name: "secret-key", Usage: "Specify Rancher API secret key", EnvVar: "RANCHER_SECRET_KEY", }, cli.StringFlag{ Name: "rancher-file,r", Usage: "Specify an alternate Rancher compose file (default: rancher-compose.yml)", Value: "/tmp/rancher-compose.yml", Hidden: true, }, cli.StringFlag{ Name: "env-file,e", Usage: "Specify a file from which to read environment variables", }, cli.StringFlag{ Name: "bindings-file,b", Usage: "Specify a file from which to read bindings", }, cli.StringFlag{ Name: "github-access-token", Usage: "Specify Github Access token", EnvVar: "GITHUB_ACCESS_TOKEN", }, cli.StringFlag{ Name: "github-repository-owner", Usage: "Specify Github repo owner", EnvVar: "GITHUB_REPOSITORY_OWNER", }, cli.StringFlag{ Name: "github-repository-name", Usage: "Specify Github repo name", EnvVar: "GITHUB_REPOSITORY_NAME", }, cli.StringFlag{ Name: "github-ref", Usage: "Specify Github ref", EnvVar: "GITHUB_REF", }, cli.StringFlag{ Name: "github-rancher-file", Usage: "Specify Rancher compose file location in Github repo (default: rancher-compose.yml)", EnvVar: "GITHUB_RANCHER_FILE", }, cli.StringFlag{ Name: "github-docker-file", Usage: "Specify Docker compose file location in Github repo (default: docker-compose.yml)", EnvVar: "GITHUB_DOCKER_FILE", }, cli.StringFlag{ Name: "callback-sns-arn", Usage: "AWS SNS Arn for callback message)", EnvVar: "AWS_SNS_ARN", }, cli.StringFlag{ Name: "callback-message", Usage: "Message to make a callback", EnvVar: "CALLBACK_MESSAGE", }, } app.Commands = []cli.Command{ rancherApp.CreateCommand(factory), rancherApp.UpCommand(factory), command.StartCommand(factory), command.LogsCommand(factory), rancherApp.RestartCommand(factory), rancherApp.StopCommand(factory), command.ScaleCommand(factory), command.RmCommand(factory), rancherApp.PullCommand(factory), rancherApp.UpgradeCommand(factory), rancherApp.DownCommand(factory, deleter), } message := unidecode.Unidecode(snsEvent.Records[0].SNS.Message) parsed, err := shellquote.Split(message) if err != nil { return } logrus.Infof("parsed: %s", parsed) for k, v := range snsEvent.Records[0].SNS.MessageAttributes { if IsInstanceOf(v, map[string]interface{}(nil)) { if v.(map[string]interface{})["Type"] == "String" { os.Setenv(k , v.(map[string]interface{})["Value"].(string)) } } else if IsInstanceOf(v, (string)("")) { os.Setenv(k, v.(string)) } } if err := app.Run(parsed); err != nil { logrus.Error(err.Error()) } } func IsInstanceOf(objectPtr, typePtr interface{}) bool { return reflect.TypeOf(objectPtr) == reflect.TypeOf(typePtr) }
[ "\"AWS_REGION\"" ]
[]
[ "AWS_REGION" ]
[]
["AWS_REGION"]
go
1
0
spyder/app/mainwindow.py
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Spyder, the Scientific Python Development Environment ===================================================== Developed and maintained by the Spyder Project Contributors Copyright © Spyder Project Contributors Licensed under the terms of the MIT License (see spyder/__init__.py for details) """ # ============================================================================= # Stdlib imports # ============================================================================= from __future__ import print_function from collections import OrderedDict from enum import Enum import errno import gc import logging import os import os.path as osp import shutil import signal import socket import glob import sys import threading import traceback #============================================================================== # Check requirements before proceeding #============================================================================== from spyder import requirements requirements.check_path() requirements.check_qt() requirements.check_spyder_kernels() #============================================================================== # Third-party imports #============================================================================== from qtpy.compat import from_qvariant from qtpy.QtCore import (QCoreApplication, Qt, QTimer, Signal, Slot, qInstallMessageHandler) from qtpy.QtGui import QColor, QIcon, QKeySequence from qtpy.QtWidgets import (QAction, QApplication, QMainWindow, QMenu, QMessageBox, QShortcut, QStyleFactory, QCheckBox) # Avoid a "Cannot mix incompatible Qt library" error on Windows platforms from qtpy import QtSvg # analysis:ignore # Avoid a bug in Qt: https://bugreports.qt.io/browse/QTBUG-46720 from qtpy import QtWebEngineWidgets # analysis:ignore from qtawesome.iconic_font import FontError #============================================================================== # Local imports # NOTE: Move (if possible) import's of widgets and plugins exactly where they # are needed in MainWindow to speed up perceived startup time (i.e. the time # from clicking the Spyder icon to showing the splash screen). #============================================================================== from spyder import __version__ from spyder import dependencies from spyder.app import tour from spyder.app.utils import (create_splash_screen, delete_lsp_log_files, qt_message_handler, set_links_color, setup_logging, set_opengl_implementation, Spy) from spyder.config.base import (_, DEV, get_conf_path, get_debug_level, get_home_dir, get_module_source_path, get_safe_mode, is_pynsist, running_in_mac_app, running_under_pytest, STDERR) from spyder.utils.image_path_manager import get_image_path from spyder.config.gui import is_dark_font_color from spyder.config.main import OPEN_FILES_PORT from spyder.config.manager import CONF from spyder.config.utils import IMPORT_EXT, is_gtk_desktop from spyder.otherplugins import get_spyderplugins_mods from spyder.py3compat import configparser as cp, PY3, to_text_string from spyder.utils import encoding, programs from spyder.utils.icon_manager import ima from spyder.utils.misc import (select_port, getcwd_or_home, get_python_executable) from spyder.utils.palette import QStylePalette from spyder.utils.qthelpers import (create_action, add_actions, file_uri, qapplication, start_file) from spyder.utils.stylesheet import APP_STYLESHEET from spyder.app.solver import ( find_external_plugins, find_internal_plugins, solve_plugin_dependencies) # Spyder API Imports from spyder.api.exceptions import SpyderAPIError from spyder.api.plugins import Plugins, SpyderPluginV2, SpyderDockablePlugin #============================================================================== # Windows only local imports #============================================================================== set_attached_console_visible = None is_attached_console_visible = None set_windows_appusermodelid = None if os.name == 'nt': from spyder.utils.windows import (set_attached_console_visible, set_windows_appusermodelid) #============================================================================== # Constants #============================================================================== # Module logger logger = logging.getLogger(__name__) # Keeping a reference to the original sys.exit before patching it ORIGINAL_SYS_EXIT = sys.exit # Get the cwd before initializing WorkingDirectory, which sets it to the one # used in the last session CWD = getcwd_or_home() # Set the index for the default tour DEFAULT_TOUR = 0 #============================================================================== # Install Qt messaage handler #============================================================================== qInstallMessageHandler(qt_message_handler) #============================================================================== # Main Window #============================================================================== class MainWindow(QMainWindow): """Spyder main window""" DOCKOPTIONS = ( QMainWindow.AllowTabbedDocks | QMainWindow.AllowNestedDocks | QMainWindow.AnimatedDocks ) SPYDER_PATH = get_conf_path('path') SPYDER_NOT_ACTIVE_PATH = get_conf_path('not_active_path') DEFAULT_LAYOUTS = 4 # Signals restore_scrollbar_position = Signal() sig_setup_finished = Signal() all_actions_defined = Signal() # type: (OrderedDict, OrderedDict) sig_pythonpath_changed = Signal(object, object) sig_main_interpreter_changed = Signal() sig_open_external_file = Signal(str) sig_resized = Signal("QResizeEvent") # Related to interactive tour sig_moved = Signal("QMoveEvent") # Related to interactive tour sig_layout_setup_ready = Signal(object) # Related to default layouts # --- Plugin handling methods # ------------------------------------------------------------------------ def get_plugin(self, plugin_name, error=True): """ Return a plugin instance by providing the plugin class. """ for name, plugin in self._PLUGINS.items(): if plugin_name == name: return plugin else: if error: raise SpyderAPIError( 'Plugin "{}" not found!'.format(plugin_name)) else: return None def show_status_message(self, message, timeout): """ Show a status message in Spyder Main Window. """ status_bar = self.statusBar() if status_bar.isVisible(): status_bar.showMessage(message, timeout) def show_plugin_compatibility_message(self, message): """ Show a compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle(_('Compatibility Check')) messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.show() def add_plugin(self, plugin, external=False): """ Add plugin to plugins dictionary. """ self._PLUGINS[plugin.NAME] = plugin if external: self._EXTERNAL_PLUGINS[plugin.NAME] = plugin else: self._INTERNAL_PLUGINS[plugin.NAME] = plugin def register_plugin(self, plugin, external=False, omit_conf=False): """ Register a plugin in Spyder Main Window. """ self.set_splash(_("Loading {}...").format(plugin.get_name())) logger.info("Loading {}...".format(plugin.NAME)) # Check plugin compatibility is_compatible, message = plugin.check_compatibility() plugin.is_compatible = is_compatible plugin.get_description() if not is_compatible: self.show_compatibility_message(message) return # Signals plugin.sig_exception_occurred.connect(self.handle_exception) plugin.sig_free_memory_requested.connect(self.free_memory) plugin.sig_quit_requested.connect(self.close) plugin.sig_restart_requested.connect(self.restart) plugin.sig_redirect_stdio_requested.connect( self.redirect_internalshell_stdio) plugin.sig_status_message_requested.connect(self.show_status_message) if isinstance(plugin, SpyderDockablePlugin): plugin.sig_focus_changed.connect(self.plugin_focus_changed) plugin.sig_switch_to_plugin_requested.connect( self.switch_to_plugin) plugin.sig_update_ancestor_requested.connect( lambda: plugin.set_ancestor(self)) # Register plugin plugin._register(omit_conf=omit_conf) plugin.register() if isinstance(plugin, SpyderDockablePlugin): # Add dockwidget self.add_dockwidget(plugin) # Update margins margin = 0 if CONF.get('main', 'use_custom_margin'): margin = CONF.get('main', 'custom_margin') plugin.update_margins(margin) self.add_plugin(plugin, external=external) logger.info("Registering shortcuts for {}...".format(plugin.NAME)) for action_name, action in plugin.get_actions().items(): context = (getattr(action, 'shortcut_context', plugin.NAME) or plugin.NAME) if getattr(action, 'register_shortcut', True): if isinstance(action_name, Enum): action_name = action_name.value self.register_shortcut(action, context, action_name) if isinstance(plugin, SpyderDockablePlugin): try: context = '_' name = 'switch to {}'.format(plugin.CONF_SECTION) shortcut = CONF.get_shortcut(context, name, plugin_name=plugin.CONF_SECTION) except (cp.NoSectionError, cp.NoOptionError): shortcut = None sc = QShortcut(QKeySequence(), self, lambda: self.switch_to_plugin(plugin)) sc.setContext(Qt.ApplicationShortcut) plugin._shortcut = sc self.register_shortcut(sc, context, name) self.register_shortcut(plugin.toggle_view_action, context, name) def unregister_plugin(self, plugin): """ Unregister a plugin from the Spyder Main Window. """ logger.info("Unloading {}...".format(plugin.NAME)) # Disconnect all slots signals = [ plugin.sig_quit_requested, plugin.sig_redirect_stdio_requested, plugin.sig_status_message_requested, ] for sig in signals: try: sig.disconnect() except TypeError: pass # Unregister shortcuts for actions logger.info("Unregistering shortcuts for {}...".format(plugin.NAME)) for action_name, action in plugin.get_actions().items(): context = (getattr(action, 'shortcut_context', plugin.NAME) or plugin.NAME) self.shortcuts.unregister_shortcut(action, context, action_name) # Unregister switch to shortcut shortcut = None try: context = '_' name = 'switch to {}'.format(plugin.CONF_SECTION) shortcut = CONF.get_shortcut(context, name, plugin_name=plugin.CONF_SECTION) except Exception: pass if shortcut is not None: self.shortcuts.unregister_shortcut( plugin._shortcut, context, "Switch to {}".format(plugin.CONF_SECTION), ) # Remove dockwidget logger.info("Removing {} dockwidget...".format(plugin.NAME)) self.remove_dockwidget(plugin) plugin.unregister() plugin._unregister() def create_plugin_conf_widget(self, plugin): """ Create configuration dialog box page widget. """ config_dialog = self.prefs_dialog_instance if plugin.CONF_WIDGET_CLASS is not None and config_dialog is not None: conf_widget = plugin.CONF_WIDGET_CLASS(plugin, config_dialog) conf_widget.initialize() return conf_widget @property def last_plugin(self): """ Get last plugin with focus if it is a dockable widget. If a non-dockable plugin has the focus this will return by default the Editor plugin. """ # Needed to prevent errors with the old API at # spyder/plugins/base::_switch_to_plugin return self.layouts.get_last_plugin() def maximize_dockwidget(self, restore=False): """ This is needed to prevent errors with the old API at spyder/plugins/base::_switch_to_plugin. See spyder-ide/spyder#15164 Parameters ---------- restore : bool, optional If the current dockwidget needs to be restored to its unmaximized state. The default is False. """ self.layouts.maximize_dockwidget(restore=restore) def switch_to_plugin(self, plugin, force_focus=None): """ Switch to this plugin. Notes ----- This operation unmaximizes the current plugin (if any), raises this plugin to view (if it's hidden) and gives it focus (if possible). """ last_plugin = self.last_plugin try: # New API if (last_plugin is not None and last_plugin.get_widget().is_maximized and last_plugin is not plugin): self.layouts.maximize_dockwidget() except AttributeError: # Old API if (last_plugin is not None and self.last_plugin._ismaximized and last_plugin is not plugin): self.layouts.maximize_dockwidget() try: # New API if not plugin.toggle_view_action.isChecked(): plugin.toggle_view_action.setChecked(True) plugin.get_widget().is_visible = False except AttributeError: # Old API if not plugin._toggle_view_action.isChecked(): plugin._toggle_view_action.setChecked(True) plugin._widget._is_visible = False plugin.change_visibility(True, force_focus=force_focus) def remove_dockwidget(self, plugin): """ Remove a plugin QDockWidget from the main window. """ self.removeDockWidget(plugin.dockwidget) try: self.widgetlist.remove(plugin) except ValueError: pass def tabify_plugins(self, first, second): """Tabify plugin dockwigdets.""" self.tabifyDockWidget(first.dockwidget, second.dockwidget) def tabify_plugin(self, plugin, default=None): """ Tabify the plugin using the list of possible TABIFY options. Only do this if the dockwidget does not have more dockwidgets in the same position and if the plugin is using the New API. """ def tabify_helper(plugin, next_to_plugins): for next_to_plugin in next_to_plugins: try: self.tabify_plugins(next_to_plugin, plugin) break except SpyderAPIError as err: logger.error(err) # If TABIFY not defined use the [default] tabify = getattr(plugin, 'TABIFY', [default]) if not isinstance(tabify, list): next_to_plugins = [tabify] else: next_to_plugins = tabify # Check if TABIFY is not a list with None as unique value or a default # list if tabify in [[None], []]: return False # Get the actual plugins from the names next_to_plugins = [self.get_plugin(p) for p in next_to_plugins] # First time plugin starts if plugin.get_conf('first_time', True): if (isinstance(plugin, SpyderDockablePlugin) and plugin.NAME != Plugins.Console): logger.info( "Tabify {} dockwidget for the first time...".format( plugin.NAME)) tabify_helper(plugin, next_to_plugins) plugin.set_conf('enable', True) plugin.set_conf('first_time', False) else: # This is needed to ensure new plugins are placed correctly # without the need for a layout reset. logger.info("Tabify {} dockwidget...".format(plugin.NAME)) # Check if plugin has no other dockwidgets in the same position if not bool(self.tabifiedDockWidgets(plugin.dockwidget)): tabify_helper(plugin, next_to_plugins) return True def handle_exception(self, error_data): """ This method will call the handle exception method of the Console plugin. It is provided as a signal on the Plugin API for convenience, so that plugin do not need to explicitly call the Console plugin. Parameters ---------- error_data: dict The dictionary containing error data. The expected keys are: >>> error_data= { "text": str, "is_traceback": bool, "repo": str, "title": str, "label": str, "steps": str, } Notes ----- The `is_traceback` key indicates if `text` contains plain text or a Python error traceback. The `title` and `repo` keys indicate how the error data should customize the report dialog and Github error submission. The `label` and `steps` keys allow customizing the content of the error dialog. """ if self.console: self.console.handle_exception(error_data) def __init__(self, splash=None, options=None): QMainWindow.__init__(self) qapp = QApplication.instance() if running_under_pytest(): self._proxy_style = None else: from spyder.utils.qthelpers import SpyderProxyStyle # None is needed, see: https://bugreports.qt.io/browse/PYSIDE-922 self._proxy_style = SpyderProxyStyle(None) # Enabling scaling for high dpi qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) self.default_style = str(qapp.style().objectName()) self.init_workdir = options.working_directory self.profile = options.profile self.multithreaded = options.multithreaded self.new_instance = options.new_instance if options.project is not None and not running_in_mac_app(): self.open_project = osp.normpath(osp.join(CWD, options.project)) else: self.open_project = None self.window_title = options.window_title logger.info("Start of MainWindow constructor") def signal_handler(signum, frame=None): """Handler for signals.""" sys.stdout.write('Handling signal: %s\n' % signum) sys.stdout.flush() QApplication.quit() if os.name == "nt": try: import win32api win32api.SetConsoleCtrlHandler(signal_handler, True) except ImportError: pass else: signal.signal(signal.SIGTERM, signal_handler) if not DEV: # Make spyder quit when presing ctrl+C in the console # In DEV Ctrl+C doesn't quit, because it helps to # capture the traceback when spyder freezes signal.signal(signal.SIGINT, signal_handler) # Use a custom Qt stylesheet if sys.platform == 'darwin': spy_path = get_module_source_path('spyder') img_path = osp.join(spy_path, 'images') mac_style = open(osp.join(spy_path, 'app', 'mac_stylesheet.qss')).read() mac_style = mac_style.replace('$IMAGE_PATH', img_path) self.setStyleSheet(mac_style) # Shortcut management data self.shortcut_data = [] # Handle Spyder path self.path = () self.not_active_path = () self.project_path = () # New API self._APPLICATION_TOOLBARS = OrderedDict() self._STATUS_WIDGETS = OrderedDict() self._PLUGINS = OrderedDict() self._EXTERNAL_PLUGINS = OrderedDict() self._INTERNAL_PLUGINS = OrderedDict() # Mapping of new plugin identifiers vs old attributtes # names given for plugins or to prevent collisions with other # attributes, i.e layout (Qt) vs layout (SpyderPluginV2) self._INTERNAL_PLUGINS_MAPPING = { 'console': Plugins.Console, 'maininterpreter': Plugins.MainInterpreter, 'outlineexplorer': Plugins.OutlineExplorer, 'variableexplorer': Plugins.VariableExplorer, 'ipyconsole': Plugins.IPythonConsole, 'workingdirectory': Plugins.WorkingDirectory, 'projects': Plugins.Projects, 'findinfiles': Plugins.Find, 'layouts': Plugins.Layout, } self.thirdparty_plugins = [] # Tour # TODO: Should be a plugin self.tour = None self.tours_available = None self.tour_dialog = None # File switcher self.switcher = None # Preferences self.prefs_dialog_size = None self.prefs_dialog_instance = None # Actions self.undo_action = None self.redo_action = None self.copy_action = None self.cut_action = None self.paste_action = None self.selectall_action = None # Menu bars self.edit_menu = None self.edit_menu_actions = [] self.search_menu = None self.search_menu_actions = [] self.source_menu = None self.source_menu_actions = [] self.run_menu = None self.run_menu_actions = [] self.debug_menu = None self.debug_menu_actions = [] # TODO: Move to corresponding Plugins self.main_toolbar = None self.main_toolbar_actions = [] self.file_toolbar = None self.file_toolbar_actions = [] self.run_toolbar = None self.run_toolbar_actions = [] self.debug_toolbar = None self.debug_toolbar_actions = [] self.menus = [] if running_under_pytest(): # Show errors in internal console when testing. CONF.set('main', 'show_internal_errors', False) self.CURSORBLINK_OSDEFAULT = QApplication.cursorFlashTime() if set_windows_appusermodelid != None: res = set_windows_appusermodelid() logger.info("appusermodelid: %s", res) # Setting QTimer if running in travis test_app = os.environ.get('TEST_CI_APP') if test_app is not None: app = qapplication() timer_shutdown_time = 30000 self.timer_shutdown = QTimer(self) self.timer_shutdown.timeout.connect(app.quit) self.timer_shutdown.start(timer_shutdown_time) # Showing splash screen self.splash = splash if CONF.get('main', 'current_version', '') != __version__: CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day...) # List of satellite widgets (registered in add_dockwidget): self.widgetlist = [] # Flags used if closing() is called by the exit() shell command self.already_closed = False self.is_starting_up = True self.is_setting_up = True self.floating_dockwidgets = [] self.window_size = None self.window_position = None # To keep track of the last focused widget self.last_focused_widget = None self.previous_focused_widget = None # Keep track of dpi message self.show_dpi_message = True # Server to open external files on a single instance # This is needed in order to handle socket creation problems. # See spyder-ide/spyder#4132. if os.name == 'nt': try: self.open_files_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) except OSError: self.open_files_server = None QMessageBox.warning(None, "Spyder", _("An error occurred while creating a socket needed " "by Spyder. Please, try to run as an Administrator " "from cmd.exe the following command and then " "restart your computer: <br><br><span " "style=\'color: {color}\'><b>netsh winsock reset " "</b></span><br>").format( color=QStylePalette.COLOR_BACKGROUND_4)) else: self.open_files_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # To show the message about starting the tour self.sig_setup_finished.connect(self.show_tour_message) # Apply main window settings self.apply_settings() # To set all dockwidgets tabs to be on top (in case we want to do it # in the future) # self.setTabPosition(Qt.AllDockWidgetAreas, QTabWidget.North) logger.info("End of MainWindow constructor") # --- Window setup def _update_shortcuts_in_panes_menu(self, show=True): """ Display the shortcut for the "Switch to plugin..." on the toggle view action of the plugins displayed in the Help/Panes menu. Notes ----- SpyderDockablePlugins provide two actions that function as a single action. The `Switch to Plugin...` action has an assignable shortcut via the shortcut preferences. The `Plugin toggle View` in the `View` application menu, uses a custom `Toggle view action` that displays the shortcut assigned to the `Switch to Plugin...` action, but is not triggered by that shortcut. """ for plugin_id, plugin in self._PLUGINS.items(): if isinstance(plugin, SpyderDockablePlugin): try: # New API action = plugin.toggle_view_action except AttributeError: # Old API action = plugin._toggle_view_action if show: section = plugin.CONF_SECTION try: context = '_' name = 'switch to {}'.format(section) shortcut = CONF.get_shortcut( context, name, plugin_name=section) except (cp.NoSectionError, cp.NoOptionError): shortcut = QKeySequence() else: shortcut = QKeySequence() action.setShortcut(shortcut) def setup(self): """Setup main window.""" # TODO: Remove circular dependency between help and ipython console # and remove this import. Help plugin should take care of it from spyder.plugins.help.utils.sphinxify import CSS_PATH, DARK_CSS_PATH logger.info("*** Start of MainWindow setup ***") logger.info("Updating PYTHONPATH") path_dict = self.get_spyder_pythonpath_dict() self.update_python_path(path_dict) logger.info("Applying theme configuration...") ui_theme = CONF.get('appearance', 'ui_theme') color_scheme = CONF.get('appearance', 'selected') if ui_theme == 'dark': if not running_under_pytest(): # Set style proxy to fix combobox popup on mac and qdark qapp = QApplication.instance() qapp.setStyle(self._proxy_style) dark_qss = str(APP_STYLESHEET) self.setStyleSheet(dark_qss) self.statusBar().setStyleSheet(dark_qss) css_path = DARK_CSS_PATH elif ui_theme == 'light': if not running_under_pytest(): # Set style proxy to fix combobox popup on mac and qdark qapp = QApplication.instance() qapp.setStyle(self._proxy_style) light_qss = str(APP_STYLESHEET) self.setStyleSheet(light_qss) self.statusBar().setStyleSheet(light_qss) css_path = CSS_PATH elif ui_theme == 'automatic': if not is_dark_font_color(color_scheme): if not running_under_pytest(): # Set style proxy to fix combobox popup on mac and qdark qapp = QApplication.instance() qapp.setStyle(self._proxy_style) dark_qss = str(APP_STYLESHEET) self.setStyleSheet(dark_qss) self.statusBar().setStyleSheet(dark_qss) css_path = DARK_CSS_PATH else: light_qss = str(APP_STYLESHEET) self.setStyleSheet(light_qss) self.statusBar().setStyleSheet(light_qss) css_path = CSS_PATH # Set css_path as a configuration to be used by the plugins CONF.set('appearance', 'css_path', css_path) # Status bar status = self.statusBar() status.setObjectName("StatusBar") status.showMessage(_("Welcome to Spyder!"), 5000) # Switcher instance logger.info("Loading switcher...") self.create_switcher() message = _( "Spyder Internal Console\n\n" "This console is used to report application\n" "internal errors and to inspect Spyder\n" "internals with the following commands:\n" " spy.app, spy.window, dir(spy)\n\n" "Please don't use it to run your code\n\n" ) CONF.set('internal_console', 'message', message) CONF.set('internal_console', 'multithreaded', self.multithreaded) CONF.set('internal_console', 'profile', self.profile) CONF.set('internal_console', 'commands', []) CONF.set('internal_console', 'namespace', {}) CONF.set('internal_console', 'show_internal_errors', True) # Working directory initialization CONF.set('workingdir', 'init_workdir', self.init_workdir) # Load and register internal and external plugins external_plugins = find_external_plugins() internal_plugins = find_internal_plugins() all_plugins = external_plugins.copy() all_plugins.update(internal_plugins.copy()) # Determine 'enable' config for the plugins that have it enabled_plugins = {} for plugin in all_plugins.values(): plugin_name = plugin.NAME plugin_main_attribute_name = ( self._INTERNAL_PLUGINS_MAPPING[plugin_name] if plugin_name in self._INTERNAL_PLUGINS_MAPPING else plugin_name) try: if CONF.get(plugin_main_attribute_name, "enable"): enabled_plugins[plugin_name] = plugin except (cp.NoOptionError, cp.NoSectionError): enabled_plugins[plugin_name] = plugin # Get ordered list of plugins classes and instantiate them plugin_deps = solve_plugin_dependencies(list(enabled_plugins.values())) for plugin_class in plugin_deps: plugin_name = plugin_class.NAME # Non-migrated plugins if plugin_name in [ Plugins.Editor, Plugins.IPythonConsole]: if plugin_name == Plugins.IPythonConsole: plugin_instance = plugin_class(self) plugin_instance.sig_exception_occurred.connect( self.handle_exception) else: plugin_instance = plugin_class(self) plugin_instance.register_plugin() self.add_plugin(plugin_instance) self.preferences.register_plugin_preferences( plugin_instance) # Migrated or new plugins elif plugin_name in [ Plugins.MainMenu, Plugins.OnlineHelp, Plugins.Toolbar, Plugins.Preferences, Plugins.Appearance, Plugins.Run, Plugins.Shortcuts, Plugins.StatusBar, Plugins.Completions, Plugins.OutlineExplorer, Plugins.Console, Plugins.MainInterpreter, Plugins.Breakpoints, Plugins.History, Plugins.Profiler, Plugins.Explorer, Plugins.Help, Plugins.Plots, Plugins.VariableExplorer, Plugins.Application, Plugins.Find, Plugins.Pylint, Plugins.WorkingDirectory, Plugins.Projects, Plugins.Layout]: plugin_instance = plugin_class(self, configuration=CONF) self.register_plugin(plugin_instance) # TODO: Check thirdparty attribute usage # For now append plugins to the thirdparty attribute as was # being done if plugin_name in [ Plugins.Breakpoints, Plugins.Profiler, Plugins.Pylint]: self.thirdparty_plugins.append(plugin_instance) # Load external_plugins adding their dependencies elif (issubclass(plugin_class, SpyderPluginV2) and plugin_class.NAME in external_plugins): try: if plugin_class.CONF_FILE: CONF.register_plugin(plugin_class) plugin_instance = plugin_class( self, configuration=CONF, ) self.register_plugin(plugin_instance, external=True, omit_conf=plugin_class.CONF_FILE) # These attributes come from spyder.app.solver to add # plugins to the dependencies dialog if not running_under_pytest(): module = plugin_class._spyder_module_name package_name = plugin_class._spyder_package_name version = plugin_class._spyder_version description = plugin_instance.get_description() dependencies.add( module, package_name, description, version, None, kind=dependencies.PLUGIN) except Exception as error: print("%s: %s" % (plugin_class, str(error)), file=STDERR) traceback.print_exc(file=STDERR) self.set_splash(_("Loading old third-party plugins...")) for mod in get_spyderplugins_mods(): try: plugin = mod.PLUGIN_CLASS(self) if plugin.check_compatibility()[0]: if hasattr(plugin, 'CONFIGWIDGET_CLASS'): self.preferences.register_plugin_preferences(plugin) if hasattr(plugin, 'COMPLETION_PROVIDER_NAME'): self.completions.register_completion_plugin(plugin) else: self.thirdparty_plugins.append(plugin) plugin.register_plugin() # Add to dependencies dialog module = mod.__name__ name = module.replace('_', '-') if plugin.DESCRIPTION: description = plugin.DESCRIPTION else: description = plugin.get_plugin_title() dependencies.add(module, name, description, '', None, kind=dependencies.PLUGIN) except TypeError: # Fixes spyder-ide/spyder#13977 pass except Exception as error: print("%s: %s" % (mod, str(error)), file=STDERR) traceback.print_exc(file=STDERR) # Set window title self.set_window_title() # Menus # TODO: Remove when all menus are migrated to use the Main Menu Plugin logger.info("Creating Menus...") from spyder.api.widgets.menus import SpyderMenu from spyder.plugins.mainmenu.api import ( ApplicationMenus, HelpMenuSections, ToolsMenuSections, FileMenuSections) mainmenu = self.mainmenu self.edit_menu = mainmenu.get_application_menu("edit_menu") self.search_menu = mainmenu.get_application_menu("search_menu") self.source_menu = mainmenu.get_application_menu("source_menu") self.source_menu.aboutToShow.connect(self.update_source_menu) self.run_menu = mainmenu.get_application_menu("run_menu") self.debug_menu = mainmenu.get_application_menu("debug_menu") # Switcher shortcuts self.file_switcher_action = create_action( self, _('File switcher...'), icon=ima.icon('filelist'), tip=_('Fast switch between files'), triggered=self.open_switcher, context=Qt.ApplicationShortcut) self.register_shortcut(self.file_switcher_action, context="_", name="File switcher") self.symbol_finder_action = create_action( self, _('Symbol finder...'), icon=ima.icon('symbol_find'), tip=_('Fast symbol search in file'), triggered=self.open_symbolfinder, context=Qt.ApplicationShortcut) self.register_shortcut(self.symbol_finder_action, context="_", name="symbol finder", add_shortcut_to_tip=True) def create_edit_action(text, tr_text, icon): textseq = text.split(' ') method_name = textseq[0].lower()+"".join(textseq[1:]) action = create_action(self, tr_text, icon=icon, triggered=self.global_callback, data=method_name, context=Qt.WidgetShortcut) self.register_shortcut(action, "Editor", text) return action self.undo_action = create_edit_action('Undo', _('Undo'), ima.icon('undo')) self.redo_action = create_edit_action('Redo', _('Redo'), ima.icon('redo')) self.copy_action = create_edit_action('Copy', _('Copy'), ima.icon('editcopy')) self.cut_action = create_edit_action('Cut', _('Cut'), ima.icon('editcut')) self.paste_action = create_edit_action('Paste', _('Paste'), ima.icon('editpaste')) self.selectall_action = create_edit_action("Select All", _("Select All"), ima.icon('selectall')) self.edit_menu_actions += [self.undo_action, self.redo_action, None, self.cut_action, self.copy_action, self.paste_action, self.selectall_action, None] + self.editor.edit_menu_actions switcher_actions = [ self.file_switcher_action, self.symbol_finder_action ] for switcher_action in switcher_actions: mainmenu.add_item_to_application_menu( switcher_action, menu_id=ApplicationMenus.File, section=FileMenuSections.Switcher, before_section=FileMenuSections.Restart) self.set_splash("") # Toolbars # TODO: Remove after finishing the migration logger.info("Creating toolbars...") toolbar = self.toolbar self.file_toolbar = toolbar.get_application_toolbar("file_toolbar") self.run_toolbar = toolbar.get_application_toolbar("run_toolbar") self.debug_toolbar = toolbar.get_application_toolbar("debug_toolbar") self.main_toolbar = toolbar.get_application_toolbar("main_toolbar") # Tools + External Tools (some of this depends on the Application # plugin) logger.info("Creating Tools menu...") spyder_path_action = create_action( self, _("PYTHONPATH manager"), None, icon=ima.icon('pythonpath'), triggered=self.show_path_manager, tip=_("PYTHONPATH manager"), menurole=QAction.ApplicationSpecificRole) from spyder.plugins.application.plugin import ( ApplicationActions, WinUserEnvDialog) winenv_action = None if WinUserEnvDialog: winenv_action = self.application.get_action( ApplicationActions.SpyderWindowsEnvVariables) mainmenu.add_item_to_application_menu( spyder_path_action, menu_id=ApplicationMenus.Tools, section=ToolsMenuSections.Tools, before=winenv_action ) if get_debug_level() >= 3: self.menu_lsp_logs = QMenu(_("LSP logs")) self.menu_lsp_logs.aboutToShow.connect(self.update_lsp_logs) mainmenu.add_item_to_application_menu( self.menu_lsp_logs, menu_id=ApplicationMenus.Tools) # Main toolbar from spyder.plugins.toolbar.api import ( ApplicationToolbars, MainToolbarSections) self.toolbar.add_item_to_application_toolbar( spyder_path_action, toolbar_id=ApplicationToolbars.Main, section=MainToolbarSections.ApplicationSection ) self.set_splash(_("Setting up main window...")) #----- Tours # TODO: Move tours to a plugin structure self.tour = tour.AnimatedTour(self) # self.tours_menu = QMenu(_("Interactive tours"), self) # self.tour_menu_actions = [] # # TODO: Only show intro tour for now. When we are close to finish # # 3.0, we will finish and show the other tour self.tours_available = tour.get_tours(DEFAULT_TOUR) for i, tour_available in enumerate(self.tours_available): self.tours_available[i]['last'] = 0 tour_name = tour_available['name'] # def trigger(i=i, self=self): # closure needed! # return lambda: self.show_tour(i) # temp_action = create_action(self, tour_name, tip="", # triggered=trigger()) # self.tour_menu_actions += [temp_action] # self.tours_menu.addActions(self.tour_menu_actions) self.tour_action = create_action( self, self.tours_available[DEFAULT_TOUR]['name'], tip=_("Interactive tour introducing Spyder's panes and features"), triggered=lambda: self.show_tour(DEFAULT_TOUR)) mainmenu.add_item_to_application_menu( self.tour_action, menu_id=ApplicationMenus.Help, section=HelpMenuSections.Documentation) # TODO: Migrate to use the MainMenu Plugin instead of list of actions # Filling out menu/toolbar entries: add_actions(self.edit_menu, self.edit_menu_actions) add_actions(self.search_menu, self.search_menu_actions) add_actions(self.source_menu, self.source_menu_actions) add_actions(self.run_menu, self.run_menu_actions) add_actions(self.debug_menu, self.debug_menu_actions) # Emitting the signal notifying plugins that main window menu and # toolbar actions are all defined: self.all_actions_defined.emit() def __getattr__(self, attr): """ Redefinition of __getattr__ to enable access to plugins. Loaded plugins can be accessed as attributes of the mainwindow as before, e.g self.console or self.main.console, preserving the same accessor as before. """ # Mapping of new plugin identifiers vs old attributtes # names given for plugins if attr in self._INTERNAL_PLUGINS_MAPPING.keys(): return self.get_plugin(self._INTERNAL_PLUGINS_MAPPING[attr]) try: return self.get_plugin(attr) except SpyderAPIError: pass return super().__getattr__(attr) def update_lsp_logs(self): """Create an action for each lsp log file.""" self.menu_lsp_logs.clear() lsp_logs = [] files = glob.glob(osp.join(get_conf_path('lsp_logs'), '*.log')) for f in files: action = create_action(self, f, triggered=self.editor.load) action.setData(f) lsp_logs.append(action) add_actions(self.menu_lsp_logs, lsp_logs) def pre_visible_setup(self): """ Actions to be performed before the main window is visible. The actions here are related with setting up the main window. """ logger.info("Setting up window...") # Create external plugins before loading the layout to include them in # the window restore state after restarts. for plugin, plugin_instance in self._EXTERNAL_PLUGINS.items(): self.tabify_plugin(plugin_instance, Plugins.Console) if isinstance(plugin_instance, SpyderDockablePlugin): plugin_instance.get_widget().toggle_view(False) for plugin_id, plugin_instance in self._PLUGINS.items(): try: plugin_instance.before_mainwindow_visible() except AttributeError: pass if self.splash is not None: self.splash.hide() # Menu about to show for child in self.menuBar().children(): if isinstance(child, QMenu): try: child.aboutToShow.connect(self.update_edit_menu) child.aboutToShow.connect(self.update_search_menu) except TypeError: pass # Register custom layouts for plugin, plugin_instance in self._PLUGINS.items(): if hasattr(plugin_instance, 'CUSTOM_LAYOUTS'): if isinstance(plugin_instance.CUSTOM_LAYOUTS, list): for custom_layout in plugin_instance.CUSTOM_LAYOUTS: self.layouts.register_layout( self, custom_layout) else: logger.info( 'Unable to load custom layouts for {}. ' 'Expecting a list of layout classes but got {}' .format(plugin, plugin_instance.CUSTOM_LAYOUTS) ) self.layouts.update_layout_menu_actions() logger.info("*** End of MainWindow setup ***") self.is_starting_up = False def post_visible_setup(self): """Actions to be performed only after the main window's `show` method was triggered""" for __, plugin in self._PLUGINS.items(): try: plugin.on_mainwindow_visible() except AttributeError: pass self.restore_scrollbar_position.emit() logger.info('Deleting previous Spyder instance LSP logs...') delete_lsp_log_files() # Workaround for spyder-ide/spyder#880. # QDockWidget objects are not painted if restored as floating # windows, so we must dock them before showing the mainwindow, # then set them again as floating windows here. for widget in self.floating_dockwidgets: widget.setFloating(True) # Server to maintain just one Spyder instance and open files in it if # the user tries to start other instances with # $ spyder foo.py if (CONF.get('main', 'single_instance') and not self.new_instance and self.open_files_server): t = threading.Thread(target=self.start_open_files_server) t.setDaemon(True) t.start() # Connect the window to the signal emitted by the previous server # when it gets a client connected to it self.sig_open_external_file.connect(self.open_external_file) # Hide Internal Console so that people don't use it instead of # the External or IPython ones if self.console.dockwidget.isVisible() and DEV is None: self.console.toggle_view_action.setChecked(False) self.console.dockwidget.hide() # Show Help and Consoles by default plugins_to_show = [self.ipyconsole] if self.help is not None: plugins_to_show.append(self.help) for plugin in plugins_to_show: if plugin.dockwidget.isVisible(): plugin.dockwidget.raise_() # Update plugins toggle actions to show the "Switch to" plugin shortcut self._update_shortcuts_in_panes_menu() # Process pending events and hide splash before loading the # previous session. QApplication.processEvents() if self.splash is not None: self.splash.hide() # TODO: Remove this reference to projects once we can send the command # line options to the plugins. if self.open_project: if not running_in_mac_app(): self.projects.open_project( self.open_project, workdir=self.init_workdir ) else: # Load last project if a project was active when Spyder # was closed self.projects.reopen_last_project() # If no project is active, load last session if self.projects.get_active_project() is None: self.editor.setup_open_files(close_previous_files=False) # Raise the menuBar to the top of the main window widget's stack # Fixes spyder-ide/spyder#3887. self.menuBar().raise_() # Handle DPI scale and window changes to show a restart message. # Don't activate this functionality on macOS because it's being # triggered in the wrong situations. # See spyder-ide/spyder#11846 if not sys.platform == 'darwin': window = self.window().windowHandle() window.screenChanged.connect(self.handle_new_screen) screen = self.window().windowHandle().screen() self.current_dpi = screen.logicalDotsPerInch() screen.logicalDotsPerInchChanged.connect( self.show_dpi_change_message) # Notify that the setup of the mainwindow was finished self.is_setting_up = False self.sig_setup_finished.emit() def handle_new_screen(self, new_screen): """Connect DPI signals for new screen.""" if new_screen is not None: new_screen_dpi = new_screen.logicalDotsPerInch() if self.current_dpi != new_screen_dpi: self.show_dpi_change_message(new_screen_dpi) else: new_screen.logicalDotsPerInchChanged.connect( self.show_dpi_change_message) def handle_dpi_change_response(self, result, dpi): """Handle dpi change message dialog result.""" if self.dpi_change_dismiss_box.isChecked(): self.show_dpi_message = False self.dpi_change_dismiss_box = None if result == 0: # Restart button was clicked # Activate HDPI auto-scaling option since is needed for a # proper display when using OS scaling CONF.set('main', 'normal_screen_resolution', False) CONF.set('main', 'high_dpi_scaling', True) CONF.set('main', 'high_dpi_custom_scale_factor', False) self.restart() else: # Update current dpi for future checks self.current_dpi = dpi def show_dpi_change_message(self, dpi): """Show message to restart Spyder since the DPI scale changed.""" if not self.show_dpi_message: return if self.current_dpi != dpi: # Check the window state to not show the message if the window # is in fullscreen mode. window = self.window().windowHandle() if (window.windowState() == Qt.WindowFullScreen and sys.platform == 'darwin'): return self.dpi_change_dismiss_box = QCheckBox( _("Hide this message during the current session"), self ) msgbox = QMessageBox(self) msgbox.setIcon(QMessageBox.Warning) msgbox.setText( _ ("A monitor scale change was detected. <br><br>" "We recommend restarting Spyder to ensure that it's properly " "displayed. If you don't want to do that, please be sure to " "activate the option<br><br><tt>Enable auto high DPI scaling" "</tt><br><br>in <tt>Preferences > Application > " "Interface</tt>, in case Spyder is not displayed " "correctly.<br><br>" "Do you want to restart Spyder?")) msgbox.addButton(_('Restart now'), QMessageBox.NoRole) dismiss_button = msgbox.addButton( _('Dismiss'), QMessageBox.NoRole) msgbox.setCheckBox(self.dpi_change_dismiss_box) msgbox.setDefaultButton(dismiss_button) msgbox.finished.connect( lambda result: self.handle_dpi_change_response(result, dpi)) msgbox.open() def set_window_title(self): """Set window title.""" if DEV is not None: title = u"Spyder %s (Python %s.%s)" % (__version__, sys.version_info[0], sys.version_info[1]) elif running_in_mac_app() or is_pynsist(): title = "Spyder" else: title = u"Spyder (Python %s.%s)" % (sys.version_info[0], sys.version_info[1]) if get_debug_level(): title += u" [DEBUG MODE %d]" % get_debug_level() if self.window_title is not None: title += u' -- ' + to_text_string(self.window_title) # TODO: Remove self.projects reference once there's an API for setting # window title. if self.projects is not None: path = self.projects.get_active_project_path() if path: path = path.replace(get_home_dir(), u'~') title = u'{0} - {1}'.format(path, title) self.base_title = title self.setWindowTitle(self.base_title) # TODO: To be removed after all actions are moved to their corresponding # plugins def register_shortcut(self, qaction_or_qshortcut, context, name, add_shortcut_to_tip=True, plugin_name=None): self.shortcuts.register_shortcut( qaction_or_qshortcut, context, name, add_shortcut_to_tip=add_shortcut_to_tip, plugin_name=plugin_name, ) # --- Other def update_source_menu(self): """Update source menu options that vary dynamically.""" # This is necessary to avoid an error at startup. # Fixes spyder-ide/spyder#14901 try: self.editor.refresh_formatter_name() except AttributeError: pass def free_memory(self): """Free memory after event.""" gc.collect() def plugin_focus_changed(self): """Focus has changed from one plugin to another""" self.update_edit_menu() self.update_search_menu() def show_shortcuts(self, menu): """Show action shortcuts in menu.""" menu_actions = menu.actions() for action in menu_actions: if getattr(action, '_shown_shortcut', False): # This is a SpyderAction if action._shown_shortcut is not None: action.setShortcut(action._shown_shortcut) elif action.menu() is not None: # This is submenu, so we need to call this again self.show_shortcuts(action.menu()) else: # We don't need to do anything for other elements continue def hide_shortcuts(self, menu): """Hide action shortcuts in menu.""" menu_actions = menu.actions() for action in menu_actions: if getattr(action, '_shown_shortcut', False): # This is a SpyderAction if action._shown_shortcut is not None: action.setShortcut(QKeySequence()) elif action.menu() is not None: # This is submenu, so we need to call this again self.hide_shortcuts(action.menu()) else: # We don't need to do anything for other elements continue def hide_options_menus(self): """Hide options menu when menubar is pressed in macOS.""" for plugin in self.widgetlist + self.thirdparty_plugins: if plugin.CONF_SECTION == 'editor': editorstack = self.editor.get_current_editorstack() editorstack.menu.hide() else: try: # New API plugin.options_menu.hide() except AttributeError: # Old API plugin._options_menu.hide() def get_focus_widget_properties(self): """Get properties of focus widget Returns tuple (widget, properties) where properties is a tuple of booleans: (is_console, not_readonly, readwrite_editor)""" from spyder.plugins.editor.widgets.base import TextEditBaseWidget from spyder.plugins.ipythonconsole.widgets import ControlWidget widget = QApplication.focusWidget() textedit_properties = None if isinstance(widget, (TextEditBaseWidget, ControlWidget)): console = isinstance(widget, ControlWidget) not_readonly = not widget.isReadOnly() readwrite_editor = not_readonly and not console textedit_properties = (console, not_readonly, readwrite_editor) return widget, textedit_properties def update_edit_menu(self): """Update edit menu""" widget, textedit_properties = self.get_focus_widget_properties() if textedit_properties is None: # widget is not an editor/console return # !!! Below this line, widget is expected to be a QPlainTextEdit # instance console, not_readonly, readwrite_editor = textedit_properties # Editor has focus and there is no file opened in it if (not console and not_readonly and self.editor and not self.editor.is_file_opened()): return # Disabling all actions to begin with for child in self.edit_menu.actions(): child.setEnabled(False) self.selectall_action.setEnabled(True) # Undo, redo self.undo_action.setEnabled( readwrite_editor \ and widget.document().isUndoAvailable() ) self.redo_action.setEnabled( readwrite_editor \ and widget.document().isRedoAvailable() ) # Copy, cut, paste, delete has_selection = widget.has_selected_text() self.copy_action.setEnabled(has_selection) self.cut_action.setEnabled(has_selection and not_readonly) self.paste_action.setEnabled(not_readonly) # Comment, uncomment, indent, unindent... if not console and not_readonly: # This is the editor and current file is writable if self.editor: for action in self.editor.edit_menu_actions: action.setEnabled(True) def update_search_menu(self): """Update search menu""" # Disabling all actions except the last one # (which is Find in files) to begin with for child in self.search_menu.actions()[:-1]: child.setEnabled(False) widget, textedit_properties = self.get_focus_widget_properties() if textedit_properties is None: # widget is not an editor/console return # !!! Below this line, widget is expected to be a QPlainTextEdit # instance console, not_readonly, readwrite_editor = textedit_properties # Find actions only trigger an effect in the Editor if not console: for action in self.search_menu.actions(): try: action.setEnabled(True) except RuntimeError: pass # Disable the replace action for read-only files if len(self.search_menu_actions) > 3: self.search_menu_actions[3].setEnabled(readwrite_editor) def createPopupMenu(self): return self.application.get_application_context_menu(parent=self) def set_splash(self, message): """Set splash message""" if self.splash is None: return if message: logger.info(message) self.splash.show() self.splash.showMessage(message, int(Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute), QColor(Qt.white)) QApplication.processEvents() def closeEvent(self, event): """closeEvent reimplementation""" if self.closing(True): event.accept() else: event.ignore() def resizeEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.layouts.get_fullscreen_flag(): self.window_size = self.size() QMainWindow.resizeEvent(self, event) # To be used by the tour to be able to resize self.sig_resized.emit(event) def moveEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.layouts.get_fullscreen_flag(): self.window_position = self.pos() QMainWindow.moveEvent(self, event) # To be used by the tour to be able to move self.sig_moved.emit(event) def hideEvent(self, event): """Reimplement Qt method""" try: for plugin in (self.widgetlist + self.thirdparty_plugins): # TODO: Remove old API try: # New API if plugin.get_widget().isAncestorOf( self.last_focused_widget): plugin.change_visibility(True) except AttributeError: # Old API if plugin.isAncestorOf(self.last_focused_widget): plugin._visibility_changed(True) QMainWindow.hideEvent(self, event) except RuntimeError: QMainWindow.hideEvent(self, event) def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QApplication.focusWidget() elif now is not None: self.last_focused_widget = now self.previous_focused_widget = old def closing(self, cancelable=False): """Exit tasks""" if self.already_closed or self.is_starting_up: return True if cancelable and CONF.get('main', 'prompt_on_exit'): reply = QMessageBox.critical(self, 'Spyder', 'Do you really want to exit?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.No: return False if CONF.get('main', 'single_instance') and self.open_files_server: self.open_files_server.close() # Internal plugins for plugin in (self.widgetlist + self.thirdparty_plugins): # New API try: if isinstance(plugin, SpyderDockablePlugin): plugin.close_window() if not plugin.on_close(cancelable): return False except AttributeError: pass # Old API try: plugin._close_window() if not plugin.closing_plugin(cancelable): return False except AttributeError: pass # New API: External plugins for plugin_name, plugin in self._EXTERNAL_PLUGINS.items(): try: if isinstance(plugin, SpyderDockablePlugin): plugin.close_window() if not plugin.on_close(cancelable): return False except AttributeError as e: logger.error(str(e)) # Save window settings *after* closing all plugin windows, in order # to show them in their previous locations in the next session. # Fixes spyder-ide/spyder#12139 prefix = 'window' + '/' self.layouts.save_current_window_settings(prefix) self.already_closed = True return True def add_dockwidget(self, plugin): """ Add a plugin QDockWidget to the main window. """ try: # New API if plugin.is_compatible: dockwidget, location = plugin.create_dockwidget(self) self.addDockWidget(location, dockwidget) self.widgetlist.append(plugin) except AttributeError: # Old API if plugin._is_compatible: dockwidget, location = plugin._create_dockwidget() self.addDockWidget(location, dockwidget) self.widgetlist.append(plugin) @Slot() def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = from_qvariant(action.data(), to_text_string) from spyder.plugins.editor.widgets.base import TextEditBaseWidget from spyder.plugins.ipythonconsole.widgets import ControlWidget if isinstance(widget, (TextEditBaseWidget, ControlWidget)): getattr(widget, callback)() else: return def redirect_internalshell_stdio(self, state): if state: self.console.redirect_stds() else: self.console.restore_stds() def open_external_console(self, fname, wdir, args, interact, debug, python, python_args, systerm, post_mortem=False): """Open external console""" if systerm: # Running script in an external system terminal try: if CONF.get('main_interpreter', 'default'): executable = get_python_executable() else: executable = CONF.get('main_interpreter', 'executable') programs.run_python_script_in_terminal( fname, wdir, args, interact, debug, python_args, executable) except NotImplementedError: QMessageBox.critical(self, _("Run"), _("Running an external system terminal " "is not supported on platform %s." ) % os.name) def open_file(self, fname, external=False): """ Open filename with the appropriate application Redirect to the right widget (txt -> editor, spydata -> workspace, ...) or open file outside Spyder (if extension is not supported) """ fname = to_text_string(fname) ext = osp.splitext(fname)[1] if encoding.is_text_file(fname): self.editor.load(fname) elif self.variableexplorer is not None and ext in IMPORT_EXT: self.variableexplorer.import_data(fname) elif not external: fname = file_uri(fname) start_file(fname) def open_external_file(self, fname): """ Open external files that can be handled either by the Editor or the variable explorer inside Spyder. """ # Check that file exists fname = encoding.to_unicode_from_fs(fname) if osp.exists(osp.join(CWD, fname)): fpath = osp.join(CWD, fname) elif osp.exists(fname): fpath = fname else: return # Don't open script that starts Spyder at startup. # Fixes issue spyder-ide/spyder#14483 if sys.platform == 'darwin' and 'bin/spyder' in fname: return if osp.isfile(fpath): self.open_file(fpath, external=True) elif osp.isdir(fpath): QMessageBox.warning( self, _("Error"), _('To open <code>{fpath}</code> as a project with Spyder, ' 'please use <code>spyder -p "{fname}"</code>.') .format(fpath=osp.normpath(fpath), fname=fname) ) # --- Path Manager # ------------------------------------------------------------------------ def load_python_path(self): """Load path stored in Spyder configuration folder.""" if osp.isfile(self.SPYDER_PATH): with open(self.SPYDER_PATH, 'r', encoding='utf-8') as f: path = f.read().splitlines() self.path = tuple(name for name in path if osp.isdir(name)) if osp.isfile(self.SPYDER_NOT_ACTIVE_PATH): with open(self.SPYDER_NOT_ACTIVE_PATH, 'r', encoding='utf-8') as f: not_active_path = f.read().splitlines() self.not_active_path = tuple(name for name in not_active_path if osp.isdir(name)) def save_python_path(self, new_path_dict): """ Save path in Spyder configuration folder. `new_path_dict` is an OrderedDict that has the new paths as keys and the state as values. The state is `True` for active and `False` for inactive. """ path = [p for p in new_path_dict] not_active_path = [p for p in new_path_dict if not new_path_dict[p]] try: encoding.writelines(path, self.SPYDER_PATH) encoding.writelines(not_active_path, self.SPYDER_NOT_ACTIVE_PATH) except EnvironmentError as e: logger.error(str(e)) CONF.set('main', 'spyder_pythonpath', self.get_spyder_pythonpath()) def get_spyder_pythonpath_dict(self): """ Return Spyder PYTHONPATH. The returned ordered dictionary has the paths as keys and the state as values. The state is `True` for active and `False` for inactive. Example: OrderedDict([('/some/path, True), ('/some/other/path, False)]) """ self.load_python_path() path_dict = OrderedDict() for path in self.path: path_dict[path] = path not in self.not_active_path for path in self.project_path: path_dict[path] = True return path_dict def get_spyder_pythonpath(self): """ Return Spyder PYTHONPATH. """ path_dict = self.get_spyder_pythonpath_dict() path = [k for k, v in path_dict.items() if v] return path def update_python_path(self, new_path_dict): """Update python path on Spyder interpreter and kernels.""" # Load previous path path_dict = self.get_spyder_pythonpath_dict() # Save path if path_dict != new_path_dict: # It doesn't include the project_path self.save_python_path(new_path_dict) # Load new path new_path_dict_p = self.get_spyder_pythonpath_dict() # Includes project # Update Spyder interpreter for path in path_dict: while path in sys.path: sys.path.remove(path) for path, active in reversed(new_path_dict_p.items()): if active: sys.path.insert(1, path) # Any plugin that needs to do some work based on this signal should # connect to it on plugin registration self.sig_pythonpath_changed.emit(path_dict, new_path_dict_p) @Slot() def show_path_manager(self): """Show path manager dialog.""" from spyder.widgets.pathmanager import PathManager read_only_path = tuple(self.projects.get_pythonpath()) dialog = PathManager(self, self.path, read_only_path, self.not_active_path, sync=True) self._path_manager = dialog dialog.sig_path_changed.connect(self.update_python_path) dialog.redirect_stdio.connect(self.redirect_internalshell_stdio) dialog.show() def pythonpath_changed(self): """Project's PYTHONPATH contribution has changed.""" self.project_path = tuple(self.projects.get_pythonpath()) path_dict = self.get_spyder_pythonpath_dict() self.update_python_path(path_dict) #---- Preferences def apply_settings(self): """Apply main window settings.""" qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes spyder-ide/spyder#2036. if is_gtk_desktop() and ('GTK+' in QStyleFactory.keys()): try: qapp.setStyle('gtk+') except: pass default = self.DOCKOPTIONS if CONF.get('main', 'vertical_tabs'): default = default|QMainWindow.VerticalTabs self.setDockOptions(default) self.apply_panes_settings() if CONF.get('main', 'use_custom_cursor_blinking'): qapp.setCursorFlashTime( CONF.get('main', 'custom_cursor_blinking')) else: qapp.setCursorFlashTime(self.CURSORBLINK_OSDEFAULT) def apply_panes_settings(self): """Update dockwidgets features settings.""" for plugin in (self.widgetlist + self.thirdparty_plugins): features = plugin.dockwidget.FEATURES plugin.dockwidget.setFeatures(features) try: # New API margin = 0 if CONF.get('main', 'use_custom_margin'): margin = CONF.get('main', 'custom_margin') plugin.update_margins(margin) except AttributeError: # Old API plugin._update_margins() @Slot() def show_preferences(self): """Edit Spyder preferences.""" self.preferences.open_dialog(self.prefs_dialog_size) def set_prefs_size(self, size): """Save preferences dialog size.""" self.prefs_dialog_size = size # -- Open files server def start_open_files_server(self): self.open_files_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) port = select_port(default_port=OPEN_FILES_PORT) CONF.set('main', 'open_files_port', port) self.open_files_server.bind(('127.0.0.1', port)) self.open_files_server.listen(20) while 1: # 1 is faster than True try: req, dummy = self.open_files_server.accept() except socket.error as e: # See spyder-ide/spyder#1275 for details on why errno EINTR is # silently ignored here. eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR # To avoid a traceback after closing on Windows if e.args[0] == eintr: continue # handle a connection abort on close error enotsock = (errno.WSAENOTSOCK if os.name == 'nt' else errno.ENOTSOCK) if e.args[0] in [errno.ECONNABORTED, enotsock]: return raise fname = req.recv(1024) fname = fname.decode('utf-8') self.sig_open_external_file.emit(fname) req.sendall(b' ') # ---- Quit and restart, and reset spyder defaults @Slot() def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """ answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do you want to continue?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart(reset=True) @Slot() def restart(self, reset=False): """Wrapper to handle plugins request to restart Spyder.""" self.application.restart(reset=reset) # ---- Interactive Tours def show_tour(self, index): """Show interactive tour.""" self.layouts.maximize_dockwidget(restore=True) frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour() # ---- Global Switcher def open_switcher(self, symbol=False): """Open switcher dialog box.""" if self.switcher is not None and self.switcher.isVisible(): self.switcher.clear() self.switcher.hide() return if symbol: self.switcher.set_search_text('@') else: self.switcher.set_search_text('') self.switcher.setup() self.switcher.show() # Note: The +6 pixel on the top makes it look better # FIXME: Why is this using the toolbars menu? A: To not be on top of # the toolbars. # Probably toolbars should be taken into account for this 'delta' only # when are visible delta_top = (self.toolbar.toolbars_menu.geometry().height() + self.menuBar().geometry().height() + 6) self.switcher.set_position(delta_top) def open_symbolfinder(self): """Open symbol list management dialog box.""" self.open_switcher(symbol=True) def create_switcher(self): """Create switcher dialog instance.""" if self.switcher is None: from spyder.widgets.switcher import Switcher self.switcher = Switcher(self) return self.switcher @Slot() def show_tour_message(self, force=False): """ Show message about starting the tour the first time Spyder starts. """ should_show_tour = CONF.get('main', 'show_tour_message') if force or (should_show_tour and not running_under_pytest() and not get_safe_mode()): CONF.set('main', 'show_tour_message', False) self.tour_dialog = tour.OpenTourDialog( self, lambda: self.show_tour(DEFAULT_TOUR)) self.tour_dialog.show() # --- For OpenGL def _test_setting_opengl(self, option): """Get the current OpenGL implementation in use""" if option == 'software': return QCoreApplication.testAttribute(Qt.AA_UseSoftwareOpenGL) elif option == 'desktop': return QCoreApplication.testAttribute(Qt.AA_UseDesktopOpenGL) elif option == 'gles': return QCoreApplication.testAttribute(Qt.AA_UseOpenGLES) #============================================================================== # Utilities for the 'main' function below #============================================================================== def create_application(): """Create application and patch sys.exit.""" # Our QApplication app = qapplication() # --- Set application icon app_icon = QIcon(get_image_path("spyder")) app.setWindowIcon(app_icon) # Required for correct icon on GNOME/Wayland: if hasattr(app, 'setDesktopFileName'): app.setDesktopFileName('spyder') #----Monkey patching QApplication class FakeQApplication(QApplication): """Spyder's fake QApplication""" def __init__(self, args): self = app # analysis:ignore @staticmethod def exec_(): """Do nothing because the Qt mainloop is already running""" pass from qtpy import QtWidgets QtWidgets.QApplication = FakeQApplication # ----Monkey patching sys.exit def fake_sys_exit(arg=[]): pass sys.exit = fake_sys_exit # ----Monkey patching sys.excepthook to avoid crashes in PyQt 5.5+ def spy_excepthook(type_, value, tback): sys.__excepthook__(type_, value, tback) sys.excepthook = spy_excepthook # Removing arguments from sys.argv as in standard Python interpreter sys.argv = [''] return app def create_window(app, splash, options, args): """ Create and show Spyder's main window and start QApplication event loop. """ # Main window main = MainWindow(splash, options) try: main.setup() except BaseException: if main.console is not None: try: main.console.exit_interpreter() except BaseException: pass raise main.pre_visible_setup() main.show() main.post_visible_setup() if main.console: namespace = CONF.get('internal_console', 'namespace', {}) main.console.start_interpreter(namespace) main.console.set_namespace_item('spy', Spy(app=app, window=main)) # Propagate current configurations to all configuration observers CONF.notify_all_observers() # Don't show icons in menus for Mac if sys.platform == 'darwin': QCoreApplication.setAttribute(Qt.AA_DontShowIconsInMenus, True) # Open external files with our Mac app if running_in_mac_app(): app.sig_open_external_file.connect(main.open_external_file) app._has_started = True if hasattr(app, '_pending_file_open'): if args: args = app._pending_file_open + args else: args = app._pending_file_open # Open external files passed as args if args: for a in args: main.open_external_file(a) # To give focus again to the last focused widget after restoring # the window app.focusChanged.connect(main.change_last_focused_widget) if not running_under_pytest(): app.exec_() return main #============================================================================== # Main #============================================================================== def main(options, args): """Main function""" # **** For Pytest **** if running_under_pytest(): if CONF.get('main', 'opengl') != 'automatic': option = CONF.get('main', 'opengl') set_opengl_implementation(option) app = create_application() window = create_window(app, None, options, None) return window # **** Handle hide_console option **** if options.show_console: print("(Deprecated) --show console does nothing, now the default " " behavior is to show the console, use --hide-console if you " "want to hide it") if set_attached_console_visible is not None: set_attached_console_visible(not options.hide_console or options.reset_config_files or options.reset_to_defaults or options.optimize or bool(get_debug_level())) # **** Set OpenGL implementation to use **** # This attribute must be set before creating the application. # See spyder-ide/spyder#11227 if options.opengl_implementation: option = options.opengl_implementation set_opengl_implementation(option) else: if CONF.get('main', 'opengl') != 'automatic': option = CONF.get('main', 'opengl') set_opengl_implementation(option) # **** Set high DPI scaling **** # This attribute must be set before creating the application. if hasattr(Qt, 'AA_EnableHighDpiScaling'): QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, CONF.get('main', 'high_dpi_scaling')) # **** Set debugging info **** setup_logging(options) # **** Create the application **** app = create_application() # **** Create splash screen **** splash = create_splash_screen() if splash is not None: splash.show() splash.showMessage( _("Initializing..."), int(Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute), QColor(Qt.white) ) QApplication.processEvents() if options.reset_to_defaults: # Reset Spyder settings to defaults CONF.reset_to_defaults() return elif options.optimize: # Optimize the whole Spyder's source code directory import spyder programs.run_python_script(module="compileall", args=[spyder.__path__[0]], p_args=['-O']) return # **** Read faulthandler log file **** faulthandler_file = get_conf_path('faulthandler.log') previous_crash = '' if osp.exists(faulthandler_file): with open(faulthandler_file, 'r') as f: previous_crash = f.read() # Remove file to not pick it up for next time. try: dst = get_conf_path('faulthandler.log.old') shutil.move(faulthandler_file, dst) except Exception: pass CONF.set('main', 'previous_crash', previous_crash) # **** Set color for links **** set_links_color(app) # **** Create main window **** mainwindow = None try: if PY3 and options.report_segfault: import faulthandler with open(faulthandler_file, 'w') as f: faulthandler.enable(file=f) mainwindow = create_window(app, splash, options, args) else: mainwindow = create_window(app, splash, options, args) except FontError: QMessageBox.information(None, "Spyder", "Spyder was unable to load the <i>Spyder 3</i> " "icon theme. That's why it's going to fallback to the " "theme used in Spyder 2.<br><br>" "For that, please close this window and start Spyder again.") CONF.set('appearance', 'icon_theme', 'spyder 2') if mainwindow is None: # An exception occurred if splash is not None: splash.hide() return ORIGINAL_SYS_EXIT() if __name__ == "__main__": main()
[]
[]
[ "TEST_CI_APP" ]
[]
["TEST_CI_APP"]
python
1
0
viewpoint_learning/code/train_images.py
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' \brief Code to train DLDL \copyright Copyright (c) 2021 Visual Computing group of Ulm University, Germany. See the LICENSE file at the top-level directory of this distribution. ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import sys import math import time import argparse import importlib import os import numpy as np import tensorflow as tf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' BASE_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.dirname(BASE_DIR) ROOT_DIR = os.path.dirname(PROJECT_DIR) DATA_DIR = os.path.join(PROJECT_DIR, 'data') sys.path.append(os.path.join(BASE_DIR, 'models')) sys.path.append(os.path.join(BASE_DIR, 'helpers')) sys.path.append(ROOT_DIR + '/MCCNN/utils') from PyUtils import visualize_progress from train_ops import create_mult_loss_approx, BN_decay, create_feed_dict_gauss from VQDataSet_DLDL import VQDataSet #from VQs import getAs, getPz, getProb, getFaceIds, getIds, vq4, vq5, vq7, vq8, vq12, vq14 #from Application import GLScene current_milli_time = lambda: time.time() * 1000.0 def fibonacci_sphere(samples=1000,randomize=False): # creates almost uniformly distributed grid of points over unit sphere # INPUT: # samples: int - number of points to be generated # randomize: bool - if True shuffles the points # OUTPUT: # points: list nx3 - points on the ficonacci_sphere rnd = 1. if randomize: rnd = random.random() * samples points = [] offset = 2./samples increment = math.pi * (3. - math.sqrt(5.)); for i in range(samples): y = ((i * offset) - 1) + (offset / 2); r = math.sqrt(1 - pow(y,2)) phi = ((i + rnd) % samples) * increment x = math.cos(phi) * r z = math.sin(phi) * r points.append([x,y,z]) return points unif_pts = fibonacci_sphere(1000) def create_loss_mult_tf(pred_images_all, numOutputs, inImages, ref_views): pred_views_list = [] loss_list = [] pred_views_ids = [] for i in range(numOutputs): pred_images = tf.reshape(pred_images_all[i], [-1, 32, 32]) pred_views_id = tf.arg_max(tf.reshape(pred_images, [-1, 1024]), dimension=1) pred_views = tf.gather(ref_views, pred_views_id) labels = inImages[i] loss= create_loss_tf(pred_images, labels) pred_views_list.append(pred_views) loss_list.append(loss) pred_views_ids.append(pred_views_id) pred_views = tf.concat(pred_views_list, axis = 1) loss = tf.stack(loss_list) lossGraph = tf.reduce_mean(loss) return lossGraph, pred_views, loss, pred_views_ids def create_loss_tf(pred_images, labels): return tf.losses.mean_squared_error(labels, pred_images) def create_training(lossGraph, learningRate, minLearningRate, learningDecayFactor, learningDecayRate, global_step): learningRateExp = tf.train.exponential_decay(learningRate, global_step, learningDecayRate, learningDecayFactor, staircase=True) learningRateExp = tf.maximum(learningRateExp, minLearningRate) optimizer = tf.train.AdamOptimizer(learning_rate =learningRateExp) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize(lossGraph, global_step=global_step) return train_op, learningRateExp def create_loss_metrics_mult(loss, VQLoss, numOutputs): loss_list = [] acc_list = [] vq_list = [] train_list = [] test_list = [] vq_op_list = [] for i in range(numOutputs): accumLoss, accumVQLoss, accumOpsTrain, accumOpsTest, accumVQLossOp = create_loss_metrics(loss[i], VQLoss[i]) loss_list.append(accumLoss) vq_list.append(accumVQLoss) train_list.append(accumOpsTrain) test_list.append(accumOpsTest) vq_op_list.append(accumVQLossOp) accumTrainOp = tf.tuple(train_list) accumTestOp = tf.tuple(test_list) accumVQLossOp = tf.tuple(vq_op_list) return loss_list, vq_list, accumTrainOp, accumTestOp, accumVQLossOp def create_loss_metrics(loss, VQLoss): accumLoss, accumLossOp = tf.metrics.mean(loss, name = 'metrics') accumVQLoss, accumVQLossOp = tf.metrics.mean(VQLoss, name = 'metrics') accumOpsTrain = tf.group(accumLossOp) accumOpsTest = tf.group(accumLossOp ) return accumLoss, accumVQLoss, accumOpsTrain, accumOpsTest, accumVQLossOp def create_summaries(accumLoss, accumVQLoss, VQs, numOutputs): train_list = [] test_list = [] for i in range(numOutputs): # training train_list.append(tf.summary.scalar('Train VQ ' + VQs[i] + ' cosine distance', accumLoss[i])) train_list.append(tf.summary.scalar('Train VQ ' + VQs[i] + ' loss', accumVQLoss[i])) # testing test_list.append(tf.summary.scalar('Val VQ ' + VQs[i] + ' cosine distance', accumLoss[i])) test_list.append(tf.summary.scalar('Val VQ ' + VQs[i] + ' loss', accumVQLoss[i])) accumLoss = tf.reduce_mean(tf.stack(accumLoss)) accumVQLoss = tf.reduce_mean(tf.stack(accumVQLoss)) train_list.append(tf.summary.scalar('Train total cosine distance', accumLoss)) train_list.append(tf.summary.scalar('Train total VQ loss', accumVQLoss)) # testing test_list.append(tf.summary.scalar('Val total cosine distance', accumLoss)) test_list.append(tf.summary.scalar('Val total VQ loss', accumVQLoss)) train_list.append(tf.summary.scalar('learninRate', learningRateExp)) train_list.append(tf.summary.scalar('BN_Momentum', BNMomentum)) trainingSummary = tf.summary.merge(train_list) testSummary = tf.summary.merge(test_list) return trainingSummary, testSummary, accumLoss, accumVQLoss def logfolder_name(args): normal_string = '' if args.useNormals: normal_string = 'wNormals_' if args.cates == None or ',' in args.cates: cate_string = '' else: cate_string = args.cates + '_' aug_string = 'aug' if not args.augment: aug_string = 'noaug' elif args.rotation_axis != '012': aug_string += 'rot'+args.rotation_axis aug_string += '_' if args.noise: aug_string += 'noise_' if args.symmetric_deformations: aug_string += 'symdef_' return args.logFolder + '/numPts'+str(args.maxNumPts)+'_LR' + str(args.initLearningRate) + '_LDR' + str(args.learningDecayRate) + '_LDF' + str(args.learningDecayFactor)+ '_grow' + str(args.grow)+'_bs'+str(args.batchSize) + '_' + cate_string + normal_string + aug_string + args.affix if __name__ == '__main__': parser = argparse.ArgumentParser(description='Script to train MCCNN for View Point Optimization of point clouds (SHREC15)') parser.add_argument('--logFolder', default='log', help='Folder of the output models (default: log)') parser.add_argument('--folders','--f', default='ModelNet40', help='data folders') parser.add_argument('--model', default='MCRegV_images', help='model (default: MCRegV_small)') parser.add_argument('--grow', default=64, type=int, help='Grow rate (default: 64)') parser.add_argument('--batchSize', default=8, type=int, help='Batch size (default: 8)') parser.add_argument('--maxEpoch', default=201, type=int, help='Max Epoch (default: 201)') parser.add_argument('--initLearningRate', default=0.001, type=float, help='Init learning rate (default: 0.005)') parser.add_argument('--learningDecayFactor', default=0.5, type=float, help='Learning decay factor (default: 0.5)') parser.add_argument('--learningDecayRate', default=20, type=int, help='Learning decay rate (default: 20 Epochs)') parser.add_argument('--minLearningRate', default=0.00001, type=float, help='Minimum Learning rate (default: 0.00001)') parser.add_argument('--weightDecay', default=0.0, type=float, help='WeightDecay ( default:0.0(disabled))') parser.add_argument('--useDropOut', action='store_true', help='Use drop out (default: False)') parser.add_argument('--dropOutKeepProb', default=0.5, type=float, help='Keep neuron probabillity drop out (default: 0.5)') parser.add_argument('--useDropOutConv', action='store_true', help='Use drop out in convolution layers (default: False)') parser.add_argument('--dropOutKeepProbConv', default=0.8, type=float, help='Keep neuron probabillity drop out in convolution layers (default: 0.8)') parser.add_argument('--augment', action='store_true', help='Augment data using rotations (default: False)') parser.add_argument('--noise', action='store_true', help='Augment data using noise (default: False)') parser.add_argument('--symmetric_deformations', action='store_true', help='Augment data using symmetric deformations (default: False)') parser.add_argument('--gpu', default='0', help='GPU (default: 0)') parser.add_argument('--restore', action='store_true', help='Restore previous model (default: False)') parser.add_argument('--no_eval', action='store_true', help='Do not run the evaluation at the end') parser.add_argument('--fix_path', action='store_true', help='dont generate a subfolder for log') parser.add_argument('--resolution', default=1024, type=int, help='Resolution used for rendering images(default: 1024)') parser.add_argument('--trackVQLoss', action='store_true', help='track loss in View Quality for the training set, slower.(default:False)') parser.add_argument('--cosineLoss', action='store_false', help='Use the cosine distance instead of MSE.(default: True)') parser.add_argument('--VQ', default='4,5,7,8', help='View Quality measure used') parser.add_argument('--label_threshold', default = 0.01, type=float) parser.add_argument('--normFactor', default = 0.0, type = float) parser.add_argument('--useBRN', action = 'store_true') parser.add_argument('--initBNMom', default = 0.5, type=float) parser.add_argument('--affix', default = '') parser.add_argument('--no_categories',action='store_false') parser.add_argument('--maxNumPts', default = 1024, type = int) parser.add_argument('--cates', default = None) parser.add_argument('--rotation_axis', default ='012', help = 'axis aroung which to augment, string (default: 2 (z axis))') parser.add_argument('--smallrotations', action = 'store_true', help = 'use small rotations') parser.add_argument('--pts_source', default = 'pts_unif_own', help= 'name of folder containing the point clouds') parser.add_argument('--useNormals', action = 'store_true', help = 'use normals as input features') parser.add_argument('--tta', action = 'store_true', help = 'use test time augmentation') args = parser.parse_args() #if args.VQ == '4,5,7,8': args.no_categories = False folders = args.folders.split(',') if not os.path.exists(args.logFolder): os.mkdir(args.logFolder) if not args.fix_path: args.logFolder = logfolder_name(args) VQ = args.VQ.split(',') if args.cates != None: args.cates = args.cates.split(',') if 'UV' in VQ: uv_ind = VQ.index('UV') numVQs = len(VQ) if not args.augment: augments_per_epoch = 2 else: augments_per_epoch = 10 #Create log folder. if not os.path.exists(args.logFolder): os.mkdir(args.logFolder) #os.system('cp models/%s.py %s' % (args.model, args.logFolder)) #os.system('cp train_with_sigmoid.py %s' % (args.logFolder)) logFile = args.logFolder+"/log.txt" #Create Folder for results resultFolder = args.logFolder + '/results_val' if not os.path.exists(resultFolder): os.mkdir(resultFolder) with open(resultFolder + '/VQs.txt','w') as outFile: for vq in VQ: outFile.write(vq+'\n') #Write execution info. with open(logFile, "a") as myFile: myFile.write("Model: "+args.model+"\n") myFile.write("Grow: "+str(args.grow)+"\n") myFile.write("VQ: "+ str(VQ) +"\n") myFile.write("BatchSize: "+str(args.batchSize)+"\n") myFile.write("MaxEpoch: "+str(args.maxEpoch)+"\n") myFile.write("WeightDecay: "+str(args.weightDecay)+"\n") myFile.write("InitLearningRate: "+str(args.initLearningRate)+"\n") myFile.write("LearningDecayFactor: "+str(args.learningDecayFactor)+"\n") myFile.write("LearningDecayRate: "+str(args.learningDecayRate)+"\n") myFile.write("MinLearningRate: "+str(args.minLearningRate)+"\n") myFile.write("UseDropOut: "+str(args.useDropOut)+"\n") myFile.write("DropOutKeepProb: "+str(args.dropOutKeepProb)+"\n") myFile.write("UseDropOutConv: "+str(args.useDropOutConv)+"\n") myFile.write("DropOutKeepProbConv: "+str(args.dropOutKeepProbConv)+"\n") myFile.write('Resolution: '+str(args.resolution)+'\n') myFile.write("Augment: "+str(args.augment)+"\n") myFile.write("Noise: "+str(args.noise)+"\n") print("Model: "+args.model) print("Grow: "+str(args.grow)) print("VQs: "+ str(VQ)) print("BatchSize: "+str(args.batchSize)) print("MaxEpoch: "+str(args.maxEpoch)) print("WeightDecay: "+str(args.weightDecay)) print("InitLearningRate: "+str(args.initLearningRate)) print("LearningDecayFactor: "+str(args.learningDecayFactor)) print("LearningDecayRate: "+str(args.learningDecayRate)) print("minLearningRate: "+str(args.minLearningRate)) print("UseDropOut: "+str(args.useDropOut)) print("DropOutKeepProb: "+str(args.dropOutKeepProb)) print("UseDropOutConv: "+str(args.useDropOutConv)) print("DropOutKeepProbConv: "+str(args.dropOutKeepProbConv)) print('Resolution: '+str(args.resolution)) print("Augment: "+str(args.augment)) print("Noise: "+str(args.noise)) #Load the model model = importlib.import_module(args.model) #Get train and test datasets maxStoredPoints = args.maxNumPts mTrainDataSet = VQDataSet('train', maxStoredPoints, args.batchSize, args.augment, args.noise, VQs = VQ, folders = folders, label_threshold = args.label_threshold, filter_categories=args.no_categories, categories = args.cates, pts_source= args.pts_source, aug_sym = args.symmetric_deformations, rotation_axis=args.rotation_axis, smallrotations=args.smallrotations) mValDataSet = VQDataSet('val', maxStoredPoints, args.batchSize, args.augment, VQs=VQ, folders = folders,filter_categories=args.no_categories, categories = args.cates, pts_source = args.pts_source, rotation_axis=args.rotation_axis, smallrotations=args.smallrotations) mTestDataSet = VQDataSet('test', maxStoredPoints, args.batchSize, args.augment, VQs=VQ, folders = folders,filter_categories=args.no_categories, categories = args.cates, pts_source = args.pts_source, rotation_axis=args.rotation_axis, smallrotations=args.smallrotations) numTrainModels = mTrainDataSet.get_num_models() numBatchesXEpoch = numTrainModels/args.batchSize if numTrainModels%args.batchSize != 0: numBatchesXEpoch = numBatchesXEpoch + 1 numValModels = mValDataSet.get_num_models() numTestModels = mTestDataSet.get_num_models() print("Train models: " + str(numTrainModels)) print("Val models: " + str(numValModels)) #Create variable and place holders global_step = tf.Variable(0, name='global_step', trainable=False) inPts = tf.placeholder(tf.float32,[None,3], name='Points') inFeatures = tf.placeholder(tf.float32,[None,1], name = 'Features') inBatchIds = tf.placeholder(tf.int32, [None,1], name = 'Batchids') inPtHier_tf = [inPts, inFeatures, inBatchIds] isTraining = tf.placeholder(tf.bool, shape=(), name = 'isTraining') keepProbConv = tf.placeholder(tf.float32, name= 'keepProbConv') keepProbFull = tf.placeholder(tf.float32, name = 'keepProbFull') inVQLoss = tf.placeholder(tf.float32, [numVQs], name = 'VQLoss') inImages = tf.placeholder(tf.float32, [numVQs, None, 32,32], name = 'VQImages') inRefViews = tf.placeholder(tf.float32, [1024,3], name = 'refViews') #Create the network useRenorm = args.useBRN BNMomentum = BN_decay(args.initBNMom, global_step, numBatchesXEpoch, 0.9) pred_images = model.create_network(inPts, inFeatures, inBatchIds, args.batchSize, 1, args.grow, 3, numVQs, isTraining, keepProbConv, keepProbFull, args.useDropOutConv, args.useDropOut, useRenorm, BNMomentum) #Create Loss lossGraph, pred_views_norm, loss, pred_views_ids = create_loss_mult_tf(pred_images, numVQs, inImages, inRefViews) #Create training trainning, learningRateExp = create_training(lossGraph, args.initLearningRate, args.minLearningRate, args.learningDecayFactor, args.learningDecayRate*numBatchesXEpoch, global_step) #Create loss metrics accumLoss, accumVQLoss, accumTrain, accumTest, accumVQLossOp = create_loss_metrics_mult(loss, inVQLoss, numVQs) metricsVars = tf.contrib.framework.get_variables('metrics', collection=tf.GraphKeys.LOCAL_VARIABLES) resetMetrics = tf.variables_initializer(metricsVars) #Create Summaries trainingSummary, testSummary, accumLoss, accumVQLoss = create_summaries(accumLoss, accumVQLoss, VQ, numVQs) #Create init variables init = tf.global_variables_initializer() initLocal = tf.local_variables_initializer() #create the saver saver = tf.train.Saver() #Create session gpu_options = tf.GPUOptions(allow_growth=True, visible_device_list=args.gpu) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) #from tensorflow.python import debug as tf_debug #sess = tf_debug.LocalCLIDebugWrapperSession(sess) #Create the summary writer summary_writer = tf.summary.FileWriter(args.logFolder, sess.graph) summary_writer.add_graph(sess.graph) #Init variables sess.run(init, {isTraining: True}) sess.run(initLocal, {isTraining: True}) np.random.seed(int(time.time())) TestLossList = [] if args.restore == True: loader = tf.train.import_meta_graph(args.logFolder+"/model.ckpt.meta") loader.restore(sess, args.logFolder+"/model.ckpt") #TestLossList = list(np.genfromtxt(resultFolder+'/TestLoss.txt', delimiter = ',').reshape(-1,numVQs)) #mTrainDataSet.ptHIndex_ = int(np.genfromtxt(args.logFolder+'/ptH_log', delimiter = ',')) #MyGL = GLScene(args.resolution, args.resolution) #Train size = 32 longitude = np.linspace(0,2*np.pi,size) latitude = np.linspace(-np.pi/2,np.pi/2,size) X, Y = np.meshgrid(longitude, latitude) x = np.reshape(np.cos(Y) * np.cos(X), [1024]) y = np.reshape(np.cos(Y) * np.sin(X), [1024]) z = np.reshape(np.sin(Y), [1024]) refViews_np = np.stack((x,y,z), axis=1) print(''); print('########## Training'); print('') for epoch in range(args.maxEpoch): startEpochTime = current_milli_time() startTrainTime = current_milli_time() PtHier = [] epochStep = 0 lossInfoCounter = 0 visStep = 0 lossAccumValue = 0.0 lossTotal = 0.0 distance = 0.0 distanceAccumValue = 0.0 distanceTotal = 0.0 processedModels = 0 #Iterate over all the train files mTrainDataSet.start_iteration() while mTrainDataSet.has_more_batches(): currbatchSize, pts, features, batchIds, modelList, referenceValuesList, images, vqs3D, invRotationMatrix = mTrainDataSet.get_next_batch() processedModels += currbatchSize feed_dict = create_feed_dict_gauss(inPtHier_tf, [pts, features, batchIds], keepProbConv, args.dropOutKeepProbConv, keepProbFull, args.dropOutKeepProb) feed_dict[isTraining] = True feed_dict[inImages] = images feed_dict[inRefViews] = refViews_np Pred_views, Pred_views_ids, _, _, step = sess.run([pred_views_norm, pred_views_ids, trainning, accumTrain, global_step], feed_dict) #print(Pred_views[0,0:3]) if args.trackVQLoss: if args.augment: for i in range(len(Pred_views)): for vq_i in range(numVQs): ind = range(vq_i*3, (vq_i+1)*3) Pred_views[i,ind] = np.dot(Pred_views[i,ind].reshape(1,3),invRotationMatrix[i]) Loss = [[] for i in range(numVQs)] for i in range(numVQs): for j in range(currbatchSize): pred_vq = images[i][j].reshape(1024)[Pred_views_ids[i][j]] Loss[i].append(1-pred_vq) Loss[i] = np.mean(Loss[i]) lossAccumValue += np.mean(Loss) sess.run(accumVQLossOp, {inVQLoss : Loss}) lossTotal += np.mean(Loss) lossInfoCounter += 1 if lossInfoCounter == 1000/args.batchSize or not mTrainDataSet.has_more_batches(): prediction, Pred_views_ids = sess.run([pred_images[0], pred_views_ids[0]], feed_dict) fig = plt.figure(figsize=[10,5]) ax=plt.subplot(121) im=plt.imshow(prediction[0]) plt.colorbar(im, ax=ax) ax=plt.subplot(122) im=plt.imshow(images[0][0]) plt.colorbar(im, ax=ax) plt.savefig('pred.png') Pred_vq = images[0][0].reshape(1024)[Pred_views_ids[0]] endTrainTime = current_milli_time() trainingSumm, distanceAccumValue = sess.run([trainingSummary, accumLoss]) summary_writer.add_summary(trainingSumm, step) summary_writer.flush() sess.run(resetMetrics) if args.trackVQLoss: visualize_progress(min(epochStep, numBatchesXEpoch), numBatchesXEpoch, "Distance: %.6f | VQLoss: %.6f | Time: %4ds " %(distanceAccumValue, lossAccumValue/float(lossInfoCounter), (endTrainTime-startTrainTime)/1000.0)) else: visualize_progress(min(epochStep, numBatchesXEpoch), numBatchesXEpoch, "Dist Loss: %.6f | Time: %2ds " %(distanceAccumValue, (endTrainTime-startTrainTime)/1000.0)) with open(logFile, "a") as myfile: if args.trackVQLoss: myfile.write("Step: %6d (%4d) | Distance: %.6f | VQLoss: %.6f\n" % (step, epochStep, distanceAccumValue, lossAccumValue/float(lossInfoCounter))) else: myfile.write("Step: %6d (%4d) | Distance: %.6f \n" % (step, epochStep, distanceAccumValue)) distanceTotal += distanceAccumValue * processedModels processedModels = 0 lossInfoCounter = 0 lossAccumValue = 0.0 startTrainTime = current_milli_time() visStep += 1 epochStep += 1 distanceTotal = distanceTotal/numTrainModels lossTotal = lossTotal/epochStep endEpochTime = current_milli_time() if args.trackVQLoss: print("Epoch %3d Train Time: %.2fs | Train Distance: %.6f | Train VQ-Loss: %.6f" %(epoch, (endEpochTime-startEpochTime)/1000.0, distanceTotal, lossTotal)) else: print("Epoch %3d Train Time: %.2fs | Dist: %.6f" %(epoch, (endEpochTime-startEpochTime)/1000.0, distanceTotal)) with open(logFile, "a") as myfile: if args.trackVQLoss: myfile.write("Epoch %3d Train Time: %.2fs | Train Distance: %.6f | Train VQ-Loss: %.6f\n" %(epoch, (endEpochTime-startEpochTime)/1000.0, distanceTotal, lossTotal)) else: myfile.write("Epoch %3d Train Time: %.2fs |Distance: %.6f\n" %(epoch, (endEpochTime-startEpochTime)/1000.0, distanceTotal)) if epoch%augments_per_epoch==0: if epoch %50==0: saver.save(sess, args.logFolder+"/model.ckpt") startTestTime = current_milli_time() #Test data accumTestLoss = 0.0 TestModels = [] it = 0 mValDataSet.start_iteration() while mValDataSet.has_more_batches(): currbatchSize, pts, features, batchIds, modelList, referenceValuesList, images, vqs3D, invRotationMatrix = mValDataSet.get_next_batch() feed_dict = create_feed_dict_gauss(inPtHier_tf, [pts, features, batchIds], keepProbConv, 1.0, keepProbFull, 1.0) feed_dict[isTraining] = False feed_dict[inImages] = images feed_dict[inRefViews] = refViews_np Pred_views, Pred_views_ids, _= sess.run([pred_views_norm, pred_views_ids, accumTest], feed_dict) if args.augment: for i in range(len(Pred_views)): for vq_i in range(numVQs): ind = range(vq_i*3, (vq_i+1)*3) Pred_views[i,ind] = np.dot(Pred_views[i,ind].reshape(1,3),invRotationMatrix[i]) Loss = [[] for i in range(numVQs)] for i in range(numVQs): for j in range(currbatchSize): pred_vq = images[i][j].reshape(1024)[Pred_views_ids[i][j]] Loss[i].append(1-pred_vq) Loss[i] = np.mean(Loss[i]) sess.run(accumVQLossOp, {inVQLoss : Loss}) accumTestLoss += np.array(Loss) if it%(400/args.batchSize) == 0 or not mValDataSet.has_more_batches(): visualize_progress(it, numValModels/currbatchSize) it += 1 TestSumm, accumTestDistance = sess.run([testSummary, accumLoss]) summary_writer.add_summary(TestSumm, step) summary_writer.flush() sess.run(resetMetrics) accumTestLoss = accumTestLoss/numValModels TestLossList.append(accumTestLoss) endTestTime = current_milli_time() print("Val Time: %.2fs | VQ-Loss: %.6f | Dist: %.6f" % ((endTestTime-startTestTime)/1000.0, np.mean(accumTestLoss), accumTestDistance)) # after training save Val results if not args.no_eval: #print(''); print('########## Evaluation'); print('') #startTestTime = current_milli_time() ##Test data #accumTestLoss = 0.0 #TestModels = [] #TestLoss = [[] for vqi in range(numVQs)] #TestViews = [[] for vqi in range(numVQs)] #TestRotations=[] #it = 0 #mValDataSet.start_iteration() #mValDataSet.batchSize_ = 1 #while mValDataSet.has_more_batches(): #currbatchSize, pts, features, batchIds, modelList, referenceValuesList, invRotationMatrix, RotationMatrix, vqs3D, ptSpheres = mValDataSet.get_next_batch() #feed_dict = create_feed_dict_gauss(inPtHier_tf, [pts, features, batchIds], keepProbConv, 1.0, keepProbFull, 1.0) #feed_dict[isTraining] = False #feed_dict[inSpheres] = ptSpheres #feed_dict[inVQs3d] = vqs3D #Pred_views, _= sess.run([pred_views_norm, accumTest], feed_dict) #Pred_views, _= sess.run([pred_views_norm, accumTest], feed_dict) #TestModels.append(modelList[0]) #TestRotations.append(RotationMatrix[0]) #if args.augment: #for i in range(len(Pred_views)): #for vq_i in range(numVQs): #ind = range(vq_i*3, (vq_i+1)*3) #Pred_views[i,ind] = np.dot(Pred_views[i,ind].reshape(1,3),invRotationMatrix[i]) #TestViews[vq_i].append(Pred_views[:,ind][i]) #Loss = create_mult_loss_approx(Pred_views, modelList, vqs3D, currbatchSize, VQ, unif_pts) ##Loss = 0 #sess.run(accumVQLossOp, {inVQLoss : Loss}) #accumTestLoss += np.mean(Loss)*currbatchSize #for vq_i in range(numVQs): #TestLoss[vq_i].append(Loss[vq_i]) #if it%(400/args.batchSize) == 0 or not mValDataSet.has_more_batches(): #visualize_progress(it, numValModels/currbatchSize) #it += 1 #TestSumm, accumTestDistance = sess.run([testSummary, accumLoss]) #accumTestLoss = accumTestLoss/numValModels #TestLossList.append(accumTestLoss) #endTestTime = current_milli_time() #print("Val Time: %.2fs | VQ-Loss: %.6f | Dist: %.6f" % ((endTestTime-startTestTime)/1000.0, np.mean(accumTestLoss), accumTestDistance)) #with open(resultFolder+'/TestDistRes.txt', "w") as myfile: #myfile.write(str(accumTestDistance) + '\n') #with open(resultFolder+'/TestLoss.txt', "w") as myfile: #myfile.write(np.array2string(np.mean(TestLoss,axis=1),precision=2)[1:-1] + '\n') #for vq_i, vq in enumerate(VQ): #np.savetxt(resultFolder+'/Loss_VQ'+vq +'.txt', TestLoss[vq_i], delimiter = ',', fmt = '%s') ##np.savetxt(resultFolder+'/VQ'+vq +'.txt', TestVQ[vq_i], delimiter = ',', fmt = '%s') ##np.savetxt(resultFolder+'/Distance.txt', TestDistance, delimiter = ',', fmt = '%s') #np.savetxt(resultFolder+'/Models.txt', TestModels, delimiter = ',', fmt = '%s') ##np.savetxt(resultFolder+'/Result_VQ'+vq +'.txt', ResultTest[vq_i], delimiter = ',', fmt = '%s') #np.savetxt(resultFolder+'/Views_VQ'+vq +'.txt', TestViews[vq_i], delimiter = ',', fmt = '%s') #np.savetxt(resultFolder+'/Rotations.txt',np.array(TestRotations).reshape(-1,9), delimiter=',', fmt='%s') sess.run(resetMetrics) print(''); print('########## Testing'); print('') resultFolder = args.logFolder + '/results_test' + args.tta*'_tta' if args.pts_source != 'pts_unif_own': resultFolder += '_' + args.pts_source if args.folders != 'ModelNet40_simplified': resultFolder += '_' + args.folders if not os.path.exists(resultFolder): os.mkdir(resultFolder) with open(resultFolder + '/VQs.txt','w') as outFile: for vq in VQ: outFile.write(vq+'\n') startTestTime = current_milli_time() #Test data accumTestLoss = 0.0 TestModels = [] TestLoss = [[] for vqi in range(numVQs)] TestViews = [[] for vqi in range(numVQs)] TestRotations=[] it = 0 mTestDataSet.start_iteration() if args.tta: mTestDataSet.batchSize_ = args.batchSize else: mTestDataSet.batchSize_ = 1 while mTestDataSet.has_more_batches(): currbatchSize, pts, features, batchIds, modelList, referenceValuesList, images, vqs3D, invRotationMatrix = mTestDataSet.get_next_batch() feed_dict = create_feed_dict_gauss(inPtHier_tf, [pts, features, batchIds], keepProbConv, 1.0, keepProbFull, 1.0) feed_dict[isTraining] = False feed_dict[inImages] = images feed_dict[inRefViews] = refViews_np Pred_views, _= sess.run([pred_views_norm, accumTest], feed_dict) Pred_views, _= sess.run([pred_views_norm, accumTest], feed_dict) TestModels.append(modelList[0]) # if args.augment: # TestRotations += RotationMatrix for vq_i in range(numVQs): for i in range(len(Pred_views)): ind = range(vq_i*3, (vq_i+1)*3) if args.augment: Pred_views[i,ind] = np.dot(Pred_views[i,ind].reshape(1,3),invRotationMatrix[i]) TestViews[vq_i].append(Pred_views[:,ind][i]) Loss = [[] for i in range(numVQs)] for i in range(numVQs): for j in range(currbatchSize): pred_vq = images[i][j].reshape(1024)[Pred_views_ids[i][j]] Loss[i].append(1-pred_vq) Loss[i] = np.mean(Loss[i]) sess.run(accumVQLossOp, {inVQLoss : Loss}) accumTestLoss += np.mean(Loss) for vq_i in range(numVQs): TestLoss[vq_i].append(Loss[vq_i]) if it%(400/args.batchSize) == 0 or not mTestDataSet.has_more_batches(): visualize_progress(it, numTestModels) it += 1 TestSumm, accumTestDistance = sess.run([testSummary, accumLoss]) accumTestLoss = accumTestLoss/numTestModels TestLossList.append(accumTestLoss) endTestTime = current_milli_time() print("Test Time: %.2fs | VQ-Loss: %.6f | Dist: %.6f" % ((endTestTime-startTestTime)/1000.0, np.mean(accumTestLoss), accumTestDistance)) with open(resultFolder+'/TestDistRes.txt', "w") as myfile: myfile.write(str(accumTestDistance) + '\n') with open(resultFolder+'/TestLoss.txt', "w") as myfile: myfile.write(np.array2string(np.mean(TestLoss,axis=1),precision=2)[1:-1] + '\n') for vq_i, vq in enumerate(VQ): np.savetxt(resultFolder+'/Loss_VQ'+vq +'.txt', TestLoss[vq_i], delimiter = ',', fmt = '%s') #np.savetxt(resultFolder+'/VQ'+vq +'.txt', TestVQ[vq_i], delimiter = ',', fmt = '%s') #np.savetxt(resultFolder+'/Distance.txt', TestDistance, delimiter = ',', fmt = '%s') np.savetxt(resultFolder+'/Models.txt', TestModels, delimiter = ',', fmt = '%s') #np.savetxt(resultFolder+'/Result_VQ'+vq +'.txt', ResultTest[vq_i], delimiter = ',', fmt = '%s') np.savetxt(resultFolder+'/Views_VQ'+vq +'.txt', TestViews[vq_i], delimiter = ',', fmt = '%s') # if args.augment: # np.savetxt(resultFolder+'/Rotations.txt',np.array(TestRotations).reshape(-1,9), delimiter=',', fmt='%s') print('[done]') with open(logFile, "a") as myfile: myfile.write('[done]')
[]
[]
[ "TF_CPP_MIN_LOG_LEVEL" ]
[]
["TF_CPP_MIN_LOG_LEVEL"]
python
1
0
ResultDisplay/activity.go
package sample import ( "encoding/json" "fmt" "image" "image/color" "os" "strings" "github.com/project-flogo/core/activity" "gocv.io/x/gocv" // "github.com/project-flogo/core/data/metadata" // "reflect" ) var ( activityMd = activity.ToMetadata(&Input{}) textColor = color.RGBA{0, 255, 0, 0} pt = image.Pt(20, 20) left, top, right, bottom int frameIndex = 0 width, height = 0, 0 windowDispaly = gocv.NewWindow("EdgeWare - Dispaly") lastDemoID = -1 demoID = 1 // demoID, _ = strconv.Atoi(os.Getenv("DEMOID")) // gender string // window = gocv.NewWindow("Gender") // textColor = color.RGBA{0, 255, 0, 0} // pt = image.Pt(20, 20) // left, top, right, bottom int ) // https://gobyexample.com/json //bounding box by form of x1,y1,x2,y2 type Bbox struct { Boxid int `json:"boxid"` X1 int `json:"x1"` Y1 int `json:"y1"` X2 int `json:"x2"` Y2 int `json:"y2"` } //json format of person recognition type imgJson struct { Imgid int `json:"imgid"` Imgpath string `json:"imgpath"` Bboxes []Bbox `json:"bboxes"` DemoID int `json:"demoid"` } type imgJsonR struct { ImgJson imgJson `json:"imgjson"` Result []string `json:"result"` } var ( lastImgJsonR = imgJsonR{} curImgJsonR = imgJsonR{} ifDisplay = false ) func init() { _ = activity.Register(&Activity{}) //activity.Register(&Activity{}, New) to create instances using factory method 'New' } //New optional factory method, should be used if one activity instance per configuration is desired func New(ctx activity.InitContext) (activity.Activity, error) { act := &Activity{} //add aSetting to instance return act, nil } // Activity is an sample Activity that can be used as a base to create a custom activity type Activity struct { } // Metadata returns the activity's metadata func (a *Activity) Metadata() *activity.Metadata { return activityMd } // Eval implements api.Activity.Eval - Logs the Message func (a *Activity) Eval(ctx activity.Context) (done bool, err error) { input := &Input{} err = ctx.GetInputObject(input) if err != nil { return true, err } //recognition done here, dummy now // ************************* // fmt.Printf("Input serial: %s\n", input.Serial) imgjsonS := input.DisplayJson imgjsonS = strings.Replace(imgjsonS, "\\\"", "\"", -1) // fmt.Printf("\n %c[%d;%d;%dmInput serial: %s%c[0m\n", 0x1B, 0, 0, 31, imgjsonS, 0x1B) // imgName := "tmpAge.jpg" // imgName := input.Serial fmt.Printf("\n %c[%d;%d;%dmResult: %s%c[0m\n", 0x1B, 0, 0, 33, imgjsonS, 0x1B) imgjson := imgJsonR{} json.Unmarshal([]byte(imgjsonS), &imgjson) curImgJsonR = imgjson // fmt.Println(imgjson) demoID = imgjson.ImgJson.DemoID if demoID != lastDemoID { lastDemoID = demoID } if demoID > 1 { if curImgJsonR.ImgJson.Imgid == lastImgJsonR.ImgJson.Imgid { ifDisplay = true } else { ifDisplay = false } if ifDisplay { framePath := curImgJsonR.ImgJson.Imgpath if exists(framePath) { for faceIndex := 0; faceIndex < len(curImgJsonR.ImgJson.Bboxes); faceIndex++ { img := gocv.IMRead(framePath, gocv.IMReadColor) if frameIndex == 0 { dims := img.Size() fmt.Println(dims) width, height = dims[1], dims[0] } left := curImgJsonR.ImgJson.Bboxes[faceIndex].X1 top := curImgJsonR.ImgJson.Bboxes[faceIndex].Y1 right := curImgJsonR.ImgJson.Bboxes[faceIndex].X2 bottom := curImgJsonR.ImgJson.Bboxes[faceIndex].Y2 left -= 20 top -= 60 right += 20 bottom += 20 if left < 0 { left = 0 } if top < 0 { top = 0 } if right > width { right = width } if bottom > height { bottom = height } rect := image.Rect(left, top, right, bottom) imgFace := img.Region(rect) age, gender := curImgJsonR.Result[faceIndex], lastImgJsonR.Result[faceIndex] if age == "male" || age == "female" { age, gender = gender, age } gocv.PutText(&imgFace, gender+", "+age, pt, gocv.FontHersheyPlain, 1.2, textColor, 2) windowDispaly.IMShow(imgFace) windowDispaly.WaitKey(30) } frameIndex++ } } // ******************************* lastImgJsonR = curImgJsonR } else { ifDisplay = true if ifDisplay { framePath := curImgJsonR.ImgJson.Imgpath if exists(framePath) { for faceIndex := 0; faceIndex < len(curImgJsonR.ImgJson.Bboxes); faceIndex++ { img := gocv.IMRead(framePath, gocv.IMReadColor) if frameIndex == 0 { dims := img.Size() fmt.Println(dims) width, height = dims[1], dims[0] } left := curImgJsonR.ImgJson.Bboxes[faceIndex].X1 top := curImgJsonR.ImgJson.Bboxes[faceIndex].Y1 right := curImgJsonR.ImgJson.Bboxes[faceIndex].X2 bottom := curImgJsonR.ImgJson.Bboxes[faceIndex].Y2 left -= 20 top -= 60 right += 20 bottom += 20 if left < 0 { left = 0 } if top < 0 { top = 0 } if right > width { right = width } if bottom > height { bottom = height } rect := image.Rect(left, top, right, bottom) imgFace := img.Region(rect) gender := curImgJsonR.Result[faceIndex] gocv.PutText(&imgFace, gender, pt, gocv.FontHersheyPlain, 1.2, textColor, 2) windowDispaly.IMShow(imgFace) windowDispaly.WaitKey(30) } frameIndex++ } } // ******************************* // lastImgJsonR = curImgJsonR } ctx.Logger().Debugf("Input serial: %s", input.DisplayJson) // ctx.Logger().Debugf("Age: %s", age) return true, nil } func checkErr(err error) { if err != nil { panic(err) } } // determine if the file/folder of the given path exists func exists(path string) bool { _, err := os.Stat(path) //os.Stat get the file information if err != nil { if os.IsExist(err) { return true } return false } return true }
[ "\"DEMOID\"" ]
[]
[ "DEMOID" ]
[]
["DEMOID"]
go
1
0
mask r-cnn/evaluation.py
""" # Train a new model starting from pre-trained weights python3 training.py --dataset=/path/to/dataset --weight=/path/to/pretrained/weight.h5 # Resume training a model python3 training.py --dataset=/path/to/dataset --continue_train=/path/to/latest/weights.h5 """ import logging import warnings import os logging.getLogger("tensorflow").setLevel(logging.ERROR) warnings.filterwarnings('ignore') os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import sys import json import datetime import numpy as np import skimage.draw import cv2 import matplotlib.pyplot as plt import imgaug # Root directory of the project ROOT_DIR = os.getcwd() from mrcnn.config import Config from mrcnn import model as modellib, utils from mrcnn import parse_args import dataset ############################################################ # Args Configurations ############################################################ args = parse_args.parse_args() # config parameter pretrained_weight = os.path.join(ROOT_DIR, args.weight) dataset_path = os.path.join(ROOT_DIR, args.dataset) logs = os.path.join(ROOT_DIR, "logs") if args.continue_train == "None": continue_train = args.continue_train else: continue_train = os.path.join(ROOT_DIR, args.continue_train) ############################################################ # Configurations ############################################################ class CustomConfig(Config): NAME = "custom_dataset" IMAGES_PER_GPU = 1 IMAGE_MAX_DIM = 512 NUM_CLASSES = 1 + 4 STEPS_PER_EPOCH = 750 VALIDATION_STEPS = 250 DETECTION_MIN_CONFIDENCE = 0.9 LEARNING_RATE = 0.001 DETECTION_NMS_THRESHOLD = 0.2 TRAIN_ROIS_PER_IMAGE = 200 MAX_GT_INSTANCES = 50 DETECTION_MAX_INSTANCES = 50 ############################################################ # Training ############################################################ def train(model): # Training set. dataset_train = dataset.CustomDataset() dataset_train.load_custom(dataset_path, "train") dataset_train.prepare() print("Images: {}\nClasses: {}".format(len(dataset_train.image_ids), dataset_train.class_names)) # Validation set dataset_val = dataset.CustomDataset() dataset_val.load_custom(dataset_path, "val") dataset_val.prepare() print("Images: {}\nClasses: {}".format(len(dataset_val.image_ids), dataset_val.class_names)) augmentation = imgaug.augmenters.Sometimes(0.5, [ imgaug.augmenters.Fliplr(0.5), imgaug.augmenters.Flipud(0.5)]) model_inference = modellib.MaskRCNN(mode="inference", config=config,model_dir=logs) #calculating COCO-mAP after every 5 epoch, limited to the first 1000 images mAP_callback = modellib.MeanAveragePrecisionCallback(model, model_inference, dataset_val, calculate_at_every_X_epoch=5, dataset_limit=1000, verbose=1) # Training - Stage 1 print("Training network heads") model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE, epochs=20, layers='heads', custom_callbacks=[mAP_callback], augmentation=augmentation) # print("Fine tune Resnet stage 4 and up") # model.train(dataset_train, dataset_val, # learning_rate=config.LEARNING_RATE, # epochs=60, # layers='4+', # custom_callbacks=[mAP_callback], # augmentation=augmentation) # print("Fine tune Resnet stage 3 and up") # model.train(dataset_train, dataset_val, # learning_rate=config.LEARNING_RATE/10, # epochs=90, # layers='3+', # custom_callbacks=[mAP_callback], # augmentation=augmentation) # print("Fine tune all layers") # model.train(dataset_train, dataset_val, # learning_rate=config.LEARNING_RATE/100, # epochs=100, # layers='all', # custom_callbacks=[mAP_callback]) # # augmentation=augmentation) ############################################################ # Main ############################################################ if __name__ == '__main__': print("Pre-trained weight: ", pretrained_weight) print("Dataset: ", dataset_path) print("Logs: ", logs) print("Continue Train: ", continue_train) # Configurations config = CustomConfig() config.display() # Create model model = modellib.MaskRCNN(mode="training", config=config, model_dir=logs) if continue_train.lower() == "none": weights_path = pretrained_weight else: weights_path = continue_train # Load weights print("Loading weights ", weights_path) if continue_train == "None": # Exclude the last layers because they require a matching # number of classes model.load_weights(weights_path, by_name=True, exclude=[ "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask"]) else: model.load_weights(weights_path, by_name=True) train(model)
[]
[]
[ "TF_CPP_MIN_LOG_LEVEL" ]
[]
["TF_CPP_MIN_LOG_LEVEL"]
python
1
0
tests/integration/local/invoke/test_integrations_cli.py
import json import shutil import os import copy import tempfile from unittest import skipIf from parameterized import parameterized from subprocess import Popen, PIPE, TimeoutExpired from timeit import default_timer as timer import pytest import docker from tests.integration.local.invoke.layer_utils import LayerUtils from .invoke_integ_base import InvokeIntegBase from tests.testing_utils import IS_WINDOWS, RUNNING_ON_CI, RUNNING_TEST_FOR_MASTER_ON_CI, RUN_BY_CANARY # Layers tests require credentials and Appveyor will only add credentials to the env if the PR is from the same repo. # This is to restrict layers tests to run outside of Appveyor, when the branch is not master and tests are not run by Canary. SKIP_LAYERS_TESTS = RUNNING_ON_CI and RUNNING_TEST_FOR_MASTER_ON_CI and not RUN_BY_CANARY from pathlib import Path TIMEOUT = 300 class TestSamPython36HelloWorldIntegration(InvokeIntegBase): template = Path("template.yml") @pytest.mark.flaky(reruns=3) def test_invoke_returncode_is_zero(self): command_list = self.get_command_list( "HelloWorldServerlessFunction", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE) try: process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise self.assertEqual(process.returncode, 0) @pytest.mark.flaky(reruns=3) def test_function_with_metadata(self): command_list = self.get_command_list("FunctionWithMetadata", template_path=self.template_path, no_event=True) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"Hello World in a different dir"') @parameterized.expand( [ ("MyReallyCoolFunction",), ("HelloWorldServerlessFunction",), ("HelloWorldServerlessWithFunctionNameRefFunction",), ] ) @pytest.mark.flaky(reruns=3) def test_invoke_returns_execpted_results(self, function_name): command_list = self.get_command_list( function_name, template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"Hello world"') @pytest.mark.flaky(reruns=3) def test_invoke_of_lambda_function(self): command_list = self.get_command_list( "HelloWorldLambdaFunction", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"Hello world"') @pytest.mark.flaky(reruns=3) def test_invoke_of_lambda_function_with_function_name_override(self): command_list = self.get_command_list( "func-name-override", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"Hello world"') @parameterized.expand( [("TimeoutFunction"), ("TimeoutFunctionWithParameter"), ("TimeoutFunctionWithStringParameter")] ) @pytest.mark.flaky(reruns=3) def test_invoke_with_timeout_set(self, function_name): command_list = self.get_command_list( function_name, template_path=self.template_path, event_path=self.event_path ) start = timer() process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise end = timer() wall_clock_cli_duration = end - start process_stdout = stdout.strip() # validate the time of the cli (timeout is set to 5s) self.assertGreater(wall_clock_cli_duration, 5) self.assertLess(wall_clock_cli_duration, 20) self.assertEqual(process.returncode, 0) self.assertEqual( process_stdout.decode("utf-8"), "", msg="The return statement in the LambdaFunction " "should never return leading to an empty string", ) @pytest.mark.flaky(reruns=3) def test_invoke_with_env_vars(self): command_list = self.get_command_list( "EchoCustomEnvVarFunction", template_path=self.template_path, event_path=self.event_path, env_var_path=self.env_var_path, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"MyVar"') @parameterized.expand( [("EchoCustomEnvVarWithFunctionNameDefinedFunction"), ("customname"),] ) @pytest.mark.flaky(reruns=3) def test_invoke_with_env_vars_with_functionname_defined(self, function_name): command_list = self.get_command_list( function_name, template_path=self.template_path, event_path=self.event_path, env_var_path=self.env_var_path, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"MyVar"') @pytest.mark.flaky(reruns=3) def test_invoke_when_function_writes_stdout(self): command_list = self.get_command_list( "WriteToStdoutFunction", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE, stderr=PIPE) try: stdout, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() process_stderr = stderr.strip() self.assertIn("Docker Lambda is writing to stdout", process_stderr.decode("utf-8")) self.assertIn("wrote to stdout", process_stdout.decode("utf-8")) @pytest.mark.flaky(reruns=3) def test_invoke_when_function_writes_stderr(self): command_list = self.get_command_list( "WriteToStderrFunction", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stderr=PIPE) try: _, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stderr = stderr.strip() self.assertIn("Docker Lambda is writing to stderr", process_stderr.decode("utf-8")) @pytest.mark.flaky(reruns=3) def test_invoke_returns_expected_result_when_no_event_given(self): command_list = self.get_command_list("EchoEventFunction", template_path=self.template_path) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process.returncode, 0) self.assertEqual("{}", process_stdout.decode("utf-8")) @pytest.mark.flaky(reruns=3) def test_invoke_with_env_using_parameters(self): command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path, parameter_overrides={"MyRuntimeVersion": "v0", "DefaultTimeout": "100"}, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) self.assertEqual(environ["Region"], "us-east-1") self.assertEqual(environ["AccountId"], "123456789012") self.assertEqual(environ["Partition"], "aws") self.assertEqual(environ["StackName"], "local") self.assertEqual( environ["StackId"], "arn:aws:cloudformation:us-east-1:123456789012:stack/" "local/51af3dc0-da77-11e4-872e-1234567db123", ) self.assertEqual(environ["URLSuffix"], "localhost") self.assertEqual(environ["Timeout"], "100") self.assertEqual(environ["MyRuntimeVersion"], "v0") self.assertEqual(environ["EmptyDefaultParameter"], "") @pytest.mark.flaky(reruns=3) def test_invoke_with_env_using_parameters_with_custom_region(self): custom_region = "my-custom-region" command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path, region=custom_region ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) self.assertEqual(environ["Region"], custom_region) @pytest.mark.flaky(reruns=3) def test_invoke_with_env_with_aws_creds(self): custom_region = "my-custom-region" key = "key" secret = "secret" session = "session" command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path ) env = copy.deepcopy(dict(os.environ)) env["AWS_DEFAULT_REGION"] = custom_region env["AWS_REGION"] = custom_region env["AWS_ACCESS_KEY_ID"] = key env["AWS_SECRET_ACCESS_KEY"] = secret env["AWS_SESSION_TOKEN"] = session process = Popen(command_list, stdout=PIPE, env=env) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) self.assertEqual(environ["AWS_DEFAULT_REGION"], custom_region) self.assertEqual(environ["AWS_REGION"], custom_region) self.assertEqual(environ["AWS_ACCESS_KEY_ID"], key) self.assertEqual(environ["AWS_SECRET_ACCESS_KEY"], secret) self.assertEqual(environ["AWS_SESSION_TOKEN"], session) @pytest.mark.flaky(reruns=3) def test_invoke_with_docker_network_of_host(self): command_list = self.get_command_list( "HelloWorldServerlessFunction", template_path=self.template_path, event_path=self.event_path, docker_network="host", ) process = Popen(command_list, stdout=PIPE) try: process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise self.assertEqual(process.returncode, 0) @pytest.mark.flaky(reruns=3) @skipIf(IS_WINDOWS, "The test hangs on Windows due to trying to attach to a non-existing network") def test_invoke_with_docker_network_of_host_in_env_var(self): command_list = self.get_command_list( "HelloWorldServerlessFunction", template_path=self.template_path, event_path=self.event_path ) env = os.environ.copy() env["SAM_DOCKER_NETWORK"] = "non-existing-network" process = Popen(command_list, stderr=PIPE, env=env) try: _, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stderr = stderr.strip() self.assertIn('Not Found ("network non-existing-network not found")', process_stderr.decode("utf-8")) @pytest.mark.flaky(reruns=3) def test_sam_template_file_env_var_set(self): command_list = self.get_command_list("HelloWorldFunctionInNonDefaultTemplate", event_path=self.event_path) self.test_data_path.joinpath("invoke", "sam-template.yaml") env = os.environ.copy() env["SAM_TEMPLATE_FILE"] = str(self.test_data_path.joinpath("invoke", "sam-template.yaml")) process = Popen(command_list, stdout=PIPE, env=env) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"Hello world"') @pytest.mark.flaky(reruns=3) @pytest.mark.timeout(timeout=TIMEOUT, method="thread") def test_skip_pull_image_in_env_var(self): docker.from_env().api.pull("lambci/lambda:python3.6") command_list = self.get_command_list( "HelloWorldLambdaFunction", template_path=self.template_path, event_path=self.event_path ) env = os.environ.copy() env["SAM_SKIP_PULL_IMAGE"] = "True" process = Popen(command_list, stderr=PIPE, env=env) try: _, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stderr = stderr.strip() self.assertIn("Requested to skip pulling images", process_stderr.decode("utf-8")) @skipIf(SKIP_LAYERS_TESTS, "Skip layers tests in Appveyor only") @skipIf(IS_WINDOWS, "This test fails on windows due to unix permissions not set properly on unzipped binary") @pytest.mark.flaky(reruns=3) def test_invoke_returns_expected_results_from_git_function(self): command_list = self.get_command_list( "GitLayerFunction", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"git init passed"') @skipIf(SKIP_LAYERS_TESTS, "Skip layers tests in Appveyor only") @skipIf(IS_WINDOWS, "This test fails on windows due to unix permissions not set properly on unzipped binary") @pytest.mark.flaky(reruns=3) def test_invoke_returns_expected_results_from_git_function_with_parameters(self): command_list = self.get_command_list( "GitLayerFunctionParameters", template_path=self.template_path, event_path=self.event_path, parameter_overrides={"LayerVersion": "5"}, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"git init passed"') class TestSamInstrinsicsAndPlugins(InvokeIntegBase): template = "template-pseudo-params.yaml" @pytest.mark.flaky(reruns=3) def test_resolve_instrincs_which_runs_plugins(self): command_list = self.get_command_list( "HelloWorldServerlessFunction", template_path=self.template_path, event_path=self.event_path ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() # Returned result is dependent on region, but should not be None. self.assertIsNotNone(process_stdout.decode("utf-8"), "Invalid ApplicationId") class TestUsingConfigFiles(InvokeIntegBase): template = Path("template.yml") def setUp(self): self.config_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.config_dir, ignore_errors=True) @pytest.mark.flaky(reruns=3) def test_existing_env_variables_precedence_over_profiles(self): profile = "default" custom_config = self._create_config_file(profile) custom_cred = self._create_cred_file(profile) command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path ) env = os.environ.copy() # Explicitly set environment variables beforehand env["AWS_DEFAULT_REGION"] = "sa-east-1" env["AWS_REGION"] = "sa-east-1" env["AWS_ACCESS_KEY_ID"] = "priority_access_key_id" env["AWS_SECRET_ACCESS_KEY"] = "priority_secret_key_id" env["AWS_SESSION_TOKEN"] = "priority_secret_token" # Setup a custom profile env["AWS_CONFIG_FILE"] = custom_config env["AWS_SHARED_CREDENTIALS_FILE"] = custom_cred process = Popen(command_list, stdout=PIPE, env=env) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) # Environment variables we explicitly set take priority over profiles. self.assertEqual(environ["AWS_DEFAULT_REGION"], "sa-east-1") self.assertEqual(environ["AWS_REGION"], "sa-east-1") self.assertEqual(environ["AWS_ACCESS_KEY_ID"], "priority_access_key_id") self.assertEqual(environ["AWS_SECRET_ACCESS_KEY"], "priority_secret_key_id") self.assertEqual(environ["AWS_SESSION_TOKEN"], "priority_secret_token") @pytest.mark.flaky(reruns=3) def test_default_profile_with_custom_configs(self): profile = "default" custom_config = self._create_config_file(profile) custom_cred = self._create_cred_file(profile) command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path ) env = os.environ.copy() # Explicitly clean environment variables beforehand env.pop("AWS_DEFAULT_REGION", None) env.pop("AWS_REGION", None) env.pop("AWS_ACCESS_KEY_ID", None) env.pop("AWS_SECRET_ACCESS_KEY", None) env.pop("AWS_SESSION_TOKEN", None) env["AWS_CONFIG_FILE"] = custom_config env["AWS_SHARED_CREDENTIALS_FILE"] = custom_cred process = Popen(command_list, stdout=PIPE, env=env) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) self.assertEqual(environ["AWS_DEFAULT_REGION"], "us-west-1") self.assertEqual(environ["AWS_REGION"], "us-west-1") self.assertEqual(environ["AWS_ACCESS_KEY_ID"], "someaccesskeyid") self.assertEqual(environ["AWS_SECRET_ACCESS_KEY"], "shhhhhthisisasecret") self.assertEqual(environ["AWS_SESSION_TOKEN"], "sessiontoken") @pytest.mark.flaky(reruns=3) def test_custom_profile_with_custom_configs(self): custom_config = self._create_config_file("custom") custom_cred = self._create_cred_file("custom") command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path, profile="custom" ) env = os.environ.copy() # Explicitly clean environment variables beforehand env.pop("AWS_DEFAULT_REGION", None) env.pop("AWS_REGION", None) env.pop("AWS_ACCESS_KEY_ID", None) env.pop("AWS_SECRET_ACCESS_KEY", None) env.pop("AWS_SESSION_TOKEN", None) env["AWS_CONFIG_FILE"] = custom_config env["AWS_SHARED_CREDENTIALS_FILE"] = custom_cred process = Popen(command_list, stdout=PIPE, env=env) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) self.assertEqual(environ["AWS_DEFAULT_REGION"], "us-west-1") self.assertEqual(environ["AWS_REGION"], "us-west-1") self.assertEqual(environ["AWS_ACCESS_KEY_ID"], "someaccesskeyid") self.assertEqual(environ["AWS_SECRET_ACCESS_KEY"], "shhhhhthisisasecret") self.assertEqual(environ["AWS_SESSION_TOKEN"], "sessiontoken") @pytest.mark.flaky(reruns=3) def test_custom_profile_through_envrionment_variables(self): # When using a custom profile in a custom location, you need both the config # and credential file otherwise we fail to find a region or the profile (depending # on which one is provided custom_config = self._create_config_file("custom") custom_cred = self._create_cred_file("custom") command_list = self.get_command_list( "EchoEnvWithParameters", template_path=self.template_path, event_path=self.event_path ) env = os.environ.copy() # Explicitly clean environment variables beforehand env.pop("AWS_DEFAULT_REGION", None) env.pop("AWS_REGION", None) env.pop("AWS_ACCESS_KEY_ID", None) env.pop("AWS_SECRET_ACCESS_KEY", None) env.pop("AWS_SESSION_TOKEN", None) env["AWS_CONFIG_FILE"] = custom_config env["AWS_SHARED_CREDENTIALS_FILE"] = custom_cred env["AWS_PROFILE"] = "custom" process = Popen(command_list, stdout=PIPE, env=env) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() environ = json.loads(process_stdout.decode("utf-8")) self.assertEqual(environ["AWS_DEFAULT_REGION"], "us-west-1") self.assertEqual(environ["AWS_REGION"], "us-west-1") self.assertEqual(environ["AWS_ACCESS_KEY_ID"], "someaccesskeyid") self.assertEqual(environ["AWS_SECRET_ACCESS_KEY"], "shhhhhthisisasecret") self.assertEqual(environ["AWS_SESSION_TOKEN"], "sessiontoken") def _create_config_file(self, profile): if profile == "default": config_file_content = "[{}]\noutput = json\nregion = us-west-1".format(profile) else: config_file_content = "[profile {}]\noutput = json\nregion = us-west-1".format(profile) custom_config = os.path.join(self.config_dir, "customconfig") with open(custom_config, "w") as file: file.write(config_file_content) return custom_config def _create_cred_file(self, profile): cred_file_content = "[{}]\naws_access_key_id = someaccesskeyid\naws_secret_access_key = shhhhhthisisasecret \ \naws_session_token = sessiontoken".format( profile ) custom_cred = os.path.join(self.config_dir, "customcred") with open(custom_cred, "w") as file: file.write(cred_file_content) return custom_cred @skipIf(SKIP_LAYERS_TESTS, "Skip layers tests in Appveyor only") class TestLayerVersion(InvokeIntegBase): template = Path("layers", "layer-template.yml") region = "us-west-2" layer_utils = LayerUtils(region=region) def setUp(self): self.layer_cache = Path().home().joinpath("integ_layer_cache") def tearDown(self): docker_client = docker.from_env() samcli_images = docker_client.images.list(name="samcli/lambda") for image in samcli_images: docker_client.images.remove(image.id) shutil.rmtree(str(self.layer_cache)) @classmethod def setUpClass(cls): cls.layer_utils.upsert_layer(LayerUtils.generate_layer_name(), "LayerOneArn", "layer1.zip") cls.layer_utils.upsert_layer(LayerUtils.generate_layer_name(), "LayerTwoArn", "layer2.zip") super(TestLayerVersion, cls).setUpClass() @classmethod def tearDownClass(cls): cls.layer_utils.delete_layers() # Added to handle the case where ^C failed the test due to invalid cleanup of layers docker_client = docker.from_env() samcli_images = docker_client.images.list(name="samcli/lambda") for image in samcli_images: docker_client.images.remove(image.id) integ_layer_cache_dir = Path().home().joinpath("integ_layer_cache") if integ_layer_cache_dir.exists(): shutil.rmtree(str(integ_layer_cache_dir)) super(TestLayerVersion, cls).tearDownClass() @parameterized.expand( [ ("ReferenceServerlessLayerVersionServerlessFunction"), ("ReferenceLambdaLayerVersionServerlessFunction"), ("ReferenceServerlessLayerVersionLambdaFunction"), ("ReferenceLambdaLayerVersionLambdaFunction"), ("ReferenceServerlessLayerVersionServerlessFunction"), ] ) def test_reference_of_layer_version(self, function_logical_id): command_list = self.get_command_list( function_logical_id, template_path=self.template_path, no_event=True, region=self.region, layer_cache=str(self.layer_cache), parameter_overrides=self.layer_utils.parameters_overrides, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.strip() expected_output = '"This is a Layer Ping from simple_python"' self.assertEqual(process_stdout.decode("utf-8"), expected_output) @parameterized.expand([("OneLayerVersionServerlessFunction"), ("OneLayerVersionLambdaFunction")]) def test_download_one_layer(self, function_logical_id): command_list = self.get_command_list( function_logical_id, template_path=self.template_path, no_event=True, region=self.region, layer_cache=str(self.layer_cache), parameter_overrides=self.layer_utils.parameters_overrides, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.decode("utf-8").strip().split(os.linesep)[-1] expected_output = '"Layer1"' self.assertEqual(process_stdout, expected_output) @parameterized.expand([("ChangedLayerVersionServerlessFunction"), ("ChangedLayerVersionLambdaFunction")]) def test_publish_changed_download_layer(self, function_logical_id): layer_name = self.layer_utils.generate_layer_name() self.layer_utils.upsert_layer(layer_name=layer_name, ref_layer_name="ChangedLayerArn", layer_zip="layer1.zip") command_list = self.get_command_list( function_logical_id, template_path=self.template_path, no_event=True, region=self.region, layer_cache=str(self.layer_cache), parameter_overrides=self.layer_utils.parameters_overrides, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stdout = stdout.decode("utf-8").strip().split(os.linesep)[-1] expected_output = '"Layer1"' self.assertEqual(process_stdout, expected_output) self.layer_utils.upsert_layer( layer_name=layer_name, ref_layer_name="ChangedLayerArn", layer_zip="changedlayer1.zip" ) command_list = self.get_command_list( function_logical_id, template_path=self.template_path, no_event=True, region=self.region, layer_cache=str(self.layer_cache), parameter_overrides=self.layer_utils.parameters_overrides, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate() except TimeoutExpired: process.kill() raise process_stdout = stdout.decode("utf-8").strip().split(os.linesep)[-1] expected_output = '"Changed_Layer_1"' self.assertEqual(process_stdout, expected_output) @parameterized.expand([("TwoLayerVersionServerlessFunction"), ("TwoLayerVersionLambdaFunction")]) @pytest.mark.flaky(reruns=3) def test_download_two_layers(self, function_logical_id): command_list = self.get_command_list( function_logical_id, template_path=self.template_path, no_event=True, region=self.region, layer_cache=str(self.layer_cache), parameter_overrides=self.layer_utils.parameters_overrides, ) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise stdout = stdout process_stdout = stdout.decode("utf-8").strip().split(os.linesep)[-1] expected_output = '"Layer2"' self.assertEqual(process_stdout, expected_output) def test_caching_two_layers(self): command_list = self.get_command_list( "TwoLayerVersionServerlessFunction", template_path=self.template_path, no_event=True, region=self.region, layer_cache=str(self.layer_cache), parameter_overrides=self.layer_utils.parameters_overrides, ) process = Popen(command_list, stdout=PIPE) try: process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise self.assertEqual(2, len(os.listdir(str(self.layer_cache)))) def test_caching_two_layers_with_layer_cache_env_set(self): command_list = self.get_command_list( "TwoLayerVersionServerlessFunction", template_path=self.template_path, no_event=True, region=self.region, parameter_overrides=self.layer_utils.parameters_overrides, ) env = os.environ.copy() env["SAM_LAYER_CACHE_BASEDIR"] = str(self.layer_cache) process = Popen(command_list, stdout=PIPE, env=env) try: process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise self.assertEqual(2, len(os.listdir(str(self.layer_cache)))) @skipIf(SKIP_LAYERS_TESTS, "Skip layers tests in Appveyor only") class TestLayerVersionThatDoNotCreateCache(InvokeIntegBase): template = Path("layers", "layer-template.yml") region = "us-west-2" layer_utils = LayerUtils(region=region) def setUp(self): self.layer_cache = Path().home().joinpath("integ_layer_cache") def tearDown(self): docker_client = docker.from_env() samcli_images = docker_client.images.list(name="samcli/lambda") for image in samcli_images: docker_client.images.remove(image.id) def test_layer_does_not_exist(self): self.layer_utils.upsert_layer(LayerUtils.generate_layer_name(), "LayerOneArn", "layer1.zip") non_existent_layer_arn = self.layer_utils.parameters_overrides["LayerOneArn"].replace( self.layer_utils.layers_meta[0].layer_name, "non_existent_layer" ) command_list = self.get_command_list( "LayerVersionDoesNotExistFunction", template_path=self.template_path, no_event=True, region=self.region, parameter_overrides={"NonExistentLayerArn": non_existent_layer_arn}, ) process = Popen(command_list, stderr=PIPE) try: _, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stderr = stderr.strip() error_output = process_stderr.decode("utf-8") expected_error_output = "{} was not found.".format(non_existent_layer_arn) self.assertIn(expected_error_output, error_output) self.layer_utils.delete_layers() def test_account_does_not_exist_for_layer(self): command_list = self.get_command_list( "LayerVersionAccountDoesNotExistFunction", template_path=self.template_path, no_event=True, region=self.region, ) process = Popen(command_list, stderr=PIPE) try: _, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stderr = stderr.strip() error_output = process_stderr.decode("utf-8") expected_error_output = ( "Credentials provided are missing lambda:Getlayerversion policy that is needed to " "download the layer or you do not have permission to download the layer" ) self.assertIn(expected_error_output, error_output) @skipIf(SKIP_LAYERS_TESTS, "Skip layers tests in Appveyor only") class TestBadLayerVersion(InvokeIntegBase): template = Path("layers", "layer-bad-template.yaml") region = "us-west-2" layer_utils = LayerUtils(region=region) def test_unresolved_layer_due_to_bad_instrinsic(self): command_list = self.get_command_list( "LayerBadInstrinsic", template_path=self.template_path, no_event=True, region=self.region, parameter_overrides={"LayerVersion": "1"}, ) process = Popen(command_list, stderr=PIPE) try: _, stderr = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise process_stderr = stderr.strip() error_output = process_stderr.decode("utf-8") expected_error_output = "Error: arn:aws:lambda:us-west-2:111111111101:layer:layerDoesNotExist:${LayerVersion} is an Invalid Layer Arn." self.assertIn(expected_error_output, error_output)
[]
[]
[]
[]
[]
python
0
0
services/ehpc/struct_nodes_in_list_nodes.go
package ehpc //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // NodesInListNodes is a nested struct in ehpc response type NodesInListNodes struct { NodeInfo []NodeInfo `json:"NodeInfo" xml:"NodeInfo"` }
[]
[]
[]
[]
[]
go
null
null
null
tests/common/impala_test_suite.py
# 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. # # The base class that should be used for almost all Impala tests import grp import json import logging import os import pprint import pwd import pytest import re import requests import shutil import socket import subprocess import tempfile import time from functools import wraps from getpass import getuser from random import choice from subprocess import check_call from tests.common.base_test_suite import BaseTestSuite from tests.common.errors import Timeout from tests.common.impala_connection import create_connection from tests.common.impala_service import ImpaladService from tests.common.test_dimensions import ( ALL_BATCH_SIZES, ALL_CLUSTER_SIZES, ALL_DISABLE_CODEGEN_OPTIONS, ALL_NODES_ONLY, TableFormatInfo, create_exec_option_dimension, get_dataset_from_workload, load_table_info_dimension) from tests.common.test_result_verifier import ( apply_error_match_filter, try_compile_regex, verify_raw_results, verify_runtime_profile) from tests.common.test_vector import ImpalaTestDimension from tests.performance.query import Query from tests.performance.query_exec_functions import execute_using_jdbc from tests.performance.query_executor import JdbcQueryExecConfig from tests.util.filesystem_utils import ( IS_S3, IS_ABFS, IS_ADLS, S3_BUCKET_NAME, ADLS_STORE_NAME, FILESYSTEM_PREFIX) from tests.util.hdfs_util import ( HdfsConfig, get_hdfs_client, get_hdfs_client_from_conf, NAMENODE) from tests.util.s3_util import S3Client from tests.util.abfs_util import ABFSClient from tests.util.test_file_parser import ( QueryTestSectionReader, parse_query_test_file, write_test_file) from tests.util.thrift_util import create_transport # Imports required for Hive Metastore Client from hive_metastore import ThriftHiveMetastore from thrift.protocol import TBinaryProtocol # Initializing the logger before conditional imports, since we will need it # for them. LOG = logging.getLogger('impala_test_suite') # The ADLS python client isn't downloaded when ADLS isn't the target FS, so do a # conditional import. if IS_ADLS: try: from tests.util.adls_util import ADLSClient except ImportError: LOG.error("Need the ADLSClient for testing with ADLS") IMPALAD_HOST_PORT_LIST = pytest.config.option.impalad.split(',') assert len(IMPALAD_HOST_PORT_LIST) > 0, 'Must specify at least 1 impalad to target' IMPALAD = IMPALAD_HOST_PORT_LIST[0] IMPALAD_HS2_HOST_PORT =\ IMPALAD.split(':')[0] + ":" + pytest.config.option.impalad_hs2_port HIVE_HS2_HOST_PORT = pytest.config.option.hive_server2 WORKLOAD_DIR = os.environ['IMPALA_WORKLOAD_DIR'] HDFS_CONF = HdfsConfig(pytest.config.option.minicluster_xml_conf) TARGET_FILESYSTEM = os.getenv("TARGET_FILESYSTEM") or "hdfs" IMPALA_HOME = os.getenv("IMPALA_HOME") INTERNAL_LISTEN_HOST = os.getenv("INTERNAL_LISTEN_HOST") # Some tests use the IP instead of the host. INTERNAL_LISTEN_IP = socket.gethostbyname_ex(INTERNAL_LISTEN_HOST)[2][0] EE_TEST_LOGS_DIR = os.getenv("IMPALA_EE_TEST_LOGS_DIR") # Match any SET statement. Assume that query options' names # only contain alphabets, underscores and digits after position 1. # The statement may include SQL line comments starting with --, which we need to # strip out. The test file parser already strips out comments starting with #. COMMENT_LINES_REGEX = r'(?:\s*--.*\n)*' SET_PATTERN = re.compile( COMMENT_LINES_REGEX + r'\s*set\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=*', re.I) METRICS_URL = 'http://localhost:25000/metrics?json' # Base class for Impala tests. All impala test cases should inherit from this class class ImpalaTestSuite(BaseTestSuite): @classmethod def add_test_dimensions(cls): """ A hook for adding additional dimensions. By default load the table_info and exec_option dimensions, but if a test wants to add more dimensions or different dimensions they can override this function. """ super(ImpalaTestSuite, cls).add_test_dimensions() cls.ImpalaTestMatrix.add_dimension( cls.create_table_info_dimension(cls.exploration_strategy())) cls.ImpalaTestMatrix.add_dimension(cls.__create_exec_option_dimension()) # Execute tests through Beeswax by default. Individual tests that have been converted # to work with the HS2 client can add HS2 in addition to or instead of beeswax. cls.ImpalaTestMatrix.add_dimension(ImpalaTestDimension('protocol', 'beeswax')) @classmethod def setup_class(cls): """Setup section that runs before each test suite""" cls.hive_client, cls.client, cls.hs2_client = [None, None, None] # Create a Hive Metastore Client (used for executing some test SETUP steps metastore_host, metastore_port = pytest.config.option.metastore_server.split(':') trans_type = 'buffered' if pytest.config.option.use_kerberos: trans_type = 'kerberos' cls.hive_transport = create_transport( host=metastore_host, port=metastore_port, service=pytest.config.option.hive_service_name, transport_type=trans_type) protocol = TBinaryProtocol.TBinaryProtocol(cls.hive_transport) cls.hive_client = ThriftHiveMetastore.Client(protocol) cls.hive_transport.open() # Create a connection to Impala, self.client is Beeswax so that existing tests that # assume beeswax do not need modification (yet). cls.client = cls.create_impala_client(protocol='beeswax') try: cls.hs2_client = cls.create_impala_client(protocol='hs2') except Exception, e: # HS2 connection can fail for benign reasons, e.g. running with unsupported auth. LOG.info("HS2 connection setup failed, continuing...: {0}", e) # Default query options are populated on demand. cls.default_query_options = {} cls.impalad_test_service = cls.create_impala_service() cls.hdfs_client = cls.create_hdfs_client() cls.filesystem_client = cls.hdfs_client if IS_S3: cls.filesystem_client = S3Client(S3_BUCKET_NAME) elif IS_ABFS: cls.filesystem_client = ABFSClient() elif IS_ADLS: cls.filesystem_client = ADLSClient(ADLS_STORE_NAME) # Override the shell history path so that commands run by any tests # don't write any history into the developer's file. os.environ['IMPALA_HISTFILE'] = '/dev/null' @classmethod def teardown_class(cls): """Setup section that runs after each test suite""" # Cleanup the Impala and Hive Metastore client connections if cls.hive_transport: cls.hive_transport.close() if cls.client: cls.client.close() if cls.hs2_client: cls.hs2_client.close() @classmethod def create_impala_client(cls, host_port=None, protocol='beeswax'): if host_port is None: host_port = cls.__get_default_host_port(protocol) client = create_connection(host_port=host_port, use_kerberos=pytest.config.option.use_kerberos, protocol=protocol) client.connect() return client @classmethod def __get_default_host_port(cls, protocol): if protocol == 'beeswax': return IMPALAD else: assert protocol == 'hs2' return IMPALAD_HS2_HOST_PORT @classmethod def __get_cluster_host_ports(cls, protocol): """Return a list of host/port combinations for all impalads in the cluster.""" if protocol == 'beeswax': return IMPALAD_HOST_PORT_LIST else: assert protocol == 'hs2' # TODO: support running tests against multiple coordinators for HS2. It should work, # we just need to update all test runners to pass in all host/port combinations for # the cluster and then handle it here. raise NotImplementedError( "Not yet implemented: only one HS2 host/port can be configured") @classmethod def create_impala_service(cls, host_port=IMPALAD, webserver_port=25000): host, port = host_port.split(':') return ImpaladService(host, beeswax_port=port, webserver_port=webserver_port) @classmethod def create_hdfs_client(cls): if pytest.config.option.namenode_http_address is None: hdfs_client = get_hdfs_client_from_conf(HDFS_CONF) else: host, port = pytest.config.option.namenode_http_address.split(":") hdfs_client = get_hdfs_client(host, port) return hdfs_client @classmethod def all_db_names(cls): results = cls.client.execute("show databases").data # Extract first column - database name return [row.split("\t")[0] for row in results] @classmethod def cleanup_db(cls, db_name, sync_ddl=1): cls.client.execute("use default") cls.client.set_configuration({'sync_ddl': sync_ddl}) cls.client.execute("drop database if exists `" + db_name + "` cascade") def __restore_query_options(self, query_options_changed, impalad_client): """ Restore the list of modified query options to their default values. """ # Populate the default query option if it's empty. if not self.default_query_options: query_options = impalad_client.get_default_configuration() for key, value in query_options.iteritems(): self.default_query_options[key.upper()] = value # Restore all the changed query options. for query_option in query_options_changed: query_option = query_option.upper() if not query_option in self.default_query_options: continue default_val = self.default_query_options[query_option] query_str = 'SET ' + query_option + '="' + default_val + '"' try: impalad_client.execute(query_str) except Exception as e: LOG.info('Unexpected exception when executing ' + query_str + ' : ' + str(e)) def get_impala_partition_info(self, table_name, *include_fields): """ Find information about partitions of a table, as returned by a SHOW PARTITION statement. Return a list that contains one tuple for each partition. If 'include_fields' is not specified, the tuples will contain all the fields returned by SHOW PARTITION. Otherwise, return only those fields whose names are listed in 'include_fields'. Field names are compared case-insensitively. """ exec_result = self.client.execute('show partitions %s' % table_name) fieldSchemas = exec_result.schema.fieldSchemas fields_dict = {} for idx, fs in enumerate(fieldSchemas): fields_dict[fs.name.lower()] = idx rows = exec_result.get_data().split('\n') rows.pop() fields_idx = [] for fn in include_fields: fn = fn.lower() assert fn in fields_dict, 'Invalid field: %s' % fn fields_idx.append(fields_dict[fn]) result = [] for row in rows: fields = row.split('\t') if not fields_idx: result_fields = fields else: result_fields = [] for i in fields_idx: result_fields.append(fields[i]) result.append(tuple(result_fields)) return result def get_debug_page(self, page_url): """Returns the content of the debug page 'page_url' as json.""" response = requests.get(page_url) assert response.status_code == requests.codes.ok return json.loads(response.text) def get_metric(self, name): """Finds the metric with name 'name' and returns its value as an int.""" def iter_metrics(group): for m in group['metrics']: yield m for c in group['child_groups']: for m in iter_metrics(c): yield m metrics = self.get_debug_page(METRICS_URL)['metric_group'] for m in iter_metrics(metrics): if m['name'] == name: return int(m['value']) assert False, "Could not find metric: %s" % name def __verify_exceptions(self, expected_strs, actual_str, use_db): """ Verifies that at least one of the strings in 'expected_str' is either: * A row_regex: line that matches the actual exception string 'actual_str' * A substring of the actual exception string 'actual_str'. """ actual_str = actual_str.replace('\n', '') for expected_str in expected_strs: # In error messages, some paths are always qualified and some are not. # So, allow both $NAMENODE and $FILESYSTEM_PREFIX to be used in CATCH. expected_str = expected_str.strip() \ .replace('$FILESYSTEM_PREFIX', FILESYSTEM_PREFIX) \ .replace('$NAMENODE', NAMENODE) \ .replace('$IMPALA_HOME', IMPALA_HOME) \ .replace('$INTERNAL_LISTEN_HOST', INTERNAL_LISTEN_HOST)\ .replace('$INTERNAL_LISTEN_IP', INTERNAL_LISTEN_IP) if use_db: expected_str = expected_str.replace('$DATABASE', use_db) # Strip newlines so we can split error message into multiple lines expected_str = expected_str.replace('\n', '') expected_regex = try_compile_regex(expected_str) if expected_regex: if expected_regex.match(actual_str): return else: # Not a regex - check if expected substring is present in actual. if expected_str in actual_str: return assert False, 'Unexpected exception string. Expected: %s\nNot found in actual: %s' % \ (expected_str, actual_str) def __verify_results_and_errors(self, vector, test_section, result, use_db): """Verifies that both results and error sections are as expected. Rewrites both by replacing $NAMENODE, $DATABASE and $IMPALA_HOME with their actual values, and optionally rewriting filenames with __HDFS_FILENAME__, to ensure that expected and actual values are easily compared. """ replace_filenames_with_placeholder = True for section_name in ('RESULTS', 'DBAPI_RESULTS', 'ERRORS'): if section_name in test_section: if "$NAMENODE" in test_section[section_name]: replace_filenames_with_placeholder = False test_section[section_name] = test_section[section_name] \ .replace('$NAMENODE', NAMENODE) \ .replace('$IMPALA_HOME', IMPALA_HOME) \ .replace('$USER', getuser()) \ .replace('$INTERNAL_LISTEN_HOST', INTERNAL_LISTEN_HOST) \ .replace('$INTERNAL_LISTEN_IP', INTERNAL_LISTEN_IP) if use_db: test_section[section_name] = test_section[section_name].replace('$DATABASE', use_db) result_section, type_section = 'RESULTS', 'TYPES' if vector.get_value('protocol') == 'hs2': if 'DBAPI_RESULTS' in test_section: assert 'RESULTS' in test_section,\ "Base RESULTS section must always be included alongside DBAPI_RESULTS" # In some cases Impyla (the HS2 dbapi client) is expected to return different # results, so use the dbapi-specific section if present. result_section = 'DBAPI_RESULTS' if 'HS2_TYPES' in test_section: assert 'TYPES' in test_section,\ "Base TYPES section must always be included alongside HS2_TYPES" # In some cases HS2 types are expected differ from Beeswax types (e.g. see # IMPALA-914), so use the HS2-specific section if present. type_section = 'HS2_TYPES' verify_raw_results(test_section, result, vector.get_value('table_format').file_format, result_section, type_section, pytest.config.option.update_results, replace_filenames_with_placeholder) def run_test_case(self, test_file_name, vector, use_db=None, multiple_impalad=False, encoding=None, test_file_vars=None): """ Runs the queries in the specified test based on the vector values Runs the query using targeting the file format/compression specified in the test vector and the exec options specified in the test vector. If multiple_impalad=True a connection to a random impalad will be chosen to execute each test section. Otherwise, the default impalad client will be used. If 'protocol' (either 'hs2' or 'beeswax') is set in the vector, a client for that protocol is used. Otherwise we use the default: beeswax. Additionally, the encoding for all test data can be specified using the 'encoding' parameter. This is useful when data is ingested in a different encoding (ex. latin). If not set, the default system encoding will be used. If a dict 'test_file_vars' is provided, then all keys will be replaced with their values in queries before they are executed. Callers need to avoid using reserved key names, see 'reserved_keywords' below. """ table_format_info = vector.get_value('table_format') exec_options = vector.get_value('exec_option') protocol = vector.get_value('protocol') # Resolve the current user's primary group name. group_id = pwd.getpwnam(getuser()).pw_gid group_name = grp.getgrgid(group_id).gr_name target_impalad_clients = list() if multiple_impalad: target_impalad_clients =\ [ImpalaTestSuite.create_impala_client(host_port, protocol=protocol) for host_port in self.__get_cluster_host_ports(protocol)] else: if protocol == 'beeswax': target_impalad_clients = [self.client] else: assert protocol == 'hs2' target_impalad_clients = [self.hs2_client] # Change the database to reflect the file_format, compression codec etc, or the # user specified database for all targeted impalad. for impalad_client in target_impalad_clients: ImpalaTestSuite.change_database(impalad_client, table_format_info, use_db, pytest.config.option.scale_factor) impalad_client.set_configuration(exec_options) sections = self.load_query_test_file(self.get_workload(), test_file_name, encoding=encoding) for test_section in sections: if 'SHELL' in test_section: assert len(test_section) == 1, \ "SHELL test sections can't contain other sections" cmd = test_section['SHELL']\ .replace('$FILESYSTEM_PREFIX', FILESYSTEM_PREFIX)\ .replace('$IMPALA_HOME', IMPALA_HOME) if use_db: cmd = cmd.replace('$DATABASE', use_db) LOG.info("Shell command: " + cmd) check_call(cmd, shell=True) continue if 'QUERY' not in test_section: assert 0, 'Error in test file %s. Test cases require a -- QUERY section.\n%s' %\ (test_file_name, pprint.pformat(test_section)) if 'SETUP' in test_section: self.execute_test_case_setup(test_section['SETUP'], table_format_info) # TODO: support running query tests against different scale factors query = QueryTestSectionReader.build_query(test_section['QUERY'] .replace('$GROUP_NAME', group_name) .replace('$IMPALA_HOME', IMPALA_HOME) .replace('$FILESYSTEM_PREFIX', FILESYSTEM_PREFIX) .replace('$SECONDARY_FILESYSTEM', os.getenv("SECONDARY_FILESYSTEM") or str()) .replace('$USER', getuser()) .replace('$INTERNAL_LISTEN_HOST', INTERNAL_LISTEN_HOST) .replace('$INTERNAL_LISTEN_IP', INTERNAL_LISTEN_IP)) if use_db: query = query.replace('$DATABASE', use_db) reserved_keywords = ["$DATABASE", "$FILESYSTEM_PREFIX", "$GROUP_NAME", "$IMPALA_HOME", "$NAMENODE", "$QUERY", "$SECONDARY_FILESYSTEM", "$USER"] if test_file_vars: for key, value in test_file_vars.iteritems(): if key in reserved_keywords: raise RuntimeError("Key {0} is reserved".format(key)) query = query.replace(key, value) if 'QUERY_NAME' in test_section: LOG.info('Query Name: \n%s\n' % test_section['QUERY_NAME']) # Support running multiple queries within the same test section, only verifying the # result of the final query. The main use case is to allow for 'USE database' # statements before a query executes, but it is not limited to that. # TODO: consider supporting result verification of all queries in the future result = None target_impalad_client = choice(target_impalad_clients) query_options_changed = [] try: user = None if 'USER' in test_section: # Create a new client so the session will use the new username. user = test_section['USER'].strip() target_impalad_client = self.create_impala_client(protocol=protocol) for query in query.split(';'): set_pattern_match = SET_PATTERN.match(query) if set_pattern_match != None: query_options_changed.append(set_pattern_match.groups()[0]) assert set_pattern_match.groups()[0] not in vector.get_value("exec_option"), \ "%s cannot be set in the '.test' file since it is in the test vector. " \ "Consider deepcopy()-ing the vector and removing this option in the " \ "python test." % set_pattern_match.groups()[0] result = self.__execute_query(target_impalad_client, query, user=user) except Exception as e: if 'CATCH' in test_section: self.__verify_exceptions(test_section['CATCH'], str(e), use_db) continue raise finally: if len(query_options_changed) > 0: self.__restore_query_options(query_options_changed, target_impalad_client) if 'CATCH' in test_section and '__NO_ERROR__' not in test_section['CATCH']: expected_str = " or ".join(test_section['CATCH']).strip() \ .replace('$FILESYSTEM_PREFIX', FILESYSTEM_PREFIX) \ .replace('$NAMENODE', NAMENODE) \ .replace('$IMPALA_HOME', IMPALA_HOME) assert False, "Expected exception: %s" % expected_str assert result is not None assert result.success # Decode the results read back if the data is stored with a specific encoding. if encoding: result.data = [row.decode(encoding) for row in result.data] # Replace $NAMENODE in the expected results with the actual namenode URI. if 'RESULTS' in test_section: # Combining 'RESULTS' with 'DML_RESULTS" is currently unsupported because # __verify_results_and_errors calls verify_raw_results which always checks # ERRORS, TYPES, LABELS, etc. which doesn't make sense if there are two # different result sets to consider (IMPALA-4471). assert 'DML_RESULTS' not in test_section self.__verify_results_and_errors(vector, test_section, result, use_db) else: # TODO: Can't validate errors without expected results for now. assert 'ERRORS' not in test_section,\ "'ERRORS' sections must have accompanying 'RESULTS' sections" # If --update_results, then replace references to the namenode URI with $NAMENODE. if pytest.config.option.update_results and 'RESULTS' in test_section: test_section['RESULTS'] = test_section['RESULTS'] \ .replace(NAMENODE, '$NAMENODE') \ .replace('$IMPALA_HOME', IMPALA_HOME) \ .replace(INTERNAL_LISTEN_HOST, '$INTERNAL_LISTEN_HOST') \ .replace(INTERNAL_LISTEN_IP, '$INTERNAL_LISTEN_IP') rt_profile_info = None if 'RUNTIME_PROFILE_%s' % table_format_info.file_format in test_section: # If this table format has a RUNTIME_PROFILE section specifically for it, evaluate # that section and ignore any general RUNTIME_PROFILE sections. rt_profile_info = 'RUNTIME_PROFILE_%s' % table_format_info.file_format elif 'RUNTIME_PROFILE' in test_section: rt_profile_info = 'RUNTIME_PROFILE' if rt_profile_info is not None: rt_profile = verify_runtime_profile(test_section[rt_profile_info], result.runtime_profile, update_section=pytest.config.option.update_results) if pytest.config.option.update_results: test_section[rt_profile_info] = "".join(rt_profile) if 'DML_RESULTS' in test_section: assert 'ERRORS' not in test_section # The limit is specified to ensure the queries aren't unbounded. We shouldn't have # test files that are checking the contents of tables larger than that anyways. dml_results_query = "select * from %s limit 1000" % \ test_section['DML_RESULTS_TABLE'] dml_result = self.__execute_query(target_impalad_client, dml_results_query) verify_raw_results(test_section, dml_result, vector.get_value('table_format').file_format, result_section='DML_RESULTS', update_section=pytest.config.option.update_results) if pytest.config.option.update_results: output_file = os.path.join(EE_TEST_LOGS_DIR, test_file_name.replace('/','_') + ".test") write_test_file(output_file, sections, encoding=encoding) def execute_test_case_setup(self, setup_section, table_format): """ Executes a test case 'SETUP' section The test case 'SETUP' section is mainly used for insert tests. These tests need to have some actions performed before each test case to ensure the target tables are empty. The current supported setup actions: RESET <table name> - Drop and recreate the table DROP PARTITIONS <table name> - Drop all partitions from the table """ setup_section = QueryTestSectionReader.build_query(setup_section) for row in setup_section.split('\n'): row = row.lstrip() if row.startswith('RESET'): db_name, table_name = QueryTestSectionReader.get_table_name_components(\ table_format, row.split('RESET')[1]) self.__reset_table(db_name, table_name) self.client.execute("invalidate metadata " + db_name + "." + table_name) elif row.startswith('DROP PARTITIONS'): db_name, table_name = QueryTestSectionReader.get_table_name_components(\ table_format, row.split('DROP PARTITIONS')[1]) self.__drop_partitions(db_name, table_name) self.client.execute("invalidate metadata " + db_name + "." + table_name) else: assert False, 'Unsupported setup command: %s' % row @classmethod def change_database(cls, impala_client, table_format=None, db_name=None, scale_factor=None): if db_name == None: assert table_format != None db_name = QueryTestSectionReader.get_db_name(table_format, scale_factor if scale_factor else '') query = 'use %s' % db_name # Clear the exec_options before executing a USE statement. # The USE statement should not fail for negative exec_option tests. impala_client.clear_configuration() impala_client.execute(query) def execute_wrapper(function): """ Issues a use database query before executing queries. Database names are dependent on the input format for table, which the table names remaining the same. A use database is issued before query execution. As such, database names need to be build pre execution, this method wraps around the different execute methods and provides a common interface to issue the proper use command. """ @wraps(function) def wrapper(*args, **kwargs): table_format = None if kwargs.get('table_format'): table_format = kwargs.get('table_format') del kwargs['table_format'] if kwargs.get('vector'): table_format = kwargs.get('vector').get_value('table_format') del kwargs['vector'] # self is the implicit first argument if table_format is not None: args[0].change_database(args[0].client, table_format) return function(*args, **kwargs) return wrapper @classmethod @execute_wrapper def execute_query_expect_success(cls, impalad_client, query, query_options=None, user=None): """Executes a query and asserts if the query fails""" result = cls.__execute_query(impalad_client, query, query_options, user) assert result.success return result @execute_wrapper def execute_query_expect_failure(self, impalad_client, query, query_options=None, user=None): """Executes a query and asserts if the query succeeds""" result = None try: result = self.__execute_query(impalad_client, query, query_options, user) except Exception, e: return e assert not result.success, "No failure encountered for query %s" % query return result @execute_wrapper def execute_query_unchecked(self, impalad_client, query, query_options=None, user=None): return self.__execute_query(impalad_client, query, query_options, user) @execute_wrapper def execute_query(self, query, query_options=None): return self.__execute_query(self.client, query, query_options) def execute_query_using_client(self, client, query, vector): self.change_database(client, vector.get_value('table_format')) return client.execute(query) def execute_query_async_using_client(self, client, query, vector): self.change_database(client, vector.get_value('table_format')) return client.execute_async(query) def close_query_using_client(self, client, query): return client.close_query(query) @execute_wrapper def execute_query_async(self, query, query_options=None): if query_options is not None: self.client.set_configuration(query_options) return self.client.execute_async(query) @execute_wrapper def close_query(self, query): return self.client.close_query(query) @execute_wrapper def execute_scalar(self, query, query_options=None): result = self.__execute_query(self.client, query, query_options) assert len(result.data) <= 1, 'Multiple values returned from scalar' return result.data[0] if len(result.data) == 1 else None def exec_and_compare_hive_and_impala_hs2(self, stmt, compare = lambda x, y: x == y): """Compare Hive and Impala results when executing the same statment over HS2""" # execute_using_jdbc expects a Query object. Convert the query string into a Query # object query = Query() query.query_str = stmt # Run the statement targeting Hive exec_opts = JdbcQueryExecConfig(impalad=HIVE_HS2_HOST_PORT, transport='SASL') hive_results = execute_using_jdbc(query, exec_opts).data # Run the statement targeting Impala exec_opts = JdbcQueryExecConfig(impalad=IMPALAD_HS2_HOST_PORT, transport='NOSASL') impala_results = execute_using_jdbc(query, exec_opts).data # Compare the results assert (impala_results is not None) and (hive_results is not None) assert compare(impala_results, hive_results) def load_query_test_file(self, workload, file_name, valid_section_names=None, encoding=None): """ Loads/Reads the specified query test file. Accepts the given section names as valid. Uses a default list of valid section names if valid_section_names is None. """ test_file_path = os.path.join(WORKLOAD_DIR, workload, 'queries', file_name + '.test') if not os.path.isfile(test_file_path): assert False, 'Test file not found: %s' % file_name return parse_query_test_file(test_file_path, valid_section_names, encoding=encoding) def __drop_partitions(self, db_name, table_name): """Drops all partitions in the given table""" for partition in self.hive_client.get_partition_names(db_name, table_name, 0): assert self.hive_client.drop_partition_by_name(db_name, table_name, \ partition, True), 'Could not drop partition: %s' % partition @classmethod def __execute_query(cls, impalad_client, query, query_options=None, user=None): """Executes the given query against the specified Impalad""" if query_options is not None: impalad_client.set_configuration(query_options) return impalad_client.execute(query, user=user) def __reset_table(self, db_name, table_name): """Resets a table (drops and recreates the table)""" table = self.hive_client.get_table(db_name, table_name) assert table is not None self.hive_client.drop_table(db_name, table_name, True) self.hive_client.create_table(table) def clone_table(self, src_tbl, dst_tbl, recover_partitions, vector): src_loc = self._get_table_location(src_tbl, vector) self.client.execute("create external table {0} like {1} location '{2}'"\ .format(dst_tbl, src_tbl, src_loc)) if recover_partitions: self.client.execute("alter table {0} recover partitions".format(dst_tbl)) def appx_equals(self, a, b, diff_perc): """Returns True if 'a' and 'b' are within 'diff_perc' percent of each other, False otherwise. 'diff_perc' must be a float in [0,1].""" if a == b: return True # Avoid division by 0 assert abs(a - b) / float(max(a,b)) <= diff_perc def _get_table_location(self, table_name, vector): """ Returns the HDFS location of the table """ result = self.execute_query_using_client(self.client, "describe formatted %s" % table_name, vector) for row in result.data: if 'Location:' in row: return row.split('\t')[1] # This should never happen. assert 0, 'Unable to get location for table: ' + table_name def run_stmt_in_hive(self, stmt, username=getuser()): """ Run a statement in Hive, returning stdout if successful and throwing RuntimeError(stderr) if not. """ # When HiveServer2 is configured to use "local" mode (i.e., MR jobs are run # in-process rather than on YARN), Hadoop's LocalDistributedCacheManager has a # race, wherein it tires to localize jars into # /tmp/hadoop-$USER/mapred/local/<millis>. Two simultaneous Hive queries # against HS2 can conflict here. Weirdly LocalJobRunner handles a similar issue # (with the staging directory) by appending a random number. To overcome this, # in the case that HS2 is on the local machine (which we conflate with also # running MR jobs locally), we move the temporary directory into a unique # directory via configuration. This workaround can be removed when # https://issues.apache.org/jira/browse/MAPREDUCE-6441 is resolved. # A similar workaround is used in bin/load-data.py. tmpdir = None beeline_opts = [] if pytest.config.option.hive_server2.startswith("localhost:"): tmpdir = tempfile.mkdtemp(prefix="impala-tests-") beeline_opts += ['--hiveconf', 'mapreduce.cluster.local.dir={0}'.format(tmpdir)] try: # Remove HADOOP_CLASSPATH from environment. Beeline doesn't need it, # and doing so avoids Hadoop 3's classpath de-duplication code from # placing $HADOOP_CONF_DIR too late in the classpath to get the right # log4j configuration file picked up. Some log4j configuration files # in Hadoop's jars send logging to stdout, confusing Impala's test # framework. env = os.environ.copy() env.pop("HADOOP_CLASSPATH", None) call = subprocess.Popen( ['beeline', '--outputformat=csv2', '-u', 'jdbc:hive2://' + pytest.config.option.hive_server2, '-n', username, '-e', stmt] + beeline_opts, stdout=subprocess.PIPE, stderr=subprocess.PIPE, # Beeline in Hive 2.1 will read from stdin even when "-e" # is specified; explicitly make sure there's nothing to # read to avoid hanging, especially when running interactively # with py.test. stdin=file("/dev/null"), env=env) (stdout, stderr) = call.communicate() call.wait() if call.returncode != 0: raise RuntimeError(stderr) return stdout finally: if tmpdir is not None: shutil.rmtree(tmpdir) def hive_partition_names(self, table_name): """Find the names of the partitions of a table, as Hive sees them. The return format is a list of strings. Each string represents a partition value of a given column in a format like 'column1=7/column2=8'. """ return self.run_stmt_in_hive( 'show partitions %s' % table_name).split('\n')[1:-1] @classmethod def create_table_info_dimension(cls, exploration_strategy): # If the user has specified a specific set of table formats to run against, then # use those. Otherwise, load from the workload test vectors. if pytest.config.option.table_formats: table_formats = list() for tf in pytest.config.option.table_formats.split(','): dataset = get_dataset_from_workload(cls.get_workload()) table_formats.append(TableFormatInfo.create_from_string(dataset, tf)) tf_dimensions = ImpalaTestDimension('table_format', *table_formats) else: tf_dimensions = load_table_info_dimension(cls.get_workload(), exploration_strategy) # If 'skip_hbase' is specified or the filesystem is isilon, s3 or local, we don't # need the hbase dimension. if pytest.config.option.skip_hbase or TARGET_FILESYSTEM.lower() \ in ['s3', 'isilon', 'local', 'abfs', 'adls']: for tf_dimension in tf_dimensions: if tf_dimension.value.file_format == "hbase": tf_dimensions.remove(tf_dimension) break return tf_dimensions @classmethod def __create_exec_option_dimension(cls): cluster_sizes = ALL_CLUSTER_SIZES disable_codegen_options = ALL_DISABLE_CODEGEN_OPTIONS batch_sizes = ALL_BATCH_SIZES exec_single_node_option = [0] if cls.exploration_strategy() == 'core': disable_codegen_options = [False] cluster_sizes = ALL_NODES_ONLY return create_exec_option_dimension(cluster_sizes, disable_codegen_options, batch_sizes, exec_single_node_option=exec_single_node_option, disable_codegen_rows_threshold_options=[0]) @classmethod def exploration_strategy(cls): default_strategy = pytest.config.option.exploration_strategy if pytest.config.option.workload_exploration_strategy: workload_strategies = pytest.config.option.workload_exploration_strategy.split(',') for workload_strategy in workload_strategies: workload_strategy = workload_strategy.split(':') if len(workload_strategy) != 2: raise ValueError, 'Invalid workload:strategy format: %s' % workload_strategy if cls.get_workload() == workload_strategy[0]: return workload_strategy[1] return default_strategy def wait_for_state(self, handle, expected_state, timeout): """Waits for the given 'query_handle' to reach the 'expected_state'. If it does not reach the given state within 'timeout' seconds, the method throws an AssertionError. """ self.wait_for_any_state(handle, [expected_state], timeout) def wait_for_any_state(self, handle, expected_states, timeout): """Waits for the given 'query_handle' to reach one of 'expected_states'. If it does not reach one of the given states within 'timeout' seconds, the method throws an AssertionError. Returns the final state. """ start_time = time.time() actual_state = self.client.get_state(handle) while actual_state not in expected_states and time.time() - start_time < timeout: actual_state = self.client.get_state(handle) time.sleep(0.5) if actual_state not in expected_states: raise Timeout("query {0} did not reach one of the expected states {1}, " "last known state {2}".format(handle.get_handle().id, expected_states, actual_state)) return actual_state def assert_impalad_log_contains(self, level, line_regex, expected_count=1): """ Convenience wrapper around assert_log_contains for impalad logs. """ self.assert_log_contains("impalad", level, line_regex, expected_count) def assert_catalogd_log_contains(self, level, line_regex, expected_count=1): """ Convenience wrapper around assert_log_contains for catalogd logs. """ self.assert_log_contains("catalogd", level, line_regex, expected_count) def assert_log_contains(self, daemon, level, line_regex, expected_count=1): """ Assert that the daemon log with specified level (e.g. ERROR, WARNING, INFO) contains expected_count lines with a substring matching the regex. When expected_count is -1, at least one match is expected. When using this method to check log files of running processes, the caller should make sure that log buffering has been disabled, for example by adding '-logbuflevel=-1' to the daemon startup options. """ pattern = re.compile(line_regex) found = 0 if hasattr(self, "impala_log_dir"): log_dir = self.impala_log_dir else: log_dir = EE_TEST_LOGS_DIR log_file_path = os.path.join(log_dir, daemon + "." + level) # Resolve symlinks to make finding the file easier. log_file_path = os.path.realpath(log_file_path) with open(log_file_path) as log_file: for line in log_file: if pattern.search(line): found += 1 if expected_count == -1: assert found > 0, "Expected at least one line in file %s matching regex '%s'"\ ", but found none." % (log_file_path, line_regex) else: assert found == expected_count, "Expected %d lines in file %s matching regex '%s'"\ ", but found %d lines. Last line was: \n%s" %\ (expected_count, log_file_path, line_regex, found, line)
[]
[]
[ "IMPALA_HISTFILE", "IMPALA_HOME", "IMPALA_WORKLOAD_DIR", "TARGET_FILESYSTEM", "SECONDARY_FILESYSTEM", "INTERNAL_LISTEN_HOST", "IMPALA_EE_TEST_LOGS_DIR" ]
[]
["IMPALA_HISTFILE", "IMPALA_HOME", "IMPALA_WORKLOAD_DIR", "TARGET_FILESYSTEM", "SECONDARY_FILESYSTEM", "INTERNAL_LISTEN_HOST", "IMPALA_EE_TEST_LOGS_DIR"]
python
7
0
go/src/github.com/koding/tunnel/tunneltest/tunneltest.go
package tunneltest import ( "errors" "fmt" "log" "net" "net/http" "net/url" "os" "sort" "strconv" "sync" "testing" "time" "github.com/koding/tunnel" ) var debugNet = os.Getenv("DEBUGNET") == "1" type dbgListener struct { net.Listener } func (l dbgListener) Accept() (net.Conn, error) { conn, err := l.Listener.Accept() if err != nil { return nil, err } return dbgConn{conn}, nil } type dbgConn struct { net.Conn } func (c dbgConn) Read(p []byte) (int, error) { n, err := c.Conn.Read(p) os.Stderr.Write(p) return n, err } func (c dbgConn) Write(p []byte) (int, error) { n, err := c.Conn.Write(p) os.Stderr.Write(p) return n, err } func logf(format string, args ...interface{}) { if testing.Verbose() { log.Printf("[tunneltest] "+format, args...) } } func nonil(err ...error) error { for _, e := range err { if e != nil { return e } } return nil } func parseHostPort(addr string) (string, int, error) { host, port, err := net.SplitHostPort(addr) if err != nil { return "", 0, err } n, err := strconv.ParseUint(port, 10, 16) if err != nil { return "", 0, err } return host, int(n), nil } // UsableAddrs returns all tcp addresses that we can bind a listener // to. func UsableAddrs() ([]*net.TCPAddr, error) { addrs, err := net.InterfaceAddrs() if err != nil { return nil, err } var usable []*net.TCPAddr for _, addr := range addrs { if ipNet, ok := addr.(*net.IPNet); ok { if !ipNet.IP.IsLinkLocalUnicast() { usable = append(usable, &net.TCPAddr{IP: ipNet.IP}) } } } if len(usable) == 0 { return nil, errors.New("no usable addresses found") } return usable, nil } const ( TypeHTTP = iota TypeTCP ) // Tunnel represents a single HTTP or TCP tunnel that can be served // by TunnelTest. type Tunnel struct { // Type specifies a tunnel type - either TypeHTTP (default) or TypeTCP. Type int // Handler is a handler to use for serving tunneled connections on // local server. The value of this field is required to be of type: // // - http.Handler or http.HandlerFunc for HTTP tunnels // - func(net.Conn) for TCP tunnels // // Required field. Handler interface{} // LocalAddr is a network address of local server that handles // connections/requests with Handler. // // Optional field, takes value of "127.0.0.1:0" when empty. LocalAddr string // ClientIdent is an identifier of a client that have already // registered a HTTP tunnel and have established control connection. // // If the Type is TypeTCP, instead of creating new client // for this TCP tunnel, we add it to an existing client // specified by the field. // // Optional field for TCP tunnels. // Ignored field for HTTP tunnels. ClientIdent string // RemoteAddr is a network address of remote server, which accepts // connections on a tunnel server side. // // Required field for TCP tunnels. // Ignored field for HTTP tunnels. RemoteAddr string // RemoteAddrIdent an identifier of an already existing listener, // that listens on multiple interfaces; if the RemoteAddrIdent is valid // identifier the IP field is required to be non-nil and RemoteAddr // is ignored. // // Optional field for TCP tunnels. // Ignored field for HTTP tunnels. RemoteAddrIdent string // IP specifies an IP address value for IP-based routing for TCP tunnels. // For more details see inline documentation for (*tunnel.Server).AddAddr. // // Optional field for TCP tunnels. // Ignored field for HTTP tunnels. IP net.IP // StateChanges listens on state transitions. // // If ClientIdent field is empty, the StateChanges will receive // state transition events for the newly created client. // Otherwise setting this field is a nop. StateChanges chan<- *tunnel.ClientStateChange } type TunnelTest struct { Server *tunnel.Server Clients map[string]*tunnel.Client Listeners map[string][2]net.Listener // [0] is local listener, [1] is remote one (for TCP tunnels) Addrs []*net.TCPAddr Tunnels map[string]*Tunnel DebugNet bool // for debugging network communication mu sync.Mutex // protects Listeners } func NewTunnelTest() (*TunnelTest, error) { cfg := &tunnel.ServerConfig{ Debug: testing.Verbose(), } s, err := tunnel.NewServer(cfg) if err != nil { return nil, err } l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return nil, err } if debugNet { l = dbgListener{l} } addrs, err := UsableAddrs() if err != nil { return nil, err } go (&http.Server{Handler: s}).Serve(l) return &TunnelTest{ Server: s, Clients: make(map[string]*tunnel.Client), Listeners: map[string][2]net.Listener{"": {l, nil}}, Addrs: addrs, Tunnels: make(map[string]*Tunnel), DebugNet: debugNet, }, nil } // Serve creates new TunnelTest that serves the given tunnels. // // If tunnels is nil, DefaultTunnels() are used instead. func Serve(tunnels map[string]*Tunnel) (*TunnelTest, error) { tt, err := NewTunnelTest() if err != nil { return nil, err } if err = tt.Serve(tunnels); err != nil { return nil, err } return tt, nil } func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { // Verify tunnel dependencies for TCP tunnels. if t.Type == TypeTCP { // If tunnel specified by t.Client was not already started, // skip and move on. if _, ok := tt.Clients[t.ClientIdent]; t.ClientIdent != "" && !ok { return false, nil } // Verify the TCP tunnel whose remote endpoint listens on multiple // interfaces is already served. if t.RemoteAddrIdent != "" { if _, ok := tt.Listeners[t.RemoteAddrIdent]; !ok { return false, nil } if tt.Tunnels[t.RemoteAddrIdent].Type != TypeTCP { return false, fmt.Errorf("expected tunnel %q to be of TCP type", t.RemoteAddrIdent) } } } l, err := net.Listen("tcp", t.LocalAddr) if err != nil { return false, fmt.Errorf("failed to listen on %q for %q tunnel: %s", t.LocalAddr, ident, err) } if tt.DebugNet { l = dbgListener{l} } cfg := &tunnel.ClientConfig{ Identifier: ident, ServerAddr: tt.ServerAddr().String(), LocalAddr: l.Addr().String(), FetchLocalAddr: tt.fetchLocalAddr, Debug: testing.Verbose(), StateChanges: t.StateChanges, } // Register tunnel: // // - start tunnel.Client (tt.Clients[ident]) or reuse existing one (tt.Clients[t.ExistingClient]) // - listen on local address and start local server (tt.Listeners[ident][0]) // - register tunnel on tunnel.Server // switch t.Type { case TypeHTTP: // TODO(rjeczalik): refactor to separate method h, ok := t.Handler.(http.Handler) if !ok { h, ok = t.Handler.(http.HandlerFunc) if !ok { fn, ok := t.Handler.(func(http.ResponseWriter, *http.Request)) if !ok { return false, fmt.Errorf("invalid handler type for %q tunnel: %T", ident, t.Handler) } h = http.HandlerFunc(fn) } } logf("serving on local %s for HTTP tunnel %q", l.Addr(), ident) go (&http.Server{Handler: h}).Serve(l) tt.Server.AddHost(cfg.LocalAddr, ident) tt.mu.Lock() tt.Listeners[ident] = [2]net.Listener{l, nil} tt.mu.Unlock() if err := tt.addClient(ident, cfg); err != nil { return false, fmt.Errorf("error creating client for %q tunnel: %s", ident, err) } logf("registered HTTP tunnel: host=%s, ident=%s", cfg.LocalAddr, ident) case TypeTCP: // TODO(rjeczalik): refactor to separate method h, ok := t.Handler.(func(net.Conn)) if !ok { return false, fmt.Errorf("invalid handler type for %q tunnel: %T", ident, t.Handler) } logf("serving on local %s for TCP tunnel %q", l.Addr(), ident) go func() { for { conn, err := l.Accept() if err != nil { log.Printf("failed accepting conn for %q tunnel: %s", ident, err) return } go h(conn) } }() var remote net.Listener if t.RemoteAddrIdent != "" { tt.mu.Lock() remote = tt.Listeners[t.RemoteAddrIdent][1] tt.mu.Unlock() } else { remote, err = net.Listen("tcp", t.RemoteAddr) if err != nil { return false, fmt.Errorf("failed to listen on %q for %q tunnel: %s", t.RemoteAddr, ident, err) } } // addrIdent holds identifier of client which is going to have registered // tunnel via (*tunnel.Server).AddAddr addrIdent := ident if t.ClientIdent != "" { tt.Clients[ident] = tt.Clients[t.ClientIdent] addrIdent = t.ClientIdent } tt.Server.AddAddr(remote, t.IP, addrIdent) tt.mu.Lock() tt.Listeners[ident] = [2]net.Listener{l, remote} tt.mu.Unlock() if _, ok := tt.Clients[ident]; !ok { if err := tt.addClient(ident, cfg); err != nil { return false, fmt.Errorf("error creating client for %q tunnel: %s", ident, err) } } logf("registered TCP tunnel: listener=%s, ip=%v, ident=%s", remote.Addr(), t.IP, addrIdent) default: return false, fmt.Errorf("unknown %q tunnel type: %d", ident, t.Type) } return true, nil } func (tt *TunnelTest) addClient(ident string, cfg *tunnel.ClientConfig) error { if _, ok := tt.Clients[ident]; ok { return fmt.Errorf("tunnel %q is already being served", ident) } c, err := tunnel.NewClient(cfg) if err != nil { return err } done := make(chan struct{}) tt.Server.OnConnect(ident, func() error { close(done) return nil }) go c.Start() <-c.StartNotify() select { case <-time.After(10 * time.Second): return errors.New("timed out after 10s waiting on client to establish control conn") case <-done: } tt.Clients[ident] = c return nil } func (tt *TunnelTest) Serve(tunnels map[string]*Tunnel) error { if len(tunnels) == 0 { return errors.New("no tunnels to serve") } // Since one tunnels depends on others do 3 passes to start them // all, each started tunnel is removed from the tunnels map. // After 3 passes all of them must be started, otherwise the // configuration is bad: // // - first pass starts HTTP tunnels as new client tunnels // - second pass starts TCP tunnels that rely on on already existing client tunnels (t.ClientIdent) // - third pass starts TCP tunnels that rely on on already existing TCP tunnels (t.RemoteAddrIdent) // for i := 0; i < 3; i++ { if err := tt.popServedDeps(tunnels); err != nil { return err } } if len(tunnels) != 0 { unresolved := make([]string, len(tunnels)) for ident := range tunnels { unresolved = append(unresolved, ident) } sort.Strings(unresolved) return fmt.Errorf("unable to start tunnels due to unresolved dependencies: %v", unresolved) } return nil } func (tt *TunnelTest) popServedDeps(tunnels map[string]*Tunnel) error { for ident, t := range tunnels { ok, err := tt.serveSingle(ident, t) if err != nil { return err } if ok { // Remove already started tunnels so they won't get started again. delete(tunnels, ident) tt.Tunnels[ident] = t } } return nil } func (tt *TunnelTest) fetchLocalAddr(port int) (string, error) { tt.mu.Lock() defer tt.mu.Unlock() for _, l := range tt.Listeners { if l[1] == nil { // this listener does not belong to a TCP tunnel continue } _, remotePort, err := parseHostPort(l[1].Addr().String()) if err != nil { return "", err } if port == remotePort { return l[0].Addr().String(), nil } } return "", fmt.Errorf("no route for %d port", port) } func (tt *TunnelTest) ServerAddr() net.Addr { return tt.Listeners[""][0].Addr() } // Addr gives server endpoint of the TCP tunnel for the given ident. // // If the tunnel does not exist or is a HTTP one, TunnelAddr return nil. func (tt *TunnelTest) Addr(ident string) net.Addr { l, ok := tt.Listeners[ident] if !ok { return nil } return l[1].Addr() } // Request creates a HTTP request to a server endpoint of the HTTP tunnel // for the given ident. // // If the tunnel does not exist, Request returns nil. func (tt *TunnelTest) Request(ident string, query url.Values) *http.Request { l, ok := tt.Listeners[ident] if !ok { return nil } var raw string if query != nil { raw = query.Encode() } return &http.Request{ Method: "GET", URL: &url.URL{ Scheme: "http", Host: tt.ServerAddr().String(), Path: "/", RawQuery: raw, }, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Host: l[0].Addr().String(), } } func (tt *TunnelTest) Close() (err error) { // Close tunnel.Clients. clients := make(map[*tunnel.Client]struct{}) for _, c := range tt.Clients { clients[c] = struct{}{} } for c := range clients { err = nonil(err, c.Close()) } // Stop all TCP/HTTP servers. listeners := make(map[net.Listener]struct{}) for _, l := range tt.Listeners { for _, l := range l { if l != nil { listeners[l] = struct{}{} } } } for l := range listeners { err = nonil(err, l.Close()) } return err }
[ "\"DEBUGNET\"" ]
[]
[ "DEBUGNET" ]
[]
["DEBUGNET"]
go
1
0
contrib/spendfrom/spendfrom.py
#!/usr/bin/env python # # Use the raw transactions API to spend LYRAs received on particular addresses, # and lyra any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a lyrad or lyra-Qt running # on localhost. # # Depends on jsonrpc # from decimal import * import getpass import math import os import os.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the lyra data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/LYRA/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "LYRA") return os.path.expanduser("~/.lyra") def read_bitcoin_config(dbdir): """Read the lyra.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "lyra.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a lyra JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 51475 if testnet else 50051 connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so lyra an RPC command mostly to catch connection errors, # but also make sure the lyrad we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(lyrad): info = lyrad.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") lyrad.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = lyrad.getinfo() return int(info['unlocked_until']) > time.time() def list_available(lyrad): address_summary = dict() address_to_account = dict() for info in lyrad.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = lyrad.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = lyrad.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-lyra-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs: outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed) def create_tx(lyrad, fromaddresses, toaddress, amount, fee): all_coins = list_available(lyrad) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before lyraing them to lyrad. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = lyrad.createrawtransaction(inputs, outputs) signed_rawtx = lyrad.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(lyrad, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = lyrad.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(lyrad, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = lyrad.decoderawtransaction(txdata_hex) total_in = compute_amount_in(lyrad, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get LYRAs from") parser.add_option("--to", dest="to", default=None, help="address to get lyra LYRAs to") parser.add_option("--amount", dest="amount", default=None, help="amount to lyra") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of lyra.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options, args) = parser.parse_args() check_json_precision() config = read_bitcoin_config(options.datadir) if options.testnet: config['testnet'] = True lyrad = connect_JSON(config) if options.amount is None: address_summary = list_available(lyrad) for address,info in address_summary.iteritems(): n_transactions = len(info['outputs']) if n_transactions > 1: print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions)) else: print("%s %.8f %s"%(address, info['total'], info['account'])) else: fee = Decimal(options.fee) amount = Decimal(options.amount) while unlock_wallet(lyrad) == False: pass # Keep asking for passphrase until they get it right txdata = create_tx(lyrad, options.fromaddresses.split(","), options.to, amount, fee) sanity_test_fee(lyrad, txdata, amount*Decimal("0.01")) if options.dry_run: print(txdata) else: txid = lyrad.lyrarawtransaction(txdata) print(txid) if __name__ == '__main__': main()
[]
[]
[ "APPDATA" ]
[]
["APPDATA"]
python
1
0
util/clissh/ssh_test.go
// +build !windows,!386 // skipping 386 because lager uses UInt64 in Session() // skipping windows because Unix/Linux only syscall in test. // should refactor out the conflicts so we could test this package in multi platforms. package clissh_test import ( "errors" "fmt" "io" "net" "os" "sync" "syscall" "time" "code.cloudfoundry.org/cli/util/clissh/clisshfakes" "code.cloudfoundry.org/cli/util/clissh/ssherror" "code.cloudfoundry.org/diego-ssh/server" fake_server "code.cloudfoundry.org/diego-ssh/server/fakes" "code.cloudfoundry.org/diego-ssh/test_helpers" "code.cloudfoundry.org/diego-ssh/test_helpers/fake_io" "code.cloudfoundry.org/diego-ssh/test_helpers/fake_net" "code.cloudfoundry.org/diego-ssh/test_helpers/fake_ssh" "code.cloudfoundry.org/lager/lagertest" "github.com/kr/pty" "github.com/moby/moby/pkg/term" "golang.org/x/crypto/ssh" . "code.cloudfoundry.org/cli/util/clissh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func BlockAcceptOnClose(fake *fake_net.FakeListener) { waitUntilClosed := make(chan bool) fake.AcceptStub = func() (net.Conn, error) { <-waitUntilClosed return nil, errors.New("banana") } var once sync.Once fake.CloseStub = func() error { once.Do(func() { close(waitUntilClosed) }) return nil } } var _ = Describe("CLI SSH", func() { var ( fakeSecureDialer *clisshfakes.FakeSecureDialer fakeSecureClient *clisshfakes.FakeSecureClient fakeTerminalHelper *clisshfakes.FakeTerminalHelper fakeListenerFactory *clisshfakes.FakeListenerFactory fakeSecureSession *clisshfakes.FakeSecureSession fakeConnection *fake_ssh.FakeConn stdinPipe *fake_io.FakeWriteCloser stdoutPipe *fake_io.FakeReader stderrPipe *fake_io.FakeReader secureShell *SecureShell username string passcode string sshEndpoint string sshEndpointFingerprint string skipHostValidation bool commands []string terminalRequest TTYRequest keepAliveDuration time.Duration ) BeforeEach(func() { fakeSecureDialer = new(clisshfakes.FakeSecureDialer) fakeSecureClient = new(clisshfakes.FakeSecureClient) fakeTerminalHelper = new(clisshfakes.FakeTerminalHelper) fakeListenerFactory = new(clisshfakes.FakeListenerFactory) fakeSecureSession = new(clisshfakes.FakeSecureSession) fakeConnection = new(fake_ssh.FakeConn) stdinPipe = new(fake_io.FakeWriteCloser) stdoutPipe = new(fake_io.FakeReader) stderrPipe = new(fake_io.FakeReader) fakeListenerFactory.ListenStub = net.Listen fakeSecureClient.NewSessionReturns(fakeSecureSession, nil) fakeSecureClient.ConnReturns(fakeConnection) fakeSecureDialer.DialReturns(fakeSecureClient, nil) stdinPipe.WriteStub = func(p []byte) (int, error) { return len(p), nil } fakeSecureSession.StdinPipeReturns(stdinPipe, nil) stdoutPipe.ReadStub = func(p []byte) (int, error) { return 0, io.EOF } fakeSecureSession.StdoutPipeReturns(stdoutPipe, nil) stderrPipe.ReadStub = func(p []byte) (int, error) { return 0, io.EOF } fakeSecureSession.StderrPipeReturns(stderrPipe, nil) username = "some-user" passcode = "some-passcode" sshEndpoint = "some-endpoint" sshEndpointFingerprint = "some-fingerprint" skipHostValidation = false commands = []string{} terminalRequest = RequestTTYAuto keepAliveDuration = DefaultKeepAliveInterval }) JustBeforeEach(func() { secureShell = NewSecureShell( fakeSecureDialer, fakeTerminalHelper, fakeListenerFactory, keepAliveDuration, ) }) Describe("Connect", func() { var connectErr error JustBeforeEach(func() { connectErr = secureShell.Connect(username, passcode, sshEndpoint, sshEndpointFingerprint, skipHostValidation) }) When("dialing succeeds", func() { It("creates the ssh client", func() { Expect(connectErr).ToNot(HaveOccurred()) Expect(fakeSecureDialer.DialCallCount()).To(Equal(1)) protocolArg, sshEndpointArg, sshConfigArg := fakeSecureDialer.DialArgsForCall(0) Expect(protocolArg).To(Equal("tcp")) Expect(sshEndpointArg).To(Equal(sshEndpoint)) Expect(sshConfigArg.User).To(Equal(username)) Expect(sshConfigArg.Auth).To(HaveLen(1)) Expect(sshConfigArg.HostKeyCallback).ToNot(BeNil()) }) }) When("dialing fails", func() { var dialError error When("the error is a generic Dial error", func() { BeforeEach(func() { dialError = errors.New("woops") fakeSecureDialer.DialReturns(nil, dialError) }) It("returns the dial error", func() { Expect(connectErr).To(Equal(dialError)) Expect(fakeSecureDialer.DialCallCount()).To(Equal(1)) }) }) When("the dialing error is a golang 'unable to authenticate' error", func() { BeforeEach(func() { dialError = fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", []string{"none", "password"}) fakeSecureDialer.DialReturns(nil, dialError) }) It("returns an UnableToAuthenticateError", func() { Expect(connectErr).To(MatchError(ssherror.UnableToAuthenticateError{Err: dialError})) Expect(fakeSecureDialer.DialCallCount()).To(Equal(1)) }) }) }) }) Describe("InteractiveSession", func() { var ( stdin *fake_io.FakeReadCloser stdout, stderr *fake_io.FakeWriter sessionErr error interactiveSessionInvoker func(secureShell *SecureShell) ) BeforeEach(func() { stdin = new(fake_io.FakeReadCloser) stdout = new(fake_io.FakeWriter) stderr = new(fake_io.FakeWriter) fakeTerminalHelper.StdStreamsReturns(stdin, stdout, stderr) interactiveSessionInvoker = func(secureShell *SecureShell) { sessionErr = secureShell.InteractiveSession(commands, terminalRequest) } }) JustBeforeEach(func() { connectErr := secureShell.Connect(username, passcode, sshEndpoint, sshEndpointFingerprint, skipHostValidation) Expect(connectErr).NotTo(HaveOccurred()) interactiveSessionInvoker(secureShell) }) When("host key validation is enabled", func() { var ( callback func(hostname string, remote net.Addr, key ssh.PublicKey) error addr net.Addr ) BeforeEach(func() { skipHostValidation = false }) JustBeforeEach(func() { Expect(fakeSecureDialer.DialCallCount()).To(Equal(1)) _, _, config := fakeSecureDialer.DialArgsForCall(0) callback = config.HostKeyCallback listener, err := net.Listen("tcp", "localhost:0") Expect(err).NotTo(HaveOccurred()) addr = listener.Addr() listener.Close() }) When("the md5 fingerprint matches", func() { BeforeEach(func() { sshEndpointFingerprint = "41:ce:56:e6:9c:42:a9:c6:9e:68:ac:e3:4d:f6:38:79" }) It("does not return an error", func() { Expect(callback("", addr, TestHostKey.PublicKey())).ToNot(HaveOccurred()) }) }) When("the hex sha1 fingerprint matches", func() { BeforeEach(func() { sshEndpointFingerprint = "a8:e2:67:cb:ea:2a:6e:23:a1:72:ce:8f:07:92:15:ee:1f:82:f8:ca" }) It("does not return an error", func() { Expect(callback("", addr, TestHostKey.PublicKey())).ToNot(HaveOccurred()) }) }) When("the base64 sha256 fingerprint matches", func() { BeforeEach(func() { sshEndpointFingerprint = "sp/jrLuj66r+yrLDUKZdJU5tdzt4mq/UaSiNBjpgr+8" }) It("does not return an error", func() { Expect(callback("", addr, TestHostKey.PublicKey())).ToNot(HaveOccurred()) }) }) When("the base64 SHA256 fingerprint does not match", func() { BeforeEach(func() { sshEndpointFingerprint = "0000000000000000000000000000000000000000000" }) It("returns an error'", func() { err := callback("", addr, TestHostKey.PublicKey()) Expect(err).To(MatchError(MatchRegexp("Host key verification failed\\."))) Expect(err).To(MatchError(MatchRegexp("The fingerprint of the received key was \".*\""))) }) }) When("the hex SHA1 fingerprint does not match", func() { BeforeEach(func() { sshEndpointFingerprint = "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00" }) It("returns an error'", func() { err := callback("", addr, TestHostKey.PublicKey()) Expect(err).To(MatchError(MatchRegexp("Host key verification failed\\."))) Expect(err).To(MatchError(MatchRegexp("The fingerprint of the received key was \".*\""))) }) }) When("the MD5 fingerprint does not match", func() { BeforeEach(func() { sshEndpointFingerprint = "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00" }) It("returns an error'", func() { err := callback("", addr, TestHostKey.PublicKey()) Expect(err).To(MatchError(MatchRegexp("Host key verification failed\\."))) Expect(err).To(MatchError(MatchRegexp("The fingerprint of the received key was \".*\""))) }) }) When("no fingerprint is present in endpoint info", func() { BeforeEach(func() { sshEndpointFingerprint = "" sshEndpoint = "" }) It("returns an error'", func() { err := callback("", addr, TestHostKey.PublicKey()) Expect(err).To(MatchError(MatchRegexp("Unable to verify identity of host\\."))) Expect(err).To(MatchError(MatchRegexp("The fingerprint of the received key was \".*\""))) }) }) When("the fingerprint length doesn't make sense", func() { BeforeEach(func() { sshEndpointFingerprint = "garbage" }) It("returns an error", func() { err := callback("", addr, TestHostKey.PublicKey()) Eventually(err).Should(MatchError(MatchRegexp("Unsupported host key fingerprint format"))) }) }) }) When("the skip host validation flag is set", func() { BeforeEach(func() { skipHostValidation = true }) It("the HostKeyCallback on the Config to always return nil", func() { Expect(fakeSecureDialer.DialCallCount()).To(Equal(1)) _, _, config := fakeSecureDialer.DialArgsForCall(0) Expect(config.HostKeyCallback("some-hostname", nil, nil)).To(BeNil()) }) }) // TODO: see if it's possible to test the piping between the ss client input and outputs and the UI object we pass in When("dialing is successful", func() { It("creates a new secure shell session", func() { Expect(fakeSecureClient.NewSessionCallCount()).To(Equal(1)) }) It("closes the session", func() { Expect(fakeSecureSession.CloseCallCount()).To(Equal(1)) }) It("gets a stdin pipe for the session", func() { Expect(fakeSecureSession.StdinPipeCallCount()).To(Equal(1)) }) When("getting the stdin pipe fails", func() { BeforeEach(func() { fakeSecureSession.StdinPipeReturns(nil, errors.New("woops")) }) It("returns the error", func() { Expect(sessionErr).Should(MatchError("woops")) }) }) It("gets a stdout pipe for the session", func() { Expect(fakeSecureSession.StdoutPipeCallCount()).To(Equal(1)) }) When("getting the stdout pipe fails", func() { BeforeEach(func() { fakeSecureSession.StdoutPipeReturns(nil, errors.New("woops")) }) It("returns the error", func() { Expect(sessionErr).Should(MatchError("woops")) }) }) It("gets a stderr pipe for the session", func() { Expect(fakeSecureSession.StderrPipeCallCount()).To(Equal(1)) }) When("getting the stderr pipe fails", func() { BeforeEach(func() { fakeSecureSession.StderrPipeReturns(nil, errors.New("woops")) }) It("returns the error", func() { Expect(sessionErr).Should(MatchError("woops")) }) }) }) When("stdin is a terminal", func() { var master, slave *os.File BeforeEach(func() { var err error master, slave, err = pty.Open() Expect(err).NotTo(HaveOccurred()) terminalRequest = RequestTTYForce terminalHelper := DefaultTerminalHelper() fakeTerminalHelper.GetFdInfoStub = terminalHelper.GetFdInfo fakeTerminalHelper.GetWinsizeStub = terminalHelper.GetWinsize }) AfterEach(func() { master.Close() // slave.Close() // race }) When("a command is not specified", func() { var terminalType string BeforeEach(func() { terminalType = os.Getenv("TERM") os.Setenv("TERM", "test-terminal-type") winsize := &term.Winsize{Width: 1024, Height: 256} fakeTerminalHelper.GetWinsizeReturns(winsize, nil) fakeSecureSession.ShellStub = func() error { Expect(fakeTerminalHelper.SetRawTerminalCallCount()).To(Equal(1)) Expect(fakeTerminalHelper.RestoreTerminalCallCount()).To(Equal(0)) return nil } }) AfterEach(func() { os.Setenv("TERM", terminalType) }) It("requests a pty with the correct terminal type, window size, and modes", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(1)) Expect(fakeTerminalHelper.GetWinsizeCallCount()).To(Equal(1)) termType, height, width, modes := fakeSecureSession.RequestPtyArgsForCall(0) Expect(termType).To(Equal("test-terminal-type")) Expect(height).To(Equal(256)) Expect(width).To(Equal(1024)) expectedModes := ssh.TerminalModes{ ssh.ECHO: 1, ssh.TTY_OP_ISPEED: 115200, ssh.TTY_OP_OSPEED: 115200, } Expect(modes).To(Equal(expectedModes)) }) When("the TERM environment variable is not set", func() { BeforeEach(func() { os.Unsetenv("TERM") }) It("requests a pty with the default terminal type", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(1)) termType, _, _, _ := fakeSecureSession.RequestPtyArgsForCall(0) Expect(termType).To(Equal("xterm")) }) }) It("puts the terminal into raw mode and restores it after running the shell", func() { Expect(fakeSecureSession.ShellCallCount()).To(Equal(1)) Expect(fakeTerminalHelper.SetRawTerminalCallCount()).To(Equal(1)) Expect(fakeTerminalHelper.RestoreTerminalCallCount()).To(Equal(1)) }) When("the pty allocation fails", func() { var ptyError error BeforeEach(func() { ptyError = errors.New("pty allocation error") fakeSecureSession.RequestPtyReturns(ptyError) }) It("returns the error", func() { Expect(sessionErr).To(Equal(ptyError)) }) }) When("placing the terminal into raw mode fails", func() { BeforeEach(func() { fakeTerminalHelper.SetRawTerminalReturns(nil, errors.New("woops")) }) It("keeps calm and carries on", func() { Expect(fakeSecureSession.ShellCallCount()).To(Equal(1)) }) It("does not not restore the terminal", func() { Expect(fakeSecureSession.ShellCallCount()).To(Equal(1)) Expect(fakeTerminalHelper.SetRawTerminalCallCount()).To(Equal(1)) Expect(fakeTerminalHelper.RestoreTerminalCallCount()).To(Equal(0)) }) }) }) When("a command is specified", func() { BeforeEach(func() { commands = []string{"echo", "-n", "hello"} }) When("a terminal is requested", func() { BeforeEach(func() { terminalRequest = RequestTTYYes fakeTerminalHelper.GetFdInfoReturns(0, true) }) It("requests a pty", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(1)) }) }) When("a terminal is not explicitly requested", func() { BeforeEach(func() { terminalRequest = RequestTTYAuto }) It("does not request a pty", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(0)) }) }) }) }) When("stdin is not a terminal", func() { BeforeEach(func() { stdin.ReadStub = func(p []byte) (int, error) { return 0, io.EOF } terminalHelper := DefaultTerminalHelper() fakeTerminalHelper.GetFdInfoStub = terminalHelper.GetFdInfo fakeTerminalHelper.GetWinsizeStub = terminalHelper.GetWinsize }) When("a terminal is not requested", func() { It("does not request a pty", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(0)) }) }) When("a terminal is requested", func() { BeforeEach(func() { terminalRequest = RequestTTYYes }) It("does not request a pty", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(0)) }) }) }) PWhen("a terminal is forced", func() { BeforeEach(func() { terminalRequest = RequestTTYForce }) It("requests a pty", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(1)) }) }) When("a terminal is disabled", func() { BeforeEach(func() { terminalRequest = RequestTTYNo }) It("does not request a pty", func() { Expect(fakeSecureSession.RequestPtyCallCount()).To(Equal(0)) }) }) When("a command is not specified", func() { It("requests an interactive shell", func() { Expect(fakeSecureSession.ShellCallCount()).To(Equal(1)) }) When("the shell request returns an error", func() { BeforeEach(func() { fakeSecureSession.ShellReturns(errors.New("oh bother")) }) It("returns the error", func() { Expect(sessionErr).To(MatchError("oh bother")) }) }) }) When("a command is specifed", func() { BeforeEach(func() { commands = []string{"echo", "-n", "hello"} }) It("starts the command", func() { Expect(fakeSecureSession.StartCallCount()).To(Equal(1)) Expect(fakeSecureSession.StartArgsForCall(0)).To(Equal("echo -n hello")) }) When("the command fails to start", func() { BeforeEach(func() { fakeSecureSession.StartReturns(errors.New("oh well")) }) It("returns the error", func() { Expect(sessionErr).To(MatchError("oh well")) }) }) }) When("the shell or command has started", func() { BeforeEach(func() { stdin.ReadStub = func(p []byte) (int, error) { p[0] = 0 return 1, io.EOF } stdinPipe.WriteStub = func(p []byte) (int, error) { defer GinkgoRecover() Expect(p[0]).To(Equal(byte(0))) return 1, nil } stdoutPipe.ReadStub = func(p []byte) (int, error) { p[0] = 1 return 1, io.EOF } stdout.WriteStub = func(p []byte) (int, error) { defer GinkgoRecover() Expect(p[0]).To(Equal(byte(1))) return 1, nil } stderrPipe.ReadStub = func(p []byte) (int, error) { p[0] = 2 return 1, io.EOF } stderr.WriteStub = func(p []byte) (int, error) { defer GinkgoRecover() Expect(p[0]).To(Equal(byte(2))) return 1, nil } fakeSecureSession.StdinPipeReturns(stdinPipe, nil) fakeSecureSession.StdoutPipeReturns(stdoutPipe, nil) fakeSecureSession.StderrPipeReturns(stderrPipe, nil) fakeSecureSession.WaitReturns(errors.New("error result")) }) It("copies data from the stdin stream to the session stdin pipe", func() { Eventually(stdin.ReadCallCount).Should(Equal(1)) Eventually(stdinPipe.WriteCallCount).Should(Equal(1)) }) It("copies data from the session stdout pipe to the stdout stream", func() { Eventually(stdoutPipe.ReadCallCount).Should(Equal(1)) Eventually(stdout.WriteCallCount).Should(Equal(1)) }) It("copies data from the session stderr pipe to the stderr stream", func() { Eventually(stderrPipe.ReadCallCount).Should(Equal(1)) Eventually(stderr.WriteCallCount).Should(Equal(1)) }) It("waits for the session to end", func() { Expect(fakeSecureSession.WaitCallCount()).To(Equal(1)) }) It("returns the result from wait", func() { Expect(sessionErr).To(MatchError("error result")) }) When("the session terminates before stream copies complete", func() { var sessionErrorCh chan error BeforeEach(func() { sessionErrorCh = make(chan error, 1) interactiveSessionInvoker = func(secureShell *SecureShell) { go func() { sessionErrorCh <- secureShell.InteractiveSession(commands, terminalRequest) }() } stdoutPipe.ReadStub = func(p []byte) (int, error) { defer GinkgoRecover() Eventually(fakeSecureSession.WaitCallCount).Should(Equal(1)) Consistently(sessionErrorCh).ShouldNot(Receive()) p[0] = 1 return 1, io.EOF } stderrPipe.ReadStub = func(p []byte) (int, error) { defer GinkgoRecover() Eventually(fakeSecureSession.WaitCallCount).Should(Equal(1)) Consistently(sessionErrorCh).ShouldNot(Receive()) p[0] = 2 return 1, io.EOF } }) It("waits for the copies to complete", func() { Eventually(sessionErrorCh).Should(Receive()) Expect(stdoutPipe.ReadCallCount()).To(Equal(1)) Expect(stderrPipe.ReadCallCount()).To(Equal(1)) }) }) When("stdin is closed", func() { BeforeEach(func() { stdin.ReadStub = func(p []byte) (int, error) { defer GinkgoRecover() Consistently(stdinPipe.CloseCallCount).Should(Equal(0)) p[0] = 0 return 1, io.EOF } }) It("closes the stdinPipe", func() { Eventually(stdinPipe.CloseCallCount).Should(Equal(1)) }) }) }) When("stdout is a terminal and a window size change occurs", func() { var master, slave *os.File BeforeEach(func() { var err error master, slave, err = pty.Open() Expect(err).NotTo(HaveOccurred()) terminalHelper := DefaultTerminalHelper() fakeTerminalHelper.GetFdInfoStub = terminalHelper.GetFdInfo fakeTerminalHelper.GetWinsizeStub = terminalHelper.GetWinsize fakeTerminalHelper.StdStreamsReturns(stdin, slave, stderr) winsize := &term.Winsize{Height: 100, Width: 100} err = term.SetWinsize(slave.Fd(), winsize) Expect(err).NotTo(HaveOccurred()) fakeSecureSession.WaitStub = func() error { fakeSecureSession.SendRequestCallCount() Expect(fakeSecureSession.SendRequestCallCount()).To(Equal(0)) // No dimension change for i := 0; i < 3; i++ { winsize := &term.Winsize{Height: 100, Width: 100} err = term.SetWinsize(slave.Fd(), winsize) Expect(err).NotTo(HaveOccurred()) } winsize := &term.Winsize{Height: 100, Width: 200} err = term.SetWinsize(slave.Fd(), winsize) Expect(err).NotTo(HaveOccurred()) err = syscall.Kill(syscall.Getpid(), syscall.SIGWINCH) Expect(err).NotTo(HaveOccurred()) Eventually(fakeSecureSession.SendRequestCallCount).Should(Equal(1)) return nil } }) AfterEach(func() { master.Close() slave.Close() }) It("sends window change events when the window dimensions change", func() { Expect(fakeSecureSession.SendRequestCallCount()).To(Equal(1)) requestType, wantReply, message := fakeSecureSession.SendRequestArgsForCall(0) Expect(requestType).To(Equal("window-change")) Expect(wantReply).To(BeFalse()) type resizeMessage struct { Width uint32 Height uint32 PixelWidth uint32 PixelHeight uint32 } var resizeMsg resizeMessage err := ssh.Unmarshal(message, &resizeMsg) Expect(err).NotTo(HaveOccurred()) Expect(resizeMsg).To(Equal(resizeMessage{Height: 100, Width: 200})) }) }) Describe("keep alive messages", func() { var times []time.Time var timesCh chan []time.Time var done chan struct{} BeforeEach(func() { keepAliveDuration = 100 * time.Millisecond times = []time.Time{} timesCh = make(chan []time.Time, 1) done = make(chan struct{}, 1) fakeConnection.SendRequestStub = func(reqName string, wantReply bool, message []byte) (bool, []byte, error) { Expect(reqName).To(Equal("[email protected]")) Expect(wantReply).To(BeTrue()) Expect(message).To(BeNil()) times = append(times, time.Now()) if len(times) == 3 { timesCh <- times close(done) } return true, nil, nil } fakeSecureSession.WaitStub = func() error { Eventually(done).Should(BeClosed()) return nil } }) PIt("sends keep alive messages at the expected interval", func() { times := <-timesCh Expect(times[2]).To(BeTemporally("~", times[0].Add(200*time.Millisecond), 160*time.Millisecond)) }) }) }) Describe("LocalPortForward", func() { var ( forwardErr error echoAddress string echoListener *fake_net.FakeListener echoHandler *fake_server.FakeConnectionHandler echoServer *server.Server localAddress string realLocalListener net.Listener fakeLocalListener *fake_net.FakeListener forwardSpecs []LocalPortForward ) BeforeEach(func() { logger := lagertest.NewTestLogger("test") var err error realLocalListener, err = net.Listen("tcp", "127.0.0.1:0") Expect(err).NotTo(HaveOccurred()) localAddress = realLocalListener.Addr().String() fakeListenerFactory.ListenReturns(realLocalListener, nil) echoHandler = new(fake_server.FakeConnectionHandler) echoHandler.HandleConnectionStub = func(conn net.Conn) { io.Copy(conn, conn) conn.Close() } realListener, err := net.Listen("tcp", "127.0.0.1:0") Expect(err).NotTo(HaveOccurred()) echoAddress = realListener.Addr().String() echoListener = new(fake_net.FakeListener) echoListener.AcceptStub = realListener.Accept echoListener.CloseStub = realListener.Close echoListener.AddrStub = realListener.Addr fakeLocalListener = new(fake_net.FakeListener) fakeLocalListener.AcceptReturns(nil, errors.New("Not Accepting Connections")) echoServer = server.NewServer(logger.Session("echo"), "", echoHandler) echoServer.SetListener(echoListener) go echoServer.Serve() forwardSpecs = []LocalPortForward{{ RemoteAddress: echoAddress, LocalAddress: localAddress, }} fakeSecureClient.DialStub = net.Dial }) JustBeforeEach(func() { connectErr := secureShell.Connect(username, passcode, sshEndpoint, sshEndpointFingerprint, skipHostValidation) Expect(connectErr).NotTo(HaveOccurred()) forwardErr = secureShell.LocalPortForward(forwardSpecs) }) AfterEach(func() { err := secureShell.Close() Expect(err).NotTo(HaveOccurred()) echoServer.Shutdown() realLocalListener.Close() }) validateConnectivity := func(addr string) { conn, err := net.Dial("tcp", addr) Expect(err).NotTo(HaveOccurred()) msg := fmt.Sprintf("Hello from %s\n", addr) n, err := conn.Write([]byte(msg)) Expect(err).NotTo(HaveOccurred()) Expect(n).To(Equal(len(msg))) response := make([]byte, len(msg)) n, err = conn.Read(response) Expect(err).NotTo(HaveOccurred()) Expect(n).To(Equal(len(msg))) err = conn.Close() Expect(err).NotTo(HaveOccurred()) Expect(response).To(Equal([]byte(msg))) } It("dials the connect address when a local connection is made", func() { Expect(forwardErr).NotTo(HaveOccurred()) conn, err := net.Dial("tcp", localAddress) Expect(err).NotTo(HaveOccurred()) Eventually(echoListener.AcceptCallCount).Should(BeNumerically(">=", 1)) Eventually(fakeSecureClient.DialCallCount).Should(Equal(1)) network, addr := fakeSecureClient.DialArgsForCall(0) Expect(network).To(Equal("tcp")) Expect(addr).To(Equal(echoAddress)) Expect(conn.Close()).NotTo(HaveOccurred()) }) It("copies data between the local and remote connections", func() { validateConnectivity(localAddress) }) When("a local connection is already open", func() { var conn net.Conn JustBeforeEach(func() { var err error conn, err = net.Dial("tcp", localAddress) Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { err := conn.Close() Expect(err).NotTo(HaveOccurred()) }) It("allows for new incoming connections as well", func() { validateConnectivity(localAddress) }) }) When("there are multiple port forward specs", func() { When("provided a real listener", func() { var ( realLocalListener2 net.Listener localAddress2 string ) BeforeEach(func() { var err error realLocalListener2, err = net.Listen("tcp", "127.0.0.1:0") Expect(err).NotTo(HaveOccurred()) localAddress2 = realLocalListener2.Addr().String() fakeListenerFactory.ListenStub = func(network, addr string) (net.Listener, error) { if addr == localAddress { return realLocalListener, nil } if addr == localAddress2 { return realLocalListener2, nil } return nil, errors.New("unexpected address") } forwardSpecs = []LocalPortForward{ { RemoteAddress: echoAddress, LocalAddress: localAddress, }, { RemoteAddress: echoAddress, LocalAddress: localAddress2, }, } }) AfterEach(func() { realLocalListener2.Close() }) It("listens to all the things", func() { Eventually(fakeListenerFactory.ListenCallCount).Should(Equal(2)) network, addr := fakeListenerFactory.ListenArgsForCall(0) Expect(network).To(Equal("tcp")) Expect(addr).To(Equal(localAddress)) network, addr = fakeListenerFactory.ListenArgsForCall(1) Expect(network).To(Equal("tcp")) Expect(addr).To(Equal(localAddress2)) }) It("forwards to the correct target", func() { validateConnectivity(localAddress) validateConnectivity(localAddress2) }) }) When("the secure client is closed", func() { var ( fakeLocalListener1 *fake_net.FakeListener fakeLocalListener2 *fake_net.FakeListener ) BeforeEach(func() { forwardSpecs = []LocalPortForward{ { RemoteAddress: echoAddress, LocalAddress: localAddress, }, { RemoteAddress: echoAddress, LocalAddress: localAddress, }, } fakeLocalListener1 = new(fake_net.FakeListener) BlockAcceptOnClose(fakeLocalListener1) fakeListenerFactory.ListenReturnsOnCall(0, fakeLocalListener1, nil) fakeLocalListener2 = new(fake_net.FakeListener) BlockAcceptOnClose(fakeLocalListener2) fakeListenerFactory.ListenReturnsOnCall(1, fakeLocalListener2, nil) }) It("closes the listeners", func() { Eventually(fakeListenerFactory.ListenCallCount).Should(Equal(2)) Eventually(fakeLocalListener1.AcceptCallCount).Should(Equal(1)) Eventually(fakeLocalListener2.AcceptCallCount).Should(Equal(1)) err := secureShell.Close() Expect(err).NotTo(HaveOccurred()) Eventually(fakeLocalListener1.CloseCallCount).Should(Equal(2)) Eventually(fakeLocalListener2.CloseCallCount).Should(Equal(2)) }) }) }) When("listen fails", func() { BeforeEach(func() { fakeListenerFactory.ListenReturns(nil, errors.New("failure is an option")) }) It("returns the error", func() { Expect(forwardErr).To(MatchError("failure is an option")) }) }) When("the client it closed", func() { BeforeEach(func() { fakeLocalListener = new(fake_net.FakeListener) BlockAcceptOnClose(fakeLocalListener) fakeListenerFactory.ListenReturns(fakeLocalListener, nil) }) It("closes the listener when the client is closed", func() { Eventually(fakeListenerFactory.ListenCallCount).Should(Equal(1)) Eventually(fakeLocalListener.AcceptCallCount).Should(Equal(1)) err := secureShell.Close() Expect(err).NotTo(HaveOccurred()) Eventually(fakeLocalListener.CloseCallCount).Should(Equal(2)) }) }) When("accept fails", func() { var fakeConn *fake_net.FakeConn BeforeEach(func() { fakeConn = &fake_net.FakeConn{} fakeConn.ReadReturns(0, io.EOF) fakeListenerFactory.ListenReturns(fakeLocalListener, nil) }) Context("with a permanent error", func() { BeforeEach(func() { fakeLocalListener.AcceptReturns(nil, errors.New("boom")) }) It("stops trying to accept connections", func() { Eventually(fakeLocalListener.AcceptCallCount).Should(Equal(1)) Consistently(fakeLocalListener.AcceptCallCount).Should(Equal(1)) Expect(fakeLocalListener.CloseCallCount()).To(Equal(1)) }) }) Context("with a temporary error", func() { var timeCh chan time.Time BeforeEach(func() { timeCh = make(chan time.Time, 3) fakeLocalListener.AcceptStub = func() (net.Conn, error) { timeCh := timeCh if fakeLocalListener.AcceptCallCount() > 3 { close(timeCh) return nil, test_helpers.NewTestNetError(false, false) } else { timeCh <- time.Now() return nil, test_helpers.NewTestNetError(false, true) } } }) PIt("retries connecting after a short delay", func() { Eventually(fakeLocalListener.AcceptCallCount).Should(Equal(3)) Expect(timeCh).To(HaveLen(3)) times := make([]time.Time, 0) for t := range timeCh { times = append(times, t) } Expect(times[1]).To(BeTemporally("~", times[0].Add(115*time.Millisecond), 80*time.Millisecond)) Expect(times[2]).To(BeTemporally("~", times[1].Add(115*time.Millisecond), 100*time.Millisecond)) }) }) }) When("dialing the connect address fails", func() { var fakeTarget *fake_net.FakeConn BeforeEach(func() { fakeTarget = &fake_net.FakeConn{} fakeSecureClient.DialReturns(fakeTarget, errors.New("boom")) }) It("does not call close on the target connection", func() { Consistently(fakeTarget.CloseCallCount).Should(Equal(0)) }) }) }) Describe("Wait", func() { var waitErr error JustBeforeEach(func() { connectErr := secureShell.Connect(username, passcode, sshEndpoint, sshEndpointFingerprint, skipHostValidation) Expect(connectErr).NotTo(HaveOccurred()) waitErr = secureShell.Wait() }) It("calls wait on the secureClient", func() { Expect(waitErr).NotTo(HaveOccurred()) Expect(fakeSecureClient.WaitCallCount()).To(Equal(1)) }) Describe("keep alive messages", func() { var times []time.Time var timesCh chan []time.Time var done chan struct{} BeforeEach(func() { keepAliveDuration = 100 * time.Millisecond times = []time.Time{} timesCh = make(chan []time.Time, 1) done = make(chan struct{}, 1) fakeConnection.SendRequestStub = func(reqName string, wantReply bool, message []byte) (bool, []byte, error) { Expect(reqName).To(Equal("[email protected]")) Expect(wantReply).To(BeTrue()) Expect(message).To(BeNil()) times = append(times, time.Now()) if len(times) == 3 { timesCh <- times close(done) } return true, nil, nil } fakeSecureClient.WaitStub = func() error { Eventually(done).Should(BeClosed()) return nil } }) PIt("sends keep alive messages at the expected interval", func() { Expect(waitErr).NotTo(HaveOccurred()) times := <-timesCh Expect(times[2]).To(BeTemporally("~", times[0].Add(200*time.Millisecond), 100*time.Millisecond)) }) }) }) Describe("Close", func() { JustBeforeEach(func() { connectErr := secureShell.Connect(username, passcode, sshEndpoint, sshEndpointFingerprint, skipHostValidation) Expect(connectErr).NotTo(HaveOccurred()) }) It("calls close on the secureClient", func() { err := secureShell.Close() Expect(err).NotTo(HaveOccurred()) Expect(fakeSecureClient.CloseCallCount()).To(Equal(1)) }) }) })
[ "\"TERM\"" ]
[]
[ "TERM" ]
[]
["TERM"]
go
1
0
daemon/execdriver/lxc/init.go
package lxc import ( "encoding/json" "fmt" "io/ioutil" "net" "os" "strings" "syscall" "github.com/dotcloud/docker/daemon/execdriver" "github.com/dotcloud/docker/pkg/libcontainer/netlink" "github.com/dotcloud/docker/pkg/user" "github.com/syndtr/gocapability/capability" ) // Clear environment pollution introduced by lxc-start func setupEnv(args *execdriver.InitArgs) error { // Get env var env []string content, err := ioutil.ReadFile(".dockerenv") if err != nil { return fmt.Errorf("Unable to load environment variables: %v", err) } if err := json.Unmarshal(content, &env); err != nil { return fmt.Errorf("Unable to unmarshal environment variables: %v", err) } // Propagate the plugin-specific container env variable env = append(env, "container="+os.Getenv("container")) args.Env = env os.Clearenv() for _, kv := range args.Env { parts := strings.SplitN(kv, "=", 2) if len(parts) == 1 { parts = append(parts, "") } os.Setenv(parts[0], parts[1]) } return nil } func setupHostname(args *execdriver.InitArgs) error { hostname := getEnv(args, "HOSTNAME") if hostname == "" { return nil } return setHostname(hostname) } // Setup networking func setupNetworking(args *execdriver.InitArgs) error { if args.Ip != "" { // eth0 iface, err := net.InterfaceByName("eth0") if err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } ip, ipNet, err := net.ParseCIDR(args.Ip) if err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } if err := netlink.NetworkLinkAddIp(iface, ip, ipNet); err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } if err := netlink.NetworkSetMTU(iface, args.Mtu); err != nil { return fmt.Errorf("Unable to set MTU: %v", err) } if err := netlink.NetworkLinkUp(iface); err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } // loopback iface, err = net.InterfaceByName("lo") if err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } if err := netlink.NetworkLinkUp(iface); err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } } if args.Gateway != "" { gw := net.ParseIP(args.Gateway) if gw == nil { return fmt.Errorf("Unable to set up networking, %s is not a valid gateway IP", args.Gateway) } if err := netlink.AddDefaultGw(gw.String(), "eth0"); err != nil { return fmt.Errorf("Unable to set up networking: %v", err) } } return nil } // Setup working directory func setupWorkingDirectory(args *execdriver.InitArgs) error { if args.WorkDir == "" { return nil } if err := syscall.Chdir(args.WorkDir); err != nil { return fmt.Errorf("Unable to change dir to %v: %v", args.WorkDir, err) } return nil } // Takes care of dropping privileges to the desired user func changeUser(args *execdriver.InitArgs) error { uid, gid, suppGids, err := user.GetUserGroupSupplementary( args.User, syscall.Getuid(), syscall.Getgid(), ) if err != nil { return err } if err := syscall.Setgroups(suppGids); err != nil { return fmt.Errorf("Setgroups failed: %v", err) } if err := syscall.Setgid(gid); err != nil { return fmt.Errorf("Setgid failed: %v", err) } if err := syscall.Setuid(uid); err != nil { return fmt.Errorf("Setuid failed: %v", err) } return nil } func setupCapabilities(args *execdriver.InitArgs) error { if args.Privileged { return nil } drop := []capability.Cap{ capability.CAP_SETPCAP, capability.CAP_SYS_MODULE, capability.CAP_SYS_RAWIO, capability.CAP_SYS_PACCT, capability.CAP_SYS_ADMIN, capability.CAP_SYS_NICE, capability.CAP_SYS_RESOURCE, capability.CAP_SYS_TIME, capability.CAP_SYS_TTY_CONFIG, capability.CAP_AUDIT_WRITE, capability.CAP_AUDIT_CONTROL, capability.CAP_MAC_OVERRIDE, capability.CAP_MAC_ADMIN, capability.CAP_NET_ADMIN, capability.CAP_SYSLOG, } c, err := capability.NewPid(os.Getpid()) if err != nil { return err } c.Unset(capability.CAPS|capability.BOUNDS, drop...) if err := c.Apply(capability.CAPS | capability.BOUNDS); err != nil { return err } return nil } func getEnv(args *execdriver.InitArgs, key string) string { for _, kv := range args.Env { parts := strings.SplitN(kv, "=", 2) if parts[0] == key && len(parts) == 2 { return parts[1] } } return "" }
[ "\"container\"" ]
[]
[ "container" ]
[]
["container"]
go
1
0
tests/benchmarks/micro_benchmarks/test_gemm_flops_performance.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """Tests for gemm-flops benchmark.""" import os import unittest from pathlib import Path from tests.helper import decorator from superbench.common.utils import nv_helper from superbench.benchmarks import BenchmarkRegistry, ReturnCode, Platform, BenchmarkType class GemmFlopsCudaTest(unittest.TestCase): """Tests for GemmFlopsCuda benchmark.""" def setUp(self): """Method called to prepare the test fixture.""" # Create fake binary file just for testing. os.environ['SB_MICRO_PATH'] = '/tmp/superbench/' binary_path = os.path.join(os.getenv('SB_MICRO_PATH'), 'bin') Path(binary_path).mkdir(parents=True, exist_ok=True) self.__binary_file = Path(os.path.join(binary_path, 'cutlass_profiler')) self.__binary_file.touch(mode=0o755, exist_ok=True) def tearDown(self): """Method called after the test method has been called and the result recorded.""" self.__binary_file.unlink() @decorator.cuda_test def test_flops_performance_cuda(self): """Test gemm-flops benchmark.""" benchmark_name = 'gemm-flops' (benchmark_class, predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) assert (benchmark_class) # Negative case - MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE. benchmark = benchmark_class( benchmark_name, parameters='--num_warmup 200 --n 1024 --k 512 --m 2048 --precision FP32 TF32_TC FP16_TC INT8_TC' ) ret = benchmark._preprocess() if nv_helper.get_device_compute_capability() not in [7.0, 8.0]: assert (ret is False) assert (benchmark.return_code == ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) else: assert (ret is True) assert (benchmark.return_code == ReturnCode.SUCCESS) # Check basic information. assert (benchmark.name == 'gemm-flops') assert (benchmark.type == BenchmarkType.MICRO) assert (benchmark._bin_name == 'cutlass_profiler') # Check parameters specified in BenchmarkContext. assert (benchmark._args.num_warmup == 200) assert (benchmark._args.n == 1024) assert (benchmark._args.k == 512) assert (benchmark._args.m == 2048) assert (benchmark._args.precision == ['FP32', 'TF32_TC', 'FP16_TC', 'INT8_TC']) benchmark._GemmFlopsCuda__precision_need_to_run = ['FP32', 'TF32_TC', 'FP16_TC', 'INT8_TC'] # Check results and metrics. raw_output_FP32 = """ CSV Results: Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,alpha,beta,split_k_slices,batch_count,op_class,accum,cta_m,cta_n,cta_k,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Runtime,GB/s,GFLOPs 1,CUTLASS,gemm,cutlass_simt_sgemm_128x128_8x2_nn_align1,passed,success,universal,16384,16384,16384,f32:column,f32:column,f32:column,1,0,1,1,simt,f32,128,128,8,2,4,2,1,1,1,1,50,1024,3221225472,8796629893120,481.022,6.23672,18287.4 1,CUTLASS,gemm,cutlass_simt_sgemm_128x128_8x2_nt_align1,passed,success,universal,16384,16384,16384,f32:column,f32:row,f32:column,1,0,1,1,simt,f32,128,128,8,2,4,2,1,1,1,1,50,1024,3221225472,8796629893120,478.866,6.2648,18369.7 1,CUTLASS,gemm,cutlass_simt_sgemm_128x128_8x2_tn_align1,passed,success,universal,16384,16384,16384,f32:row,f32:column,f32:column,1,0,1,1,simt,f32,128,128,8,2,4,2,1,1,1,1,50,1024,3221225472,8796629893120,482.034,6.22363,18249 1,CUTLASS,gemm,cutlass_simt_sgemm_128x128_8x2_tt_align1,passed,success,universal,16384,16384,16384,f32:row,f32:row,f32:column,1,0,1,1,simt,f32,128,128,8,2,4,2,1,1,1,1,50,1024,3221225472,8796629893120,481.838,6.22616,18256.4 """ raw_output_TF32_TC = """ CSV Results: Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,alpha,beta,split_k_slices,batch_count,op_class,accum,cta_m,cta_n,cta_k,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Runtime,GB/s,GFLOPs 1,CUTLASS,gemm,cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3_nn_align4,passed,success,universal,16384,16384,16384,tf32:column,tf32:column,tf32:column,1,0,1,1,tensorop,f32,256,128,16,3,4,2,1,16,8,8,80,1024,3221225472,8796629893120,88.5764,33.8691,99311.2 1,CUTLASS,gemm,cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3_nt_align4,passed,success,universal,16384,16384,16384,tf32:column,tf32:row,tf32:column,1,0,1,1,tensorop,f32,256,128,16,3,4,2,1,16,8,8,80,1024,3221225472,8796629893120,70.3503,42.6438,125040 1,CUTLASS,gemm,cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3_tn_align4,passed,success,universal,16384,16384,16384,tf32:row,tf32:column,tf32:column,1,0,1,1,tensorop,f32,256,128,16,3,4,2,1,16,8,8,80,1024,3221225472,8796629893120,86.5167,34.6754,101676 1,CUTLASS,gemm,cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3_tt_align4,passed,success,universal,16384,16384,16384,tf32:row,tf32:row,tf32:column,1,0,1,1,tensorop,f32,256,128,16,3,4,2,1,16,8,8,80,1024,3221225472,8796629893120,68.3621,43.884,128677 """ raw_output_FP16_TC = """ CSV Results: Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,alpha,beta,split_k_slices,batch_count,op_class,accum,cta_m,cta_n,cta_k,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Runtime,GB/s,GFLOPs 1,CUTLASS,gemm,cutlass_tensorop_h16816gemm_256x128_32x3_nn_align8,incorrect,success,universal,16384,16384,16384,f16:column,f16:column,f16:column,1,0,1,1,tensorop,f16,256,128,32,3,4,2,1,16,8,16,80,1024,1610612736,8796629893120,34.1575,43.9142,257531 1,CUTLASS,gemm,cutlass_tensorop_h16816gemm_256x128_32x3_nt_align8,incorrect,success,universal,16384,16384,16384,f16:column,f16:row,f16:column,1,0,1,1,tensorop,f16,256,128,32,3,4,2,1,16,8,16,80,1024,1610612736,8796629893120,34.6153,43.3334,254126 1,CUTLASS,gemm,cutlass_tensorop_h16816gemm_256x128_32x3_tn_align8,incorrect,success,universal,16384,16384,16384,f16:row,f16:column,f16:column,1,0,1,1,tensorop,f16,256,128,32,3,4,2,1,16,8,16,80,1024,1610612736,8796629893120,39.0413,38.4209,225316 1,CUTLASS,gemm,cutlass_tensorop_h16816gemm_256x128_32x3_tt_align8,incorrect,success,universal,16384,16384,16384,f16:row,f16:row,f16:column,1,0,1,1,tensorop,f16,256,128,32,3,4,2,1,16,8,16,80,1024,1610612736,8796629893120,31.2994,47.9243,281048 """ assert (benchmark._process_raw_result(0, raw_output_FP32)) assert (benchmark._process_raw_result(1, raw_output_TF32_TC)) assert (benchmark._process_raw_result(2, raw_output_FP16_TC)) assert (benchmark.result['FP32'][0] == 18369.7) assert (benchmark.result['TF32_TC'][0] == 128677) assert (benchmark.result['FP16_TC'][0] == 281048) # Negative case - Add invalid raw output. assert (benchmark._process_raw_result(3, 'Invalid raw output') is False)
[]
[]
[ "SB_MICRO_PATH" ]
[]
["SB_MICRO_PATH"]
python
1
0
contentcuration/contentcuration/models.py
import functools import hashlib import json import logging import os import urllib.parse import uuid from datetime import datetime import pytz from celery import states from django.conf import settings from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core.cache import cache from django.core.exceptions import MultipleObjectsReturned from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import PermissionDenied from django.core.exceptions import ValidationError from django.core.files.storage import default_storage from django.core.files.storage import FileSystemStorage from django.core.mail import send_mail from django.db import IntegrityError from django.db import models from django.db.models import Count from django.db.models import Exists from django.db.models import F from django.db.models import Index from django.db.models import IntegerField from django.db.models import JSONField from django.db.models import Max from django.db.models import OuterRef from django.db.models import Q from django.db.models import Subquery from django.db.models import Sum from django.db.models import UUIDField as DjangoUUIDField from django.db.models import Value from django.db.models.expressions import ExpressionList from django.db.models.expressions import RawSQL from django.db.models.functions import Cast from django.db.models.functions import Lower from django.db.models.indexes import IndexExpression from django.db.models.query_utils import DeferredAttribute from django.db.models.sql import Query from django.dispatch import receiver from django.utils import timezone from django.utils.translation import gettext as _ from django_cte import With from le_utils import proquint from le_utils.constants import content_kinds from le_utils.constants import exercises from le_utils.constants import file_formats from le_utils.constants import format_presets from le_utils.constants import languages from le_utils.constants import roles from model_utils import FieldTracker from mptt.models import MPTTModel from mptt.models import raise_if_unsaved from mptt.models import TreeForeignKey from postmark.core import PMMailInactiveRecipientException from postmark.core import PMMailUnauthorizedException from rest_framework.authtoken.models import Token from contentcuration.constants import channel_history from contentcuration.db.models.expressions import Array from contentcuration.db.models.functions import ArrayRemove from contentcuration.db.models.functions import Unnest from contentcuration.db.models.manager import CustomContentNodeTreeManager from contentcuration.db.models.manager import CustomManager from contentcuration.statistics import record_channel_stats from contentcuration.utils.cache import delete_public_channel_cache_keys from contentcuration.utils.parser import load_json_string EDIT_ACCESS = "edit" VIEW_ACCESS = "view" DEFAULT_CONTENT_DEFAULTS = { 'license': None, 'language': None, 'author': None, 'aggregator': None, 'provider': None, 'copyright_holder': None, 'license_description': None, 'mastery_model': exercises.NUM_CORRECT_IN_A_ROW_5, 'm_value': 5, 'n_value': 5, 'auto_derive_video_thumbnail': True, 'auto_derive_audio_thumbnail': True, 'auto_derive_document_thumbnail': True, 'auto_derive_html5_thumbnail': True, 'auto_derive_exercise_thumbnail': True, 'auto_randomize_questions': True, } DEFAULT_USER_PREFERENCES = json.dumps(DEFAULT_CONTENT_DEFAULTS, ensure_ascii=False) def to_pk(model_or_pk): if isinstance(model_or_pk, models.Model): return model_or_pk.pk return model_or_pk class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('Email address not specified') new_user = self.model( email=self.normalize_email(email), ) new_user.set_password(password) new_user.first_name = first_name new_user.last_name = last_name new_user.save(using=self._db) return new_user def create_superuser(self, email, first_name, last_name, password=None): new_user = self.create_user(email, first_name, last_name, password=password) new_user.is_admin = True new_user.save(using=self._db) return new_user class UniqueActiveUserIndex(Index): def create_sql(self, model, schema_editor, using='', **kwargs): """ This is a vendored and modified version of the Django create_sql method We do this so that we can monkey patch in the unique index statement onto the schema_editor while we create the statement for this index, and then revert it to normal. We should remove this as soon as Django natively supports UniqueConstraints with Expressions. This should hopefully be the case in Django 3.3. """ include = [model._meta.get_field(field_name).column for field_name in self.include] condition = self._get_condition_sql(model, schema_editor) if self.expressions: index_expressions = [] for expression in self.expressions: index_expression = IndexExpression(expression) index_expression.set_wrapper_classes(schema_editor.connection) index_expressions.append(index_expression) expressions = ExpressionList(*index_expressions).resolve_expression( Query(model, alias_cols=False), ) fields = None col_suffixes = None else: fields = [ model._meta.get_field(field_name) for field_name, _ in self.fields_orders ] col_suffixes = [order[1] for order in self.fields_orders] expressions = None sql = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(include)s%(condition)s" # Store the normal SQL statement for indexes old_create_index_sql = schema_editor.sql_create_index # Replace it with our own unique index so that this index actually adds a constraint schema_editor.sql_create_index = sql # Generate the SQL staetment that we want to return return_statement = schema_editor._create_index_sql( model, fields=fields, name=self.name, using=using, db_tablespace=self.db_tablespace, col_suffixes=col_suffixes, opclasses=self.opclasses, condition=condition, include=include, expressions=expressions, **kwargs, ) # Reinstate the previous index SQL statement so that we have done no harm schema_editor.sql_create_index = old_create_index_sql # Return our SQL statement return return_statement class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) is_admin = models.BooleanField(default=False) is_active = models.BooleanField('active', default=False, help_text='Designates whether this user should be treated as active.') is_staff = models.BooleanField('staff status', default=False, help_text='Designates whether the user can log into this admin site.') date_joined = models.DateTimeField('date joined', default=timezone.now) clipboard_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='user_clipboard', on_delete=models.SET_NULL) preferences = models.TextField(default=DEFAULT_USER_PREFERENCES) disk_space = models.FloatField(default=524288000, help_text='How many bytes a user can upload') disk_space_used = models.FloatField(default=0, help_text='How many bytes a user has uploaded') information = JSONField(null=True) content_defaults = JSONField(default=dict) policies = JSONField(default=dict, null=True) feature_flags = JSONField(default=dict, null=True) _field_updates = FieldTracker(fields=[ # Field to watch for changes "disk_space", ]) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __unicode__(self): return self.email def delete(self): from contentcuration.viewsets.common import SQCount # Remove any invitations associated to this account self.sent_to.all().delete() # Delete channels associated with this user (if user is the only editor) user_query = ( User.objects.filter(editable_channels__id=OuterRef('id')) .values_list('id', flat=True) .distinct() ) self.editable_channels.annotate(num_editors=SQCount(user_query, field="id")).filter(num_editors=1).delete() # Delete channel collections associated with this user (if user is the only editor) user_query = ( User.objects.filter(channel_sets__id=OuterRef('id')) .values_list('id', flat=True) .distinct() ) self.channel_sets.annotate(num_editors=SQCount(user_query, field="id")).filter(num_editors=1).delete() super(User, self).delete() def can_edit(self, channel_id): return Channel.filter_edit_queryset(Channel.objects.all(), self).filter(pk=channel_id).exists() def check_space(self, size, checksum): active_files = self.get_user_active_files() if active_files.filter(checksum=checksum).exists(): return True space = self.get_available_space(active_files=active_files) if space < size: raise PermissionDenied(_("Not enough space. Check your storage under Settings page.")) def check_channel_space(self, channel): active_files = self.get_user_active_files() staging_tree_id = channel.staging_tree.tree_id channel_files = self.files\ .filter(contentnode__tree_id=staging_tree_id)\ .values('checksum')\ .distinct()\ .exclude(checksum__in=active_files.values_list('checksum', flat=True)) staged_size = float(channel_files.aggregate(used=Sum('file_size'))['used'] or 0) if self.get_available_space(active_files=active_files) < (staged_size): raise PermissionDenied(_('Out of storage! Request more space under Settings > Storage.')) def check_staged_space(self, size, checksum): if self.staged_files.filter(checksum=checksum).exists(): return True space = self.get_available_staged_space() if space < size: raise PermissionDenied(_('Out of storage! Request more space under Settings > Storage.')) def get_available_staged_space(self): space_used = self.staged_files.values('checksum').distinct().aggregate(size=Sum("file_size"))['size'] or 0 return float(max(self.disk_space - space_used, 0)) def get_available_space(self, active_files=None): return float(max(self.disk_space - self.get_space_used(active_files=active_files), 0)) def get_user_active_trees(self): return self.editable_channels.exclude(deleted=True)\ .values(tree_id=F("main_tree__tree_id")) def get_user_active_files(self): cte = With(self.get_user_active_trees().distinct()) return cte.join(self.files.get_queryset(), contentnode__tree_id=cte.col.tree_id)\ .with_cte(cte)\ .values('checksum')\ .distinct() def get_space_used(self, active_files=None): active_files = active_files or self.get_user_active_files() files = active_files.aggregate(total_used=Sum('file_size')) return float(files['total_used'] or 0) def set_space_used(self): self.disk_space_used = self.get_space_used() self.save() return self.disk_space_used def get_space_used_by_kind(self): active_files = self.get_user_active_files() files = active_files.values('preset__kind_id')\ .annotate(space=Sum('file_size'))\ .order_by() kind_dict = {} for item in files: kind_dict[item['preset__kind_id']] = item['space'] return kind_dict def email_user(self, subject, message, from_email=None, **kwargs): try: # msg = EmailMultiAlternatives(subject, message, from_email, [self.email]) # msg.attach_alternative(kwargs["html_message"],"text/html") # msg.send() send_mail(subject, message, from_email, [self.email], **kwargs) except (PMMailInactiveRecipientException, PMMailUnauthorizedException) as e: logging.error(str(e)) def clean(self): super(User, self).clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """ Returns the short name for the user. """ return self.first_name def get_token(self): token, _ = Token.objects.get_or_create(user=self) return token.key def save(self, *args, **kwargs): from contentcuration.utils.user import calculate_user_storage super(User, self).save(*args, **kwargs) if 'disk_space' in self._field_updates.changed(): calculate_user_storage(self.pk) changed = False if not self.content_defaults: self.content_defaults = DEFAULT_CONTENT_DEFAULTS changed = True if not self.clipboard_tree: self.clipboard_tree = ContentNode.objects.create(title=self.email + " clipboard", kind_id=content_kinds.TOPIC) self.clipboard_tree.save() changed = True if changed: self.save() class Meta: verbose_name = "User" verbose_name_plural = "Users" indexes = [ UniqueActiveUserIndex(Lower('email'), condition=Q(is_active=True), name="contentcura_email_d4d492_idx") ] @classmethod def filter_view_queryset(cls, queryset, user): if user.is_anonymous: return queryset.none() if user.is_admin: return queryset # all shared editors all_editable = User.editable_channels.through.objects.all() editable = all_editable.filter( channel_id__in=all_editable.filter(user_id=user.pk).values_list("channel_id", flat=True) ) # all shared viewers all_view_only = User.view_only_channels.through.objects.all() view_only = all_view_only.filter( channel_id__in=all_view_only.filter(user_id=user.pk).values_list("channel_id", flat=True) ) return queryset.filter( Q(pk=user.pk) | Q(pk__in=editable.values_list("user_id", flat=True)) | Q(pk__in=view_only.values_list("user_id", flat=True)) ) @classmethod def filter_edit_queryset(cls, queryset, user): if user.is_anonymous: return queryset.none() if user.is_admin: return queryset return queryset.filter(pk=user.pk) @classmethod def get_for_email(cls, email, **filters): """ Returns the appropriate User record given an email, ordered by: - those with is_active=True first, which there should only ever be one - otherwise by ID DESC so most recent inactive shoud be returned :param email: A string of the user's email :param filters: Additional filters to filter the User queryset :return: User or None """ return User.objects.filter(email__iexact=email.strip(), **filters)\ .order_by("-is_active", "-id").first() class UUIDField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 32 super(UUIDField, self).__init__(*args, **kwargs) def prepare_value(self, value): if isinstance(value, uuid.UUID): return value.hex return value def get_default(self): result = super(UUIDField, self).get_default() if isinstance(result, uuid.UUID): result = result.hex return result def to_python(self, value): if isinstance(value, uuid.UUID): return value.hex return value class MPTTTreeIDManager(models.Model): """ Because MPTT uses plain integers for tree IDs and does not use an auto-incrementing field for them, the same ID can sometimes be assigned to two trees if two channel create ops happen concurrently. As we are using this table only for the ID generation, it does not need any fields. We resolve this by creating a dummy table and using its ID as the tree index to take advantage of the db's concurrency-friendly way of generating sequential integer IDs. There is a custom migration that ensures that the number of records (and thus id) matches the max tree ID number when this table gets added. """ def file_on_disk_name(instance, filename): """ Create a name spaced file path from the File obejct's checksum property. This path will be used to store the content copy :param instance: File (content File model) :param filename: str :return: str """ return generate_file_on_disk_name(instance.checksum, filename) def generate_file_on_disk_name(checksum, filename): """ Separated from file_on_disk_name to allow for simple way to check if has already exists """ h = checksum basename, ext = os.path.splitext(filename) directory = os.path.join(settings.STORAGE_ROOT, h[0], h[1]) if not os.path.exists(directory): os.makedirs(directory) return os.path.join(directory, h + ext.lower()) def object_storage_name(instance, filename): """ Create a name spaced file path from the File obejct's checksum property. This path will be used to store the content copy :param instance: File (content File model) :param filename: str :return: str """ default_ext = '' if instance.file_format_id: default_ext = '.{}'.format(instance.file_format_id) return generate_object_storage_name(instance.checksum, filename, default_ext) def generate_object_storage_name(checksum, filename, default_ext=''): """ Separated from file_on_disk_name to allow for simple way to check if has already exists """ h = checksum basename, actual_ext = os.path.splitext(filename) ext = actual_ext if actual_ext else default_ext # Use / instead of os.path.join as Windows makes this \\ directory = "/".join([settings.STORAGE_ROOT, h[0], h[1]]) return os.path.join(directory, h + ext.lower()) def generate_storage_url(filename, request=None, *args): """ Generate a storage URL for the given content filename. """ path = generate_object_storage_name(os.path.splitext(filename)[0], filename) # There are three scenarios where Studio might be run as: # # 1. In normal kubernetes, nginx will proxy for us. We'll know we're in kubernetes when the # environment variable RUN_MODE=k8s # # 2. In Docker Compose and bare metal runserver, we'll be running in runserver, and minio # will be exposed in port 9000 in the host's localhost network. # Note (aron): returning the true storage URL (e.g. https://storage.googleapis.com/storage/a.mp4) # isn't too important, because we have CDN in front of our servers, so it should be cached. # But change the logic here in case there is a potential for bandwidth and latency improvement. # Detect our current state first run_mode = os.getenv("RUN_MODE") # if we're running inside k8s, then just serve the normal /content/{storage,databases} URL, # and let nginx handle proper proxying. if run_mode == "k8s": url = "/content/{path}".format( path=path, ) # if we're in docker-compose or in baremetal, just return the object storage URL as localhost:9000 elif run_mode == "docker-compose" or run_mode is None: # generate the minio storage URL, so we can get the GET parameters that give everyone # access even if they don't need to log in params = urllib.parse.urlparse(default_storage.url(path)).query host = "localhost" port = 9000 # hardcoded to the default minio IP address url = "http://{host}:{port}/{bucket}/{path}?{params}".format( host=host, port=port, bucket=settings.AWS_S3_BUCKET_NAME, path=path, params=params, ) return url class FileOnDiskStorage(FileSystemStorage): """ Overrider FileSystemStorage's default save method to ignore duplicated file. """ def get_available_name(self, name): return name def _save(self, name, content): if self.exists(name): # if the file exists, do not call the superclasses _save method logging.warn('Content copy "%s" already exists!' % name) return name return super(FileOnDiskStorage, self)._save(name, content) class SecretToken(models.Model): """Tokens for channels""" token = models.CharField(max_length=100, unique=True) is_primary = models.BooleanField(default=False) @classmethod def exists(cls, token): """ Return true when the token string given by string already exists. Returns false otherwise. """ return cls.objects.filter(token=token).exists() @classmethod def generate_new_token(cls): """ Creates a primary secret token for the current channel using a proquint string. Creates a secondary token containing the channel id. These tokens can be used to refer to the channel to download its content database. """ token = proquint.generate() # Try 100 times to generate a unique token. TRIALS = 100 for __ in range(TRIALS): token = proquint.generate() if SecretToken.exists(token): continue break # after TRIALS attempts and we didn't get a unique token, # just raise an error. # See https://stackoverflow.com/a/9980160 on what for-else loop does. else: raise ValueError("Cannot generate new token") # We found a unique token! Save it return token def __str__(self): return "{}-{}".format(self.token[:5], self.token[5:]) def get_channel_thumbnail(channel): if not isinstance(channel, dict): channel = channel.__dict__ if channel.get("thumbnail_encoding"): thumbnail_data = channel.get("thumbnail_encoding") if thumbnail_data.get("base64"): return thumbnail_data["base64"] if channel.get("thumbnail") and 'static' not in channel.get("thumbnail"): return generate_storage_url(channel.get("thumbnail")) return '/static/img/kolibri_placeholder.png' CHANNEL_NAME_INDEX_NAME = "channel_name_idx" # A list of all the FKs from Channel object # to ContentNode trees # used for permissions filtering CHANNEL_TREES = ( "main_tree", "chef_tree", "trash_tree", "staging_tree", "previous_tree", ) def boolean_val(val): return Value(val, output_field=models.BooleanField()) class PermissionCTE(With): tree_id_fields = [ "channel__{}__tree_id".format(tree_name) for tree_name in CHANNEL_TREES ] def __init__(self, model, user_id, **kwargs): queryset = model.objects.filter(user_id=user_id)\ .annotate( tree_id=Unnest(ArrayRemove(Array(*self.tree_id_fields), None), output_field=models.IntegerField()) ) super(PermissionCTE, self).__init__(queryset=queryset.values("user_id", "channel_id", "tree_id"), **kwargs) @classmethod def editable_channels(cls, user_id): return PermissionCTE(User.editable_channels.through, user_id, name="editable_channels_cte") @classmethod def view_only_channels(cls, user_id): return PermissionCTE(User.view_only_channels.through, user_id, name="view_only_channels_cte") def exists(self, *filters): return Exists(self.queryset().filter(*filters).values("user_id")) class Channel(models.Model): """ Permissions come from association with organizations """ id = UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=400, blank=True) tagline = models.CharField(max_length=150, blank=True, null=True) version = models.IntegerField(default=0) thumbnail = models.TextField(blank=True, null=True) thumbnail_encoding = JSONField(default=dict) editors = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='editable_channels', verbose_name="editors", help_text="Users with edit rights", blank=True, ) viewers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='view_only_channels', verbose_name="viewers", help_text="Users with view only rights", blank=True, ) language = models.ForeignKey('Language', null=True, blank=True, related_name='channel_language', on_delete=models.SET_NULL) trash_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='channel_trash', on_delete=models.SET_NULL) clipboard_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='channel_clipboard', on_delete=models.SET_NULL) main_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='channel_main', on_delete=models.SET_NULL) staging_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='channel_staging', on_delete=models.SET_NULL) chef_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='channel_chef', on_delete=models.SET_NULL) previous_tree = models.ForeignKey('ContentNode', null=True, blank=True, related_name='channel_previous', on_delete=models.SET_NULL) bookmarked_by = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='bookmarked_channels', verbose_name="bookmarked by", ) deleted = models.BooleanField(default=False, db_index=True) public = models.BooleanField(default=False, db_index=True) preferences = models.TextField(default=DEFAULT_USER_PREFERENCES) content_defaults = JSONField(default=dict) priority = models.IntegerField(default=0, help_text="Order to display public channels") last_published = models.DateTimeField(blank=True, null=True) secret_tokens = models.ManyToManyField( SecretToken, related_name='channels', verbose_name="secret tokens", blank=True, ) source_url = models.CharField(max_length=200, blank=True, null=True) demo_server_url = models.CharField(max_length=200, blank=True, null=True) # Fields specific to content generated by Ricecooker source_id = models.CharField(max_length=200, blank=True, null=True) source_domain = models.CharField(max_length=300, blank=True, null=True) ricecooker_version = models.CharField(max_length=100, blank=True, null=True) # Fields to calculate when channel is published published_data = JSONField(default=dict) icon_encoding = models.TextField(blank=True, null=True) total_resource_count = models.IntegerField(default=0) published_kind_count = models.TextField(blank=True, null=True) published_size = models.FloatField(default=0) included_languages = models.ManyToManyField( "Language", related_name='channels', verbose_name="languages", blank=True, ) _field_updates = FieldTracker(fields=[ # Field to watch for changes "description", "language_id", "thumbnail", "name", "thumbnail_encoding", # watch these fields for changes # but exclude them from setting changed # on the main tree "deleted", "public", "main_tree_id", "version", ]) @classmethod def get_editable(cls, user, channel_id): return cls.filter_edit_queryset(cls.objects.all(), user).get(id=channel_id) @classmethod def filter_edit_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id # it won't return anything if not user_id: return queryset.none() edit = Exists(User.editable_channels.through.objects.filter(user_id=user_id, channel_id=OuterRef("id"))) queryset = queryset.annotate(edit=edit) if user.is_admin: return queryset return queryset.filter(edit=True) @classmethod def filter_view_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id user_email = not user.is_anonymous and user.email if user_id: filters = dict(user_id=user_id, channel_id=OuterRef("id")) edit = Exists(User.editable_channels.through.objects.filter(**filters).values("user_id")) view = Exists(User.view_only_channels.through.objects.filter(**filters).values("user_id")) else: edit = boolean_val(False) view = boolean_val(False) queryset = queryset.annotate( edit=edit, view=view, ) if user_id and user.is_admin: return queryset permission_filter = Q() if user_id: pending_channels = Invitation.objects.filter(email=user_email, revoked=False, declined=False, accepted=False).values_list( "channel_id", flat=True ) permission_filter = ( Q(view=True) | Q(edit=True) | Q(deleted=False, id__in=pending_channels) ) return queryset.filter(permission_filter | Q(deleted=False, public=True)) @classmethod def get_all_channels(cls): return cls.objects.select_related('main_tree').prefetch_related('editors', 'viewers').distinct() def resource_size_key(self): return "{}_resource_size".format(self.pk) # Might be good to display resource size, but need to improve query time first def get_resource_size(self): cached_data = cache.get(self.resource_size_key()) if cached_data: return cached_data tree_id = self.main_tree.tree_id files = File.objects.select_related('contentnode', 'assessment_item')\ .filter(contentnode__tree_id=tree_id)\ .values('checksum', 'file_size')\ .distinct()\ .aggregate(resource_size=Sum('file_size')) cache.set(self.resource_size_key(), files['resource_size'] or 0, None) return files['resource_size'] or 0 def on_create(self): record_channel_stats(self, None) if not self.content_defaults: self.content_defaults = DEFAULT_CONTENT_DEFAULTS if not self.main_tree: self.main_tree = ContentNode.objects.create( title=self.name, kind_id=content_kinds.TOPIC, content_id=self.id, node_id=self.id, original_channel_id=self.id, source_channel_id=self.id, changed=True, complete=True, ) # Ensure that locust or unit tests raise if there are any concurrency issues with tree ids. if settings.DEBUG: if ContentNode.objects.filter(parent=None, tree_id=self.main_tree.tree_id).count() != 1: raise AssertionError if not self.trash_tree: self.trash_tree = ContentNode.objects.create( title=self.name, kind_id=content_kinds.TOPIC, content_id=self.id, node_id=self.id, ) # if this change affects the published channel list, clear the channel cache if self.public and (self.main_tree and self.main_tree.published): delete_public_channel_cache_keys() def on_update(self): from contentcuration.utils.user import calculate_user_storage original_values = self._field_updates.changed() record_channel_stats(self, original_values) blacklist = set([ "public", "main_tree_id", "version", ]) if self.main_tree and original_values and any((True for field in original_values if field not in blacklist)): # Changing channel metadata should also mark main_tree as changed self.main_tree.changed = True # Check if original thumbnail is no longer referenced if "thumbnail" in original_values and original_values["thumbnail"] and 'static' not in original_values["thumbnail"]: filename, ext = os.path.splitext(original_values["thumbnail"]) delete_empty_file_reference(filename, ext[1:]) # Refresh storage for all editors on the channel if "deleted" in original_values: for editor in self.editors.all(): calculate_user_storage(editor.pk) # Delete db if channel has been deleted and mark as unpublished if "deleted" in original_values and not original_values["deleted"]: self.pending_editors.all().delete() export_db_storage_path = os.path.join(settings.DB_ROOT, "{channel_id}.sqlite3".format(channel_id=self.id)) if default_storage.exists(export_db_storage_path): default_storage.delete(export_db_storage_path) if self.main_tree: self.main_tree.published = False if self.main_tree and self.main_tree._field_updates.changed(): self.main_tree.save() # if this change affects the published channel list, clear the channel cache if "public" in original_values and (self.main_tree and self.main_tree.published): delete_public_channel_cache_keys() def save(self, *args, **kwargs): if self._state.adding: self.on_create() else: self.on_update() super(Channel, self).save(*args, **kwargs) def get_thumbnail(self): return get_channel_thumbnail(self) def has_changes(self): return self.main_tree.get_descendants(include_self=True).filter(changed=True).exists() def get_date_modified(self): return self.main_tree.get_descendants(include_self=True).aggregate(last_modified=Max('modified'))['last_modified'] def get_resource_count(self): return self.main_tree.get_descendants().exclude(kind_id=content_kinds.TOPIC).order_by('content_id').distinct('content_id').count() def get_human_token(self): return self.secret_tokens.get(is_primary=True) def get_channel_id_token(self): return self.secret_tokens.get(token=self.id) def make_token(self): token = self.secret_tokens.create(token=SecretToken.generate_new_token(), is_primary=True) self.secret_tokens.get_or_create(token=self.id) return token def make_public(self, bypass_signals=False): """ Sets the current channel object to be public and viewable by anyone. If bypass_signals is True, update the model in such a way that we prevent any model signals from running due to the update. Returns the same channel object. """ if bypass_signals: self.public = True # set this attribute still, so the object will be updated Channel.objects.filter(id=self.id).update(public=True) # clear the channel cache delete_public_channel_cache_keys() else: self.public = True self.save() return self def mark_created(self, user): self.history.create(actor_id=to_pk(user), action=channel_history.CREATION) def mark_publishing(self, user): self.history.create(actor_id=to_pk(user), action=channel_history.PUBLICATION) self.main_tree.publishing = True self.main_tree.save() def mark_deleted(self, user): self.history.create(actor_id=to_pk(user), action=channel_history.DELETION) self.deleted = True self.save() def mark_recovered(self, user): self.history.create(actor_id=to_pk(user), action=channel_history.RECOVERY) self.deleted = False self.save() @property def deletion_history(self): return self.history.filter(action=channel_history.DELETION) @property def publishing_history(self): return self.history.filter(action=channel_history.PUBLICATION) @classmethod def get_public_channels(cls, defer_nonmain_trees=False): """ Get all public channels. If defer_nonmain_trees is True, defer the loading of all trees except for the main_tree.""" if defer_nonmain_trees: c = (Channel.objects .filter(public=True) .exclude(deleted=True) .select_related('main_tree') .prefetch_related('editors') .defer('trash_tree', 'clipboard_tree', 'staging_tree', 'chef_tree', 'previous_tree', 'viewers')) else: c = Channel.objects.filter(public=True).exclude(deleted=True) return c class Meta: verbose_name = "Channel" verbose_name_plural = "Channels" indexes = [ models.Index(fields=["name"], name=CHANNEL_NAME_INDEX_NAME), ] index_together = [ ["deleted", "public"] ] CHANNEL_HISTORY_CHANNEL_INDEX_NAME = "idx_channel_history_channel_id" class ChannelHistory(models.Model): """ Model for tracking certain actions performed on a channel """ channel = models.ForeignKey('Channel', null=False, blank=False, related_name='history', on_delete=models.CASCADE) actor = models.ForeignKey('User', null=False, blank=False, related_name='channel_history', on_delete=models.CASCADE) performed = models.DateTimeField(default=timezone.now) action = models.CharField(max_length=50, choices=channel_history.choices) @classmethod def prune(cls): """ Prunes history records by keeping the most recent actions for each channel and type, and deleting all other older actions """ keep_ids = cls.objects.distinct("channel_id", "action").order_by("channel_id", "action", "-performed").values_list("id", flat=True) cls.objects.exclude(id__in=keep_ids).delete() class Meta: verbose_name = "Channel history" verbose_name_plural = "Channel histories" indexes = [ models.Index(fields=["channel_id"], name=CHANNEL_HISTORY_CHANNEL_INDEX_NAME), ] class ChannelSet(models.Model): # NOTE: this is referred to as "channel collections" on the front-end, but we need to call it # something else as there is already a ChannelCollection model on the front-end id = UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=400, blank=True) public = models.BooleanField(default=False, db_index=True) editors = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='channel_sets', verbose_name="editors", help_text="Users with edit rights", blank=True, ) secret_token = models.ForeignKey('SecretToken', null=True, blank=True, related_name='channel_sets', on_delete=models.SET_NULL) @classmethod def filter_edit_queryset(cls, queryset, user): if user.is_anonymous: return queryset.none() user_id = not user.is_anonymous and user.id edit = Exists(User.channel_sets.through.objects.filter(user_id=user_id, channelset_id=OuterRef("id"))) queryset = queryset.annotate(edit=edit) if user.is_admin: return queryset return queryset.filter(edit=True) @classmethod def filter_view_queryset(cls, queryset, user): return cls.filter_edit_queryset(queryset, user) def get_channels(self): if self.secret_token: return self.secret_token.channels.filter(deleted=False) def save(self, *args, **kwargs): if self._state.adding: self.on_create() super(ChannelSet, self).save() def on_create(self): if not self.secret_token: self.secret_token = SecretToken.objects.create(token=SecretToken.generate_new_token()) def delete(self, *args, **kwargs): super(ChannelSet, self).delete(*args, **kwargs) if self.secret_token: self.secret_token.delete() class ContentTag(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4) tag_name = models.CharField(max_length=50) channel = models.ForeignKey('Channel', related_name='tags', blank=True, null=True, db_index=True, on_delete=models.SET_NULL) objects = CustomManager() def __str__(self): return self.tag_name class Meta: unique_together = ['tag_name', 'channel'] def delegate_manager(method): """ Delegate method calls to base manager, if exists. """ @functools.wraps(method) def wrapped(self, *args, **kwargs): if self._base_manager: return getattr(self._base_manager, method.__name__)(*args, **kwargs) return method(self, *args, **kwargs) return wrapped class License(models.Model): """ Normalize the license of ContentNode model """ license_name = models.CharField(max_length=50) license_url = models.URLField(blank=True) license_description = models.TextField(blank=True) copyright_holder_required = models.BooleanField(default=True) is_custom = models.BooleanField(default=False) exists = models.BooleanField( default=False, verbose_name="license exists", help_text="Tells whether or not a content item is licensed to share", ) @classmethod def validate_name(cls, name): if cls.objects.filter(license_name=name).count() == 0: raise ValidationError('License `{}` does not exist'.format(name)) def __str__(self): return self.license_name NODE_ID_INDEX_NAME = "node_id_idx" NODE_MODIFIED_INDEX_NAME = "node_modified_idx" NODE_MODIFIED_DESC_INDEX_NAME = "node_modified_desc_idx" class ContentNode(MPTTModel, models.Model): """ By default, all nodes have a title and can be used as a topic. """ # Random id used internally on Studio (See `node_id` for id used in Kolibri) id = UUIDField(primary_key=True, default=uuid.uuid4) # the content_id is used for tracking a user's interaction with a piece of # content, in the face of possibly many copies of that content. When a user # interacts with a piece of content, all substantially similar pieces of # content should be marked as such as well. We track these "substantially # similar" types of content by having them have the same content_id. content_id = UUIDField(primary_key=False, default=uuid.uuid4, editable=False, db_index=True) # Note this field is indexed, but we are using the Index API to give it an explicit name, see the model Meta node_id = UUIDField(primary_key=False, default=uuid.uuid4, editable=False) # TODO: disallow nulls once existing models have been set original_channel_id = UUIDField(primary_key=False, editable=False, null=True, db_index=True) # Original channel copied from source_channel_id = UUIDField(primary_key=False, editable=False, null=True) # Immediate channel copied from # Original node_id of node copied from (TODO: original_node_id clashes with original_node field - temporary) original_source_node_id = UUIDField(primary_key=False, editable=False, null=True, db_index=True) source_node_id = UUIDField(primary_key=False, editable=False, null=True) # Immediate node_id of node copied from # Fields specific to content generated by Ricecooker source_id = models.CharField(max_length=200, blank=True, null=True) source_domain = models.CharField(max_length=300, blank=True, null=True) title = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) kind = models.ForeignKey('ContentKind', related_name='contentnodes', db_index=True, null=True, blank=True, on_delete=models.SET_NULL) license = models.ForeignKey('License', null=True, blank=True, on_delete=models.SET_NULL) license_description = models.CharField(max_length=400, null=True, blank=True) prerequisite = models.ManyToManyField('self', related_name='is_prerequisite_of', through='PrerequisiteContentRelationship', symmetrical=False, blank=True) is_related = models.ManyToManyField('self', related_name='relate_to', through='RelatedContentRelationship', symmetrical=False, blank=True) language = models.ForeignKey('Language', null=True, blank=True, related_name='content_language', on_delete=models.SET_NULL) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) tags = models.ManyToManyField(ContentTag, symmetrical=False, related_name='tagged_content', blank=True) # No longer used sort_order = models.FloatField(max_length=50, default=1, verbose_name="sort order", help_text="Ascending, lowest number shown first") copyright_holder = models.CharField(max_length=200, null=True, blank=True, default="", help_text="Organization of person who holds the essential rights") # legacy field... original_node = TreeForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='duplicates') cloned_source = TreeForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='clones') thumbnail_encoding = models.TextField(blank=True, null=True) created = models.DateTimeField(default=timezone.now, verbose_name="created") modified = models.DateTimeField(auto_now=True, verbose_name="modified") published = models.BooleanField(default=False) publishing = models.BooleanField(default=False) complete = models.BooleanField(null=True) changed = models.BooleanField(default=True) """ Extra fields for exercises: - type: mastery model to use to determine completion - m: m value for M out of N mastery criteria - n: n value for M out of N mastery criteria """ extra_fields = JSONField(default=dict, blank=True, null=True) author = models.CharField(max_length=200, blank=True, default="", help_text="Who created this content?", null=True) aggregator = models.CharField(max_length=200, blank=True, default="", help_text="Who gathered this content together?", null=True) provider = models.CharField(max_length=200, blank=True, default="", help_text="Who distributed this content?", null=True) role_visibility = models.CharField(max_length=50, choices=roles.choices, default=roles.LEARNER) freeze_authoring_data = models.BooleanField(default=False) # Fields for metadata labels # These fields use a map to store applied labels # { # "<label_id1>": true, # "<label_id2>": true, # } grade_levels = models.JSONField(blank=True, null=True) resource_types = models.JSONField(blank=True, null=True) learning_activities = models.JSONField(blank=True, null=True) accessibility_labels = models.JSONField(blank=True, null=True) categories = models.JSONField(blank=True, null=True) learner_needs = models.JSONField(blank=True, null=True) # A field for storing a suggested duration for the content node # this duration should be in seconds. suggested_duration = models.IntegerField(blank=True, null=True, help_text="Suggested duration for the content node (in seconds)") objects = CustomContentNodeTreeManager() # Track all updates and ignore a blacklist of attributes # when we check for changes _field_updates = FieldTracker() _permission_filter = Q(tree_id=OuterRef("tree_id")) @classmethod def _annotate_channel_id(cls, queryset): # Annotate channel id return queryset.annotate( channel_id=Subquery( Channel.objects.filter( main_tree__tree_id=OuterRef("tree_id") ).values_list("id", flat=True)[:1] ) ) @classmethod def _orphan_tree_id_subquery(cls): # For some reason this now requires an explicit type cast # or it gets interpreted as a varchar return Cast(cls.objects.filter( pk=settings.ORPHANAGE_ROOT_ID ).values_list("tree_id", flat=True)[:1], output_field=IntegerField()) @classmethod def filter_edit_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id queryset = queryset.exclude(pk=settings.ORPHANAGE_ROOT_ID) if not user_id: return queryset.none() edit_cte = PermissionCTE.editable_channels(user_id) queryset = queryset.with_cte(edit_cte).annotate( edit=edit_cte.exists(cls._permission_filter), ) if user.is_admin: return queryset return queryset.filter(Q(edit=True) | Q(tree_id=cls._orphan_tree_id_subquery())) @classmethod def filter_view_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id queryset = queryset.annotate( public=Exists( Channel.objects.filter( public=True, main_tree__tree_id=OuterRef("tree_id") ).values("pk") ), ).exclude(pk=settings.ORPHANAGE_ROOT_ID) if not user_id: return queryset.annotate(edit=boolean_val(False), view=boolean_val(False)).filter(public=True) edit_cte = PermissionCTE.editable_channels(user_id) view_cte = PermissionCTE.view_only_channels(user_id) queryset = queryset.with_cte(edit_cte).with_cte(view_cte).annotate( edit=edit_cte.exists(cls._permission_filter), view=view_cte.exists(cls._permission_filter), ) if user.is_admin: return queryset return queryset.filter( Q(view=True) | Q(edit=True) | Q(public=True) | Q(tree_id=cls._orphan_tree_id_subquery()) ) @raise_if_unsaved def get_root(self): # Only topics can be root nodes if self.is_root_node() and self.kind_id != content_kinds.TOPIC: return self return super(ContentNode, self).get_root() @raise_if_unsaved def get_root_id(self): # Only topics can be root nodes if self.is_root_node() and self.kind_id != content_kinds.TOPIC: return self return ContentNode.objects.values_list('pk', flat=True).get( tree_id=self._mpttfield('tree_id'), parent=None, ) def get_tree_data(self, levels=float('inf')): """ Returns `levels`-deep tree information starting at current node. Args: levels (int): depth of tree hierarchy to return Returns: tree (dict): starting with self, with children list containing either the just the children's `node_id`s or full recusive tree. """ if self.kind_id == content_kinds.TOPIC: node_data = { "title": self.title, "kind": self.kind_id, "node_id": self.node_id, "studio_id": self.id, } children = self.children.all() if levels > 0: node_data["children"] = [c.get_tree_data(levels=levels - 1) for c in children] return node_data if self.kind_id == content_kinds.EXERCISE: return { "title": self.title, "kind": self.kind_id, "count": self.assessment_items.count(), "node_id": self.node_id, "studio_id": self.id, } return { "title": self.title, "kind": self.kind_id, "file_size": self.files.values('file_size').aggregate(size=Sum('file_size'))['size'], "node_id": self.node_id, "studio_id": self.id, } def get_original_node(self): original_node = self.original_node or self if self.original_channel_id and self.original_source_node_id: original_tree_id = Channel.objects.select_related("main_tree").get(pk=self.original_channel_id).main_tree.tree_id original_node = ContentNode.objects.filter(tree_id=original_tree_id, node_id=self.original_source_node_id).first() or \ ContentNode.objects.filter(tree_id=original_tree_id, content_id=self.content_id).first() or self return original_node def get_associated_presets(self): key = "associated_presets_{}".format(self.kind_id) cached_data = cache.get(key) if cached_data: return cached_data presets = list(FormatPreset.objects.filter(kind=self.kind).values()) cache.set(key, presets, None) return presets def get_prerequisites(self): prerequisite_mapping = {} prerequisites = self.prerequisite.all() prereqlist = list(prerequisites) for prereq in prerequisites: prlist, prereqmapping = prereq.get_prerequisites() prerequisite_mapping.update({prereq.pk: prereqmapping}) prereqlist.extend(prlist) return prereqlist, prerequisite_mapping def get_postrequisites(self): postrequisite_mapping = {} postrequisites = self.is_prerequisite_of.all() postreqlist = list(postrequisites) for postreq in postrequisites: prlist, postreqmapping = postreq.get_postrequisites() postrequisite_mapping.update({postreq.pk: postreqmapping}) postreqlist.extend(prlist) return postreqlist, postrequisite_mapping def get_channel_id(self): if hasattr(self, "channel_id"): return self.channel_id channel = self.get_channel() if channel: return channel.id return None def get_channel(self): try: root = self.get_root() if not root: return None return Channel.objects.filter(Q(main_tree=root) | Q(chef_tree=root) | Q(trash_tree=root) | Q(staging_tree=root) | Q(previous_tree=root)).first() except (ObjectDoesNotExist, MultipleObjectsReturned, AttributeError): return None def get_thumbnail(self): # Problems with json.loads, so use ast.literal_eval to get dict if self.thumbnail_encoding: thumbnail_data = load_json_string(self.thumbnail_encoding) if type(thumbnail_data) is dict and thumbnail_data.get("base64"): return thumbnail_data["base64"] thumbnail = self.files.filter(preset__thumbnail=True).first() if thumbnail: return generate_storage_url(str(thumbnail)) return "" @classmethod def get_nodes_with_title(cls, title, limit_to_children_of=None): """ Returns all ContentNodes with a given title. If limit_to_children_of is passed in with an id, only look at all the children of the node with that id. """ if limit_to_children_of: root = cls.objects.get(id=limit_to_children_of) return root.get_descendants().filter(title=title) return cls.objects.filter(title=title) def get_details(self, channel_id=None): """ Returns information about the node and its children, including total size, languages, files, etc. :return: A dictionary with detailed statistics and information about the node. """ from contentcuration.viewsets.common import SQArrayAgg from contentcuration.viewsets.common import SQCount from contentcuration.viewsets.common import SQRelatedArrayAgg from contentcuration.viewsets.common import SQSum node = ContentNode.objects.filter(pk=self.id).order_by() descendants = ( self.get_descendants() .prefetch_related("children", "files", "tags") .select_related("license", "language") .values("id") ) if channel_id: channel = Channel.objects.filter(id=channel_id)[0] else: channel = self.get_channel() if not descendants.exists(): data = { "last_update": pytz.utc.localize(datetime.now()).strftime( settings.DATE_TIME_FORMAT ), "created": self.created.strftime(settings.DATE_TIME_FORMAT), "resource_count": 0, "resource_size": 0, "includes": {"coach_content": 0, "exercises": 0}, "kind_count": [], "languages": "", "accessible_languages": "", "licenses": "", "tags": [], "copyright_holders": "", "authors": "", "aggregators": "", "providers": "", "sample_pathway": [], "original_channels": [], "sample_nodes": [], } # Set cache with latest data cache.set("details_{}".format(self.node_id), json.dumps(data), None) return data # Get resources resources = descendants.exclude(kind=content_kinds.TOPIC).order_by() nodes = With( File.objects.filter(contentnode_id__in=Subquery(resources.values("id"))) .values("checksum", "file_size") .order_by(), name="nodes", ) file_query = ( nodes.queryset().with_cte(nodes).values("checksum", "file_size").distinct() ) l_nodes = With( File.objects.filter(contentnode_id__in=Subquery(resources.values("id"))) .values("language_id", "preset_id") .order_by(), name="l_nodes", ) accessible_languages_query = ( l_nodes.queryset() .filter(preset_id=format_presets.VIDEO_SUBTITLE) .with_cte(l_nodes) .values("language__native_name") .distinct() ) tags_query = str( ContentTag.objects.filter( tagged_content__pk__in=descendants.values_list("pk", flat=True) ) .values("tag_name") .annotate(count=Count("tag_name")) .query ).replace("topic", "'topic'") kind_count_query = str( resources.values("kind_id").annotate(count=Count("kind_id")).query ).replace("topic", "'topic'") node = node.annotate( resource_count=SQCount(resources, field="id"), resource_size=SQSum(file_query, field="file_size"), copyright_holders=SQArrayAgg( resources.distinct("copyright_holder").order_by("copyright_holder"), field="copyright_holder", ), authors=SQArrayAgg( resources.distinct("author").order_by("author"), field="author" ), aggregators=SQArrayAgg( resources.distinct("aggregator").order_by("aggregator"), field="aggregator", ), providers=SQArrayAgg( resources.distinct("provider").order_by("provider"), field="provider" ), languages=SQRelatedArrayAgg( descendants.exclude(language=None) .distinct("language__native_name") .order_by(), field="language__native_name", fieldname="native_name", ), accessible_languages=SQRelatedArrayAgg( accessible_languages_query, field="language__native_name", fieldname="native_name", ), licenses=SQRelatedArrayAgg( resources.exclude(license=None) .distinct("license__license_name") .order_by("license__license_name"), field="license__license_name", fieldname="license_name", ), kind_count=RawSQL( "SELECT json_agg(row_to_json (x)) FROM ({}) as x".format( kind_count_query ), (), ), tags_list=RawSQL( "SELECT json_agg(row_to_json (x)) FROM ({}) as x".format(tags_query), () ), coach_content=SQCount( resources.filter(role_visibility=roles.COACH), field="id" ), exercises=SQCount( resources.filter(kind_id=content_kinds.EXERCISE), field="id" ), ) # Get sample pathway by getting longest path # Using resources.aggregate adds a lot of time, use values that have already been fetched max_level = max( resources.values_list("level", flat=True).order_by().distinct() or [0] ) m_nodes = With( resources.values("id", "level", "tree_id", "lft").order_by(), name="m_nodes", ) deepest_node_record = ( m_nodes.queryset() .with_cte(m_nodes) .filter(level=max_level) .values("id") .order_by("tree_id", "lft") .first() ) if deepest_node_record: deepest_node = ContentNode.objects.get(pk=deepest_node_record["id"]) pathway = ( list( deepest_node.get_ancestors() .order_by() .exclude(parent=None) .values("title", "node_id", "kind_id") .order_by() ) if deepest_node_record else [] ) sample_nodes = ( [ { "node_id": n.node_id, "title": n.title, "description": n.description, "thumbnail": n.get_thumbnail(), "kind": n.kind_id, } for n in deepest_node.get_siblings(include_self=True)[0:4] ] if deepest_node_record else [] ) # Get list of channels nodes were originally imported from (omitting the current channel) channel_id = channel and channel.id originals = ( resources.values("original_channel_id") .annotate(count=Count("original_channel_id")) .order_by("original_channel_id") ) originals = {c["original_channel_id"]: c["count"] for c in originals} original_channels = ( Channel.objects.exclude(pk=channel_id) .filter(pk__in=originals.keys(), deleted=False) .order_by() ) original_channels = [ { "id": c.id, "name": "{}{}".format( c.name, _(" (Original)") if channel_id == c.id else "" ), "thumbnail": c.get_thumbnail(), "count": originals[c.id], } for c in original_channels ] node = ( node.order_by() .values( "id", "resource_count", "resource_size", "copyright_holders", "authors", "aggregators", "providers", "languages", "accessible_languages", "coach_content", "licenses", "tags_list", "kind_count", "exercises", ) .first() ) for_educators = { "coach_content": node["coach_content"], "exercises": node["exercises"], } # Serialize data data = { "last_update": pytz.utc.localize(datetime.now()).strftime( settings.DATE_TIME_FORMAT ), "created": self.created.strftime(settings.DATE_TIME_FORMAT), "resource_count": node.get("resource_count", 0), "resource_size": node.get("resource_size", 0), "includes": for_educators, "kind_count": node.get("kind_count", []), "languages": node.get("languages", ""), "accessible_languages": node.get("accessible_languages", ""), "licenses": node.get("licenses", ""), "tags": node.get("tags_list", []), "copyright_holders": node["copyright_holders"], "authors": node["authors"], "aggregators": node["aggregators"], "providers": node["providers"], "sample_pathway": pathway, "original_channels": original_channels, "sample_nodes": sample_nodes, } # Set cache with latest data cache.set("details_{}".format(self.node_id), json.dumps(data), None) return data def has_changes(self): mptt_opts = self._mptt_meta # Ignore fields that are used for dirty tracking, and also mptt fields, as changes to these are tracked in mptt manager methods. blacklist = set([ 'changed', 'modified', 'publishing', mptt_opts.tree_id_attr, mptt_opts.left_attr, mptt_opts.right_attr, mptt_opts.level_attr, ]) original_values = self._field_updates.changed() return any((True for field in original_values if field not in blacklist)) def recalculate_editors_storage(self): from contentcuration.utils.user import calculate_user_storage for editor in self.files.values_list('uploaded_by_id', flat=True).distinct(): calculate_user_storage(editor) def on_create(self): self.changed = True self.recalculate_editors_storage() def on_update(self): self.changed = self.changed or self.has_changes() def move_to(self, target, *args, **kwargs): parent_was_trashtree = self.parent.channel_trash.exists() super(ContentNode, self).move_to(target, *args, **kwargs) # Recalculate storage if node was moved to or from the trash tree if target.channel_trash.exists() or parent_was_trashtree: self.recalculate_editors_storage() def save(self, skip_lock=False, *args, **kwargs): if self._state.adding: self.on_create() else: self.on_update() # Logic borrowed from mptt - do a simple check to see if we have changed # the parent of the node. We use the mptt specific cached fields here # because these get updated by the mptt move methods, and so will be up to # date, meaning we can avoid locking the DB twice when the fields have already # been updated in the database. # If most moves are being done independently of just changing the parent # and then calling a save, locking within the save method itself should rarely # be triggered - meaning updates to contentnode metadata should only rarely # trigger a write lock on mptt fields. old_parent_id = self._field_updates.changed().get("parent_id") if self._state.adding and (self.parent_id or self.parent): same_order = False elif old_parent_id is DeferredAttribute: same_order = True else: same_order = old_parent_id == self.parent_id if not same_order: changed_ids = list(filter(lambda x: x is not None, set([old_parent_id, self.parent_id]))) else: changed_ids = [] if not same_order and not skip_lock: # Lock the mptt fields for the trees of the old and new parent with ContentNode.objects.lock_mptt(*ContentNode.objects .filter(id__in=[pid for pid in [old_parent_id, self.parent_id] if pid]) .values_list('tree_id', flat=True).distinct()): super(ContentNode, self).save(*args, **kwargs) # Always write to the database for the parent change updates, as we have # no persistent object references for the original and new parent to modify if changed_ids: ContentNode.objects.filter(id__in=changed_ids).update(changed=True) else: super(ContentNode, self).save(*args, **kwargs) # Always write to the database for the parent change updates, as we have # no persistent object references for the original and new parent to modify if changed_ids: ContentNode.objects.filter(id__in=changed_ids).update(changed=True) # Copied from MPTT save.alters_data = True def delete(self, *args, **kwargs): parent = self.parent or self._field_updates.changed().get('parent') if parent: parent.changed = True parent.save() self.recalculate_editors_storage() # Lock the mptt fields for the tree of this node with ContentNode.objects.lock_mptt(self.tree_id): return super(ContentNode, self).delete(*args, **kwargs) # Copied from MPTT delete.alters_data = True def copy_to( self, target=None, position="last-child", pk=None, mods=None, excluded_descendants=None, can_edit_source_channel=None, batch_size=None, progress_tracker=None ): return self._tree_manager.copy_node(self, target, position, pk, mods, excluded_descendants, can_edit_source_channel, batch_size, progress_tracker)[0] def copy(self): return self.copy_to() class Meta: verbose_name = "Topic" verbose_name_plural = "Topics" # Do not allow two nodes with the same name on the same level # unique_together = ('parent', 'title') indexes = [ models.Index(fields=["node_id"], name=NODE_ID_INDEX_NAME), models.Index(fields=["-modified"], name=NODE_MODIFIED_DESC_INDEX_NAME), ] class ContentKind(models.Model): kind = models.CharField(primary_key=True, max_length=200, choices=content_kinds.choices) def __str__(self): return self.kind class FileFormat(models.Model): extension = models.CharField(primary_key=True, max_length=40, choices=file_formats.choices) mimetype = models.CharField(max_length=200, blank=True) def __str__(self): return self.extension class FormatPreset(models.Model): id = models.CharField(primary_key=True, max_length=150, choices=format_presets.choices) readable_name = models.CharField(max_length=400) multi_language = models.BooleanField(default=False) supplementary = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) subtitle = models.BooleanField(default=False) display = models.BooleanField(default=True) # Render on client side order = models.IntegerField(default=0) kind = models.ForeignKey(ContentKind, related_name='format_presets', null=True, on_delete=models.SET_NULL) allowed_formats = models.ManyToManyField(FileFormat, blank=True) def __str__(self): return self.id @classmethod def guess_format_preset(cls, filename): """ Guess the format preset of a filename based on its extension. Return None if format is unknown. """ _, ext = os.path.splitext(filename) ext = ext.lstrip(".") f = FormatPreset.objects.filter( allowed_formats__extension=ext, display=True ) return f.first() @classmethod def get_preset(cls, preset_name): """ Get the FormatPreset object with that exact name. Returns None if that format preset is not found. """ try: return FormatPreset.objects.get(id=preset_name) except FormatPreset.DoesNotExist: return None class Language(models.Model): id = models.CharField(max_length=14, primary_key=True) lang_code = models.CharField(max_length=3, db_index=True) lang_subcode = models.CharField(max_length=10, db_index=True, blank=True, null=True) readable_name = models.CharField(max_length=100, blank=True) native_name = models.CharField(max_length=100, blank=True) lang_direction = models.CharField(max_length=3, choices=languages.LANGUAGE_DIRECTIONS, default=languages.LANGUAGE_DIRECTIONS[0][0]) def ietf_name(self): return "{code}-{subcode}".format(code=self.lang_code, subcode=self.lang_subcode) if self.lang_subcode else self.lang_code def __str__(self): return self.ietf_name() ASSESSMENT_ID_INDEX_NAME = "assessment_id_idx" class AssessmentItem(models.Model): type = models.CharField(max_length=50, default="multiplechoice") question = models.TextField(blank=True) hints = models.TextField(default="[]") answers = models.TextField(default="[]") order = models.IntegerField(default=1) contentnode = models.ForeignKey('ContentNode', related_name="assessment_items", blank=True, null=True, db_index=True, on_delete=models.CASCADE) # Note this field is indexed, but we are using the Index API to give it an explicit name, see the model Meta assessment_id = UUIDField(primary_key=False, default=uuid.uuid4, editable=False) raw_data = models.TextField(blank=True) source_url = models.CharField(max_length=400, blank=True, null=True) randomize = models.BooleanField(default=False) deleted = models.BooleanField(default=False) objects = CustomManager() # Track all updates _field_updates = FieldTracker() def has_changes(self): return bool(self._field_updates.changed()) class Meta: indexes = [ models.Index(fields=["assessment_id"], name=ASSESSMENT_ID_INDEX_NAME), ] unique_together = ['contentnode', 'assessment_id'] _permission_filter = Q(tree_id=OuterRef("contentnode__tree_id")) @classmethod def filter_edit_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id if not user_id: return queryset.none() edit_cte = PermissionCTE.editable_channels(user_id) queryset = queryset.with_cte(edit_cte).annotate( edit=edit_cte.exists(cls._permission_filter), ) if user.is_admin: return queryset return queryset.filter(edit=True) @classmethod def filter_view_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id queryset = queryset.annotate( public=Exists( Channel.objects.filter( public=True, main_tree__tree_id=OuterRef("contentnode__tree_id") ).values("pk") ), ) if not user_id: return queryset.annotate(edit=boolean_val(False), view=boolean_val(False)).filter(public=True) edit_cte = PermissionCTE.editable_channels(user_id) view_cte = PermissionCTE.view_only_channels(user_id) queryset = queryset.with_cte(edit_cte).with_cte(view_cte).annotate( edit=edit_cte.exists(cls._permission_filter), view=view_cte.exists(cls._permission_filter), ) if user.is_admin: return queryset return queryset.filter(Q(view=True) | Q(edit=True) | Q(public=True)) class SlideshowSlide(models.Model): contentnode = models.ForeignKey('ContentNode', related_name="slideshow_slides", blank=True, null=True, db_index=True, on_delete=models.CASCADE) sort_order = models.FloatField(default=1.0) metadata = JSONField(default=dict) class StagedFile(models.Model): """ Keeps track of files uploaded through Ricecooker to avoid user going over disk quota limit """ checksum = models.CharField(max_length=400, blank=True, db_index=True) file_size = models.IntegerField(blank=True, null=True) uploaded_by = models.ForeignKey(User, related_name='staged_files', blank=True, null=True, on_delete=models.CASCADE) FILE_DISTINCT_INDEX_NAME = "file_checksum_file_size_idx" FILE_MODIFIED_DESC_INDEX_NAME = "file_modified_desc_idx" FILE_DURATION_CONSTRAINT = "file_media_duration_int" MEDIA_PRESETS = [format_presets.AUDIO, format_presets.VIDEO_HIGH_RES, format_presets.VIDEO_LOW_RES] class File(models.Model): """ The bottom layer of the contentDB schema, defines the basic building brick for content. Things it can represent are, for example, mp4, avi, mov, html, css, jpeg, pdf, mp3... """ id = UUIDField(primary_key=True, default=uuid.uuid4) checksum = models.CharField(max_length=400, blank=True, db_index=True) file_size = models.IntegerField(blank=True, null=True) file_on_disk = models.FileField(upload_to=object_storage_name, storage=default_storage, max_length=500, blank=True) contentnode = models.ForeignKey(ContentNode, related_name='files', blank=True, null=True, db_index=True, on_delete=models.CASCADE) assessment_item = models.ForeignKey(AssessmentItem, related_name='files', blank=True, null=True, db_index=True, on_delete=models.CASCADE) slideshow_slide = models.ForeignKey(SlideshowSlide, related_name='files', blank=True, null=True, db_index=True, on_delete=models.CASCADE) file_format = models.ForeignKey(FileFormat, related_name='files', blank=True, null=True, db_index=True, on_delete=models.SET_NULL) preset = models.ForeignKey(FormatPreset, related_name='files', blank=True, null=True, db_index=True, on_delete=models.SET_NULL) language = models.ForeignKey(Language, related_name='files', blank=True, null=True, on_delete=models.SET_NULL) original_filename = models.CharField(max_length=255, blank=True) source_url = models.CharField(max_length=400, blank=True, null=True) uploaded_by = models.ForeignKey(User, related_name='files', blank=True, null=True, on_delete=models.SET_NULL) modified = models.DateTimeField(auto_now=True, verbose_name="modified", null=True) duration = models.IntegerField(blank=True, null=True) objects = CustomManager() _permission_filter = Q(tree_id=OuterRef("contentnode__tree_id")) | Q(tree_id=OuterRef("assessment_item__contentnode__tree_id")) @classmethod def filter_edit_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id if not user_id: return queryset.none() cte = PermissionCTE.editable_channels(user_id) queryset = queryset.with_cte(cte).annotate(edit=cte.exists(cls._permission_filter)) if user.is_admin: return queryset return queryset.filter( Q(edit=True) | Q(uploaded_by=user, contentnode__isnull=True, assessment_item__isnull=True) ) @classmethod def filter_view_queryset(cls, queryset, user): user_id = not user.is_anonymous and user.id queryset = queryset.annotate( public=Exists( Channel.objects.filter(public=True).filter( Q(main_tree__tree_id=OuterRef("contentnode__tree_id")) | Q(main_tree__tree_id=OuterRef("assessment_item__contentnode__tree_id")) ).values("pk") ), ) if not user_id: return queryset.annotate(edit=boolean_val(False), view=boolean_val(False)).filter(public=True) edit_cte = PermissionCTE.editable_channels(user_id) view_cte = PermissionCTE.view_only_channels(user_id) queryset = queryset.with_cte(edit_cte).with_cte(view_cte).annotate( edit=edit_cte.exists(cls._permission_filter), view=view_cte.exists(cls._permission_filter), ) if user.is_admin: return queryset return queryset.filter( Q(view=True) | Q(edit=True) | Q(public=True) | Q(uploaded_by=user, contentnode__isnull=True, assessment_item__isnull=True) ) class Admin: pass def __str__(self): return '{checksum}{extension}'.format(checksum=self.checksum, extension='.' + self.file_format.extension) def filename(self): """ Returns just the filename of the File in storage, without the path e.g. abcd.mp4 """ # TODO(aron): write tests for this return os.path.basename(self.file_on_disk.name) def on_update(self): # since modified was added later as a nullable field to File, we don't use a default but # instead we'll just make sure it's always updated through our serializers self.modified = timezone.now() def save(self, set_by_file_on_disk=True, *args, **kwargs): """ Overrider the default save method. If the file_on_disk FileField gets passed a content copy: 1. generate the MD5 from the content copy 2. fill the other fields accordingly """ from contentcuration.utils.user import calculate_user_storage if set_by_file_on_disk and self.file_on_disk: # if file_on_disk is supplied, hash out the file if self.checksum is None or self.checksum == "": md5 = hashlib.md5() for chunk in self.file_on_disk.chunks(): md5.update(chunk) self.checksum = md5.hexdigest() if not self.file_size: self.file_size = self.file_on_disk.size if not self.file_format_id: ext = os.path.splitext(self.file_on_disk.name)[1].lstrip('.') if ext in list(dict(file_formats.choices).keys()): self.file_format_id = ext else: raise ValueError("Files of type `{}` are not supported.".format(ext)) super(File, self).save(*args, **kwargs) if self.uploaded_by_id: calculate_user_storage(self.uploaded_by_id) class Meta: indexes = [ models.Index(fields=['checksum', 'file_size'], name=FILE_DISTINCT_INDEX_NAME), models.Index(fields=["-modified"], name=FILE_MODIFIED_DESC_INDEX_NAME), ] constraints = [ models.CheckConstraint(check=(Q(preset__in=MEDIA_PRESETS, duration__gt=0) | Q(duration__isnull=True)), name=FILE_DURATION_CONSTRAINT) ] @receiver(models.signals.post_delete, sender=File) def auto_delete_file_on_delete(sender, instance, **kwargs): """ Deletes file from filesystem if no other File objects are referencing the same file on disk when corresponding `File` object is deleted. Be careful! we don't know if this will work when perform bash delete on File obejcts. """ # Recalculate storage from contentcuration.utils.user import calculate_user_storage if instance.uploaded_by_id: calculate_user_storage(instance.uploaded_by_id) def delete_empty_file_reference(checksum, extension): filename = checksum + '.' + extension if not File.objects.filter(checksum=checksum).exists() and not Channel.objects.filter(thumbnail=filename).exists(): storage_path = generate_object_storage_name(checksum, filename) if default_storage.exists(storage_path): default_storage.delete(storage_path) class PrerequisiteContentRelationship(models.Model): """ Predefine the prerequisite relationship between two ContentNode objects. """ target_node = models.ForeignKey(ContentNode, related_name='%(app_label)s_%(class)s_target_node', on_delete=models.CASCADE) prerequisite = models.ForeignKey(ContentNode, related_name='%(app_label)s_%(class)s_prerequisite', on_delete=models.CASCADE) class Meta: unique_together = ['target_node', 'prerequisite'] def clean(self, *args, **kwargs): # self reference exception if self.target_node == self.prerequisite: raise IntegrityError('Cannot self reference as prerequisite.') # immediate cyclic exception if PrerequisiteContentRelationship.objects.using(self._state.db) \ .filter(target_node=self.prerequisite, prerequisite=self.target_node): raise IntegrityError( 'Note: Prerequisite relationship is directional! %s and %s cannot be prerequisite of each other!' % (self.target_node, self.prerequisite)) # distant cyclic exception # elif <this is a nice to have exception, may implement in the future when the priority raises.> # raise Exception('Note: Prerequisite relationship is acyclic! %s and %s forms a closed loop!' % (self.target_node, self.prerequisite)) super(PrerequisiteContentRelationship, self).clean(*args, **kwargs) def save(self, *args, **kwargs): self.full_clean() super(PrerequisiteContentRelationship, self).save(*args, **kwargs) def __unicode__(self): return u'%s' % (self.pk) class RelatedContentRelationship(models.Model): """ Predefine the related relationship between two ContentNode objects. """ contentnode_1 = models.ForeignKey(ContentNode, related_name='%(app_label)s_%(class)s_1', on_delete=models.CASCADE) contentnode_2 = models.ForeignKey(ContentNode, related_name='%(app_label)s_%(class)s_2', on_delete=models.CASCADE) class Meta: unique_together = ['contentnode_1', 'contentnode_2'] def save(self, *args, **kwargs): # self reference exception if self.contentnode_1 == self.contentnode_2: raise IntegrityError('Cannot self reference as related.') # handle immediate cyclic if RelatedContentRelationship.objects.using(self._state.db) \ .filter(contentnode_1=self.contentnode_2, contentnode_2=self.contentnode_1): return # silently cancel the save super(RelatedContentRelationship, self).save(*args, **kwargs) class Invitation(models.Model): """ Invitation to edit channel """ id = UUIDField(primary_key=True, default=uuid.uuid4) accepted = models.BooleanField(default=False) declined = models.BooleanField(default=False) revoked = models.BooleanField(default=False) invited = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='sent_to') share_mode = models.CharField(max_length=50, default=EDIT_ACCESS) email = models.EmailField(max_length=100, null=True) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sent_by', null=True, on_delete=models.CASCADE) channel = models.ForeignKey('Channel', null=True, related_name='pending_editors', on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: verbose_name = "Invitation" verbose_name_plural = "Invitations" def accept(self): user = User.objects.filter(email__iexact=self.email).first() if self.channel: # channel is a nullable field, so check that it exists. if self.share_mode == VIEW_ACCESS: self.channel.editors.remove(user) self.channel.viewers.add(user) else: self.channel.viewers.remove(user) self.channel.editors.add(user) @classmethod def filter_edit_queryset(cls, queryset, user): if user.is_anonymous: return queryset.none() if user.is_admin: return queryset return queryset.filter( Q(email__iexact=user.email) | Q(sender=user) | Q(channel__editors=user) ).distinct() @classmethod def filter_view_queryset(cls, queryset, user): if user.is_anonymous: return queryset.none() if user.is_admin: return queryset return queryset.filter( Q(email__iexact=user.email) | Q(sender=user) | Q(channel__editors=user) | Q(channel__viewers=user) ).distinct() class Task(models.Model): """Asynchronous tasks""" task_id = UUIDField(db_index=True, default=uuid.uuid4) # This ID is used as the Celery task ID task_type = models.CharField(max_length=50) created = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=10) is_progress_tracking = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="task", on_delete=models.CASCADE) metadata = JSONField() channel_id = DjangoUUIDField(db_index=True, null=True, blank=True) @classmethod def find_incomplete(cls, task_type, **filters): filters.update(task_type=task_type, status__in=["QUEUED", states.PENDING, states.RECEIVED, states.STARTED]) return cls.objects.filter(**filters)
[]
[]
[ "RUN_MODE" ]
[]
["RUN_MODE"]
python
1
0
main.go
package main import ( "log" "os" "sync" "github.com/donohutcheon/gowebserver/state" "github.com/donohutcheon/gowebserver/state/facotory" _ "github.com/heroku/x/hmetrics/onload" "github.com/joho/godotenv" ) func main() { logger := log.New(os.Stdout, "server ", log.LstdFlags|log.Lshortfile) // Load environment from .env file for development. err := godotenv.Load() if err != nil { logger.Printf("Could not load environment files. %s", err.Error()) } mode := os.Getenv("ENVIRONMENT") mainThreadWG := new(sync.WaitGroup) var serverState *state.ServerState if mode == "prod" { serverState, err = facotory.NewForProduction(logger, mainThreadWG) } else { serverState, err = facotory.NewForStaging(logger, mainThreadWG) } if err != nil { logger.Printf("failed to initialize production state %s", err.Error()) return } mainThreadWG.Wait() serverState.Logger.Printf("graceful shutdown") }
[ "\"ENVIRONMENT\"" ]
[]
[ "ENVIRONMENT" ]
[]
["ENVIRONMENT"]
go
1
0
backend/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "turbosettings.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
[]
[]
[]
[]
[]
python
0
0
solver/llbsolver/ops/exec.go
package ops import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "net" "os" "path" "path/filepath" "sort" "strings" "sync" "time" "github.com/containerd/containerd/mount" "github.com/containerd/containerd/platforms" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/locker" "github.com/moby/buildkit/cache" "github.com/moby/buildkit/cache/metadata" "github.com/moby/buildkit/client" "github.com/moby/buildkit/executor" "github.com/moby/buildkit/identity" "github.com/moby/buildkit/session" "github.com/moby/buildkit/session/secrets" "github.com/moby/buildkit/session/sshforward" "github.com/moby/buildkit/snapshot" "github.com/moby/buildkit/solver" "github.com/moby/buildkit/solver/llbsolver" "github.com/moby/buildkit/solver/pb" "github.com/moby/buildkit/util/progress/logs" utilsystem "github.com/moby/buildkit/util/system" "github.com/moby/buildkit/worker" digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/opencontainers/runc/libcontainer/system" "github.com/pkg/errors" "github.com/sirupsen/logrus" bolt "go.etcd.io/bbolt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) const execCacheType = "buildkit.exec.v0" type execOp struct { op *pb.ExecOp cm cache.Manager sm *session.Manager md *metadata.Store exec executor.Executor w worker.Worker platform *pb.Platform numInputs int cacheMounts map[string]*cacheRefShare cacheMountsMu sync.Mutex } func NewExecOp(v solver.Vertex, op *pb.Op_Exec, platform *pb.Platform, cm cache.Manager, sm *session.Manager, md *metadata.Store, exec executor.Executor, w worker.Worker) (solver.Op, error) { if err := llbsolver.ValidateOp(&pb.Op{Op: op}); err != nil { return nil, err } return &execOp{ op: op.Exec, cm: cm, sm: sm, md: md, exec: exec, numInputs: len(v.Inputs()), w: w, platform: platform, cacheMounts: map[string]*cacheRefShare{}, }, nil } func cloneExecOp(old *pb.ExecOp) pb.ExecOp { n := *old meta := *n.Meta meta.ExtraHosts = nil for i := range n.Meta.ExtraHosts { h := *n.Meta.ExtraHosts[i] meta.ExtraHosts = append(meta.ExtraHosts, &h) } n.Meta = &meta n.Mounts = nil for i := range n.Mounts { m := *n.Mounts[i] n.Mounts = append(n.Mounts, &m) } return n } func (e *execOp) CacheMap(ctx context.Context, index int) (*solver.CacheMap, bool, error) { op := cloneExecOp(e.op) for i := range op.Meta.ExtraHosts { h := op.Meta.ExtraHosts[i] h.IP = "" op.Meta.ExtraHosts[i] = h } for i := range op.Mounts { op.Mounts[i].Selector = "" } op.Meta.ProxyEnv = nil p := platforms.DefaultSpec() if e.platform != nil { p = specs.Platform{ OS: e.platform.OS, Architecture: e.platform.Architecture, Variant: e.platform.Variant, } } dt, err := json.Marshal(struct { Type string Exec *pb.ExecOp OS string Arch string Variant string `json:",omitempty"` }{ Type: execCacheType, Exec: &op, OS: p.OS, Arch: p.Architecture, Variant: p.Variant, }) if err != nil { return nil, false, err } cm := &solver.CacheMap{ Digest: digest.FromBytes(dt), Deps: make([]struct { Selector digest.Digest ComputeDigestFunc solver.ResultBasedCacheFunc }, e.numInputs), } deps, err := e.getMountDeps() if err != nil { return nil, false, err } for i, dep := range deps { if len(dep.Selectors) != 0 { dgsts := make([][]byte, 0, len(dep.Selectors)) for _, p := range dep.Selectors { dgsts = append(dgsts, []byte(p)) } cm.Deps[i].Selector = digest.FromBytes(bytes.Join(dgsts, []byte{0})) } if !dep.NoContentBasedHash { cm.Deps[i].ComputeDigestFunc = llbsolver.NewContentHashFunc(toSelectors(dedupePaths(dep.Selectors))) } } return cm, true, nil } func dedupePaths(inp []string) []string { old := make(map[string]struct{}, len(inp)) for _, p := range inp { old[p] = struct{}{} } paths := make([]string, 0, len(old)) for p1 := range old { var skip bool for p2 := range old { if p1 != p2 && strings.HasPrefix(p1, p2+"/") { skip = true break } } if !skip { paths = append(paths, p1) } } sort.Slice(paths, func(i, j int) bool { return paths[i] < paths[j] }) return paths } func toSelectors(p []string) []llbsolver.Selector { sel := make([]llbsolver.Selector, 0, len(p)) for _, p := range p { sel = append(sel, llbsolver.Selector{Path: p, FollowLinks: true}) } return sel } type dep struct { Selectors []string NoContentBasedHash bool } func (e *execOp) getMountDeps() ([]dep, error) { deps := make([]dep, e.numInputs) for _, m := range e.op.Mounts { if m.Input == pb.Empty { continue } if int(m.Input) >= len(deps) { return nil, errors.Errorf("invalid mountinput %v", m) } sel := m.Selector if sel != "" { sel = path.Join("/", sel) deps[m.Input].Selectors = append(deps[m.Input].Selectors, sel) } if (!m.Readonly || m.Dest == pb.RootMount) && m.Output != -1 { // exclude read-only rootfs && read-write mounts deps[m.Input].NoContentBasedHash = true } } return deps, nil } func (e *execOp) getRefCacheDir(ctx context.Context, ref cache.ImmutableRef, id string, m *pb.Mount, sharing pb.CacheSharingOpt) (mref cache.MutableRef, err error) { g := &cacheRefGetter{ locker: &e.cacheMountsMu, cacheMounts: e.cacheMounts, cm: e.cm, md: e.md, globalCacheRefs: sharedCacheRefs, name: fmt.Sprintf("cached mount %s from exec %s", m.Dest, strings.Join(e.op.Meta.Args, " ")), } return g.getRefCacheDir(ctx, ref, id, sharing) } type cacheRefGetter struct { locker sync.Locker cacheMounts map[string]*cacheRefShare cm cache.Manager md *metadata.Store globalCacheRefs *cacheRefs name string } func (g *cacheRefGetter) getRefCacheDir(ctx context.Context, ref cache.ImmutableRef, id string, sharing pb.CacheSharingOpt) (mref cache.MutableRef, err error) { key := "cache-dir:" + id if ref != nil { key += ":" + ref.ID() } mu := g.locker mu.Lock() defer mu.Unlock() if ref, ok := g.cacheMounts[key]; ok { return ref.clone(), nil } defer func() { if err == nil { share := &cacheRefShare{MutableRef: mref, refs: map[*cacheRef]struct{}{}} g.cacheMounts[key] = share mref = share.clone() } }() switch sharing { case pb.CacheSharingOpt_SHARED: return g.globalCacheRefs.get(key, func() (cache.MutableRef, error) { return g.getRefCacheDirNoCache(ctx, key, ref, id, false) }) case pb.CacheSharingOpt_PRIVATE: return g.getRefCacheDirNoCache(ctx, key, ref, id, false) case pb.CacheSharingOpt_LOCKED: return g.getRefCacheDirNoCache(ctx, key, ref, id, true) default: return nil, errors.Errorf("invalid cache sharing option: %s", sharing.String()) } } func (g *cacheRefGetter) getRefCacheDirNoCache(ctx context.Context, key string, ref cache.ImmutableRef, id string, block bool) (cache.MutableRef, error) { makeMutable := func(ref cache.ImmutableRef) (cache.MutableRef, error) { return g.cm.New(ctx, ref, cache.WithRecordType(client.UsageRecordTypeCacheMount), cache.WithDescription(g.name), cache.CachePolicyRetain) } cacheRefsLocker.Lock(key) defer cacheRefsLocker.Unlock(key) for { sis, err := g.md.Search(key) if err != nil { return nil, err } locked := false for _, si := range sis { if mRef, err := g.cm.GetMutable(ctx, si.ID()); err == nil { logrus.Debugf("reusing ref for cache dir: %s", mRef.ID()) return mRef, nil } else if errors.Is(err, cache.ErrLocked) { locked = true } } if block && locked { cacheRefsLocker.Unlock(key) select { case <-ctx.Done(): cacheRefsLocker.Lock(key) return nil, ctx.Err() case <-time.After(100 * time.Millisecond): cacheRefsLocker.Lock(key) } } else { break } } mRef, err := makeMutable(ref) if err != nil { return nil, err } si, _ := g.md.Get(mRef.ID()) v, err := metadata.NewValue(key) if err != nil { mRef.Release(context.TODO()) return nil, err } v.Index = key if err := si.Update(func(b *bolt.Bucket) error { return si.SetValue(b, key, v) }); err != nil { mRef.Release(context.TODO()) return nil, err } return mRef, nil } func (e *execOp) getSSHMountable(ctx context.Context, m *pb.Mount) (cache.Mountable, error) { sessionID := session.FromContext(ctx) if sessionID == "" { return nil, errors.New("could not access local files without session") } timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() caller, err := e.sm.Get(timeoutCtx, sessionID) if err != nil { return nil, err } if err := sshforward.CheckSSHID(ctx, caller, m.SSHOpt.ID); err != nil { if m.SSHOpt.Optional { return nil, nil } if st, ok := status.FromError(errors.Cause(err)); ok && st.Code() == codes.Unimplemented { return nil, errors.Errorf("no SSH key %q forwarded from the client", m.SSHOpt.ID) } return nil, err } return &sshMount{mount: m, caller: caller, idmap: e.cm.IdentityMapping()}, nil } type sshMount struct { mount *pb.Mount caller session.Caller idmap *idtools.IdentityMapping } func (sm *sshMount) Mount(ctx context.Context, readonly bool) (snapshot.Mountable, error) { return &sshMountInstance{sm: sm, idmap: sm.idmap}, nil } type sshMountInstance struct { sm *sshMount idmap *idtools.IdentityMapping } func (sm *sshMountInstance) Mount() ([]mount.Mount, func() error, error) { ctx, cancel := context.WithCancel(context.TODO()) uid := int(sm.sm.mount.SSHOpt.Uid) gid := int(sm.sm.mount.SSHOpt.Gid) if sm.idmap != nil { identity, err := sm.idmap.ToHost(idtools.Identity{ UID: uid, GID: gid, }) if err != nil { return nil, nil, err } uid = identity.UID gid = identity.GID } sock, cleanup, err := sshforward.MountSSHSocket(ctx, sm.sm.caller, sshforward.SocketOpt{ ID: sm.sm.mount.SSHOpt.ID, UID: uid, GID: gid, Mode: int(sm.sm.mount.SSHOpt.Mode & 0777), }) if err != nil { cancel() return nil, nil, err } release := func() error { var err error if cleanup != nil { err = cleanup() } cancel() return err } return []mount.Mount{{ Type: "bind", Source: sock, Options: []string{"rbind"}, }}, release, nil } func (sm *sshMountInstance) IdentityMapping() *idtools.IdentityMapping { return sm.idmap } func (e *execOp) getSecretMountable(ctx context.Context, m *pb.Mount) (cache.Mountable, error) { if m.SecretOpt == nil { return nil, errors.Errorf("invalid sercet mount options") } sopt := *m.SecretOpt id := sopt.ID if id == "" { return nil, errors.Errorf("secret ID missing from mount options") } sessionID := session.FromContext(ctx) if sessionID == "" { return nil, errors.New("could not access local files without session") } timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() caller, err := e.sm.Get(timeoutCtx, sessionID) if err != nil { return nil, err } dt, err := secrets.GetSecret(ctx, caller, id) if err != nil { if errors.Is(err, secrets.ErrNotFound) && m.SecretOpt.Optional { return nil, nil } return nil, err } return &secretMount{mount: m, data: dt, idmap: e.cm.IdentityMapping()}, nil } type secretMount struct { mount *pb.Mount data []byte idmap *idtools.IdentityMapping } func (sm *secretMount) Mount(ctx context.Context, readonly bool) (snapshot.Mountable, error) { return &secretMountInstance{sm: sm, idmap: sm.idmap}, nil } type secretMountInstance struct { sm *secretMount root string idmap *idtools.IdentityMapping } func (sm *secretMountInstance) Mount() ([]mount.Mount, func() error, error) { dir, err := ioutil.TempDir("", "buildkit-secrets") if err != nil { return nil, nil, errors.Wrap(err, "failed to create temp dir") } cleanupDir := func() error { return os.RemoveAll(dir) } if err := os.Chmod(dir, 0711); err != nil { cleanupDir() return nil, nil, err } tmpMount := mount.Mount{ Type: "tmpfs", Source: "tmpfs", Options: []string{"nodev", "nosuid", "noexec", fmt.Sprintf("uid=%d,gid=%d", os.Geteuid(), os.Getegid())}, } if system.RunningInUserNS() { tmpMount.Options = nil } if err := mount.All([]mount.Mount{tmpMount}, dir); err != nil { cleanupDir() return nil, nil, errors.Wrap(err, "unable to setup secret mount") } sm.root = dir cleanup := func() error { if err := mount.Unmount(dir, 0); err != nil { return err } return cleanupDir() } randID := identity.NewID() fp := filepath.Join(dir, randID) if err := ioutil.WriteFile(fp, sm.sm.data, 0600); err != nil { cleanup() return nil, nil, err } uid := int(sm.sm.mount.SecretOpt.Uid) gid := int(sm.sm.mount.SecretOpt.Gid) if sm.idmap != nil { identity, err := sm.idmap.ToHost(idtools.Identity{ UID: uid, GID: gid, }) if err != nil { cleanup() return nil, nil, err } uid = identity.UID gid = identity.GID } if err := os.Chown(fp, uid, gid); err != nil { cleanup() return nil, nil, err } if err := os.Chmod(fp, os.FileMode(sm.sm.mount.SecretOpt.Mode&0777)); err != nil { cleanup() return nil, nil, err } return []mount.Mount{{ Type: "bind", Source: fp, Options: []string{"ro", "rbind", "nodev", "nosuid", "noexec"}, }}, cleanup, nil } func (sm *secretMountInstance) IdentityMapping() *idtools.IdentityMapping { return sm.idmap } func addDefaultEnvvar(env []string, k, v string) []string { for _, e := range env { if strings.HasPrefix(e, k+"=") { return env } } return append(env, k+"="+v) } func (e *execOp) Exec(ctx context.Context, inputs []solver.Result) ([]solver.Result, error) { var mounts []executor.Mount var root cache.Mountable var readonlyRootFS bool var outputs []cache.Ref defer func() { for _, o := range outputs { if o != nil { go o.Release(context.TODO()) } } }() // loop over all mounts, fill in mounts, root and outputs for _, m := range e.op.Mounts { var mountable cache.Mountable var ref cache.ImmutableRef if m.Dest == pb.RootMount && m.MountType != pb.MountType_BIND { return nil, errors.Errorf("invalid mount type %s for %s", m.MountType.String(), m.Dest) } // if mount is based on input validate and load it if m.Input != pb.Empty { if int(m.Input) > len(inputs) { return nil, errors.Errorf("missing input %d", m.Input) } inp := inputs[int(m.Input)] workerRef, ok := inp.Sys().(*worker.WorkerRef) if !ok { return nil, errors.Errorf("invalid reference for exec %T", inp.Sys()) } ref = workerRef.ImmutableRef mountable = ref } makeMutable := func(ref cache.ImmutableRef) (cache.MutableRef, error) { desc := fmt.Sprintf("mount %s from exec %s", m.Dest, strings.Join(e.op.Meta.Args, " ")) return e.cm.New(ctx, ref, cache.WithDescription(desc)) } switch m.MountType { case pb.MountType_BIND: // if mount creates an output if m.Output != pb.SkipOutput { // it it is readonly and not root then output is the input if m.Readonly && ref != nil && m.Dest != pb.RootMount { outputs = append(outputs, ref.Clone()) } else { // otherwise output and mount is the mutable child active, err := makeMutable(ref) if err != nil { return nil, err } outputs = append(outputs, active) mountable = active } } else if (!m.Readonly || ref == nil) && m.Dest != pb.RootMount { // this case is empty readonly scratch without output that is not really useful for anything but don't error active, err := makeMutable(ref) if err != nil { return nil, err } defer active.Release(context.TODO()) mountable = active } case pb.MountType_CACHE: if m.CacheOpt == nil { return nil, errors.Errorf("missing cache mount options") } mRef, err := e.getRefCacheDir(ctx, ref, m.CacheOpt.ID, m, m.CacheOpt.Sharing) if err != nil { return nil, err } mountable = mRef defer func() { go mRef.Release(context.TODO()) }() if m.Output != pb.SkipOutput && ref != nil { outputs = append(outputs, ref.Clone()) } case pb.MountType_TMPFS: mountable = newTmpfs(e.cm.IdentityMapping()) case pb.MountType_SECRET: secretMount, err := e.getSecretMountable(ctx, m) if err != nil { return nil, err } if secretMount == nil { continue } mountable = secretMount case pb.MountType_SSH: sshMount, err := e.getSSHMountable(ctx, m) if err != nil { return nil, err } if sshMount == nil { continue } mountable = sshMount default: return nil, errors.Errorf("mount type %s not implemented", m.MountType) } // validate that there is a mount if mountable == nil { return nil, errors.Errorf("mount %s has no input", m.Dest) } // if dest is root we need mutable ref even if there is no output if m.Dest == pb.RootMount { root = mountable readonlyRootFS = m.Readonly if m.Output == pb.SkipOutput && readonlyRootFS { active, err := makeMutable(ref) if err != nil { return nil, err } defer func() { go active.Release(context.TODO()) }() root = active } } else { mounts = append(mounts, executor.Mount{Src: mountable, Dest: m.Dest, Readonly: m.Readonly, Selector: m.Selector}) } } // sort mounts so parents are mounted first sort.Slice(mounts, func(i, j int) bool { return mounts[i].Dest < mounts[j].Dest }) extraHosts, err := parseExtraHosts(e.op.Meta.ExtraHosts) if err != nil { return nil, err } meta := executor.Meta{ Args: e.op.Meta.Args, Env: e.op.Meta.Env, Cwd: e.op.Meta.Cwd, User: e.op.Meta.User, ReadonlyRootFS: readonlyRootFS, ExtraHosts: extraHosts, NetMode: e.op.Network, SecurityMode: e.op.Security, } if e.op.Meta.ProxyEnv != nil { meta.Env = append(meta.Env, proxyEnvList(e.op.Meta.ProxyEnv)...) } meta.Env = addDefaultEnvvar(meta.Env, "PATH", utilsystem.DefaultPathEnv) stdout, stderr := logs.NewLogStreams(ctx, os.Getenv("BUILDKIT_DEBUG_EXEC_OUTPUT") == "1") defer stdout.Close() defer stderr.Close() if err := e.exec.Exec(ctx, meta, root, mounts, nil, stdout, stderr); err != nil { return nil, errors.Wrapf(err, "executor failed running %v", meta.Args) } refs := []solver.Result{} for i, out := range outputs { if mutable, ok := out.(cache.MutableRef); ok { ref, err := mutable.Commit(ctx) if err != nil { return nil, errors.Wrapf(err, "error committing %s", mutable.ID()) } refs = append(refs, worker.NewWorkerRefResult(ref, e.w)) } else { refs = append(refs, worker.NewWorkerRefResult(out.(cache.ImmutableRef), e.w)) } outputs[i] = nil } return refs, nil } func proxyEnvList(p *pb.ProxyEnv) []string { out := []string{} if v := p.HttpProxy; v != "" { out = append(out, "HTTP_PROXY="+v, "http_proxy="+v) } if v := p.HttpsProxy; v != "" { out = append(out, "HTTPS_PROXY="+v, "https_proxy="+v) } if v := p.FtpProxy; v != "" { out = append(out, "FTP_PROXY="+v, "ftp_proxy="+v) } if v := p.NoProxy; v != "" { out = append(out, "NO_PROXY="+v, "no_proxy="+v) } return out } func newTmpfs(idmap *idtools.IdentityMapping) cache.Mountable { return &tmpfs{idmap: idmap} } type tmpfs struct { idmap *idtools.IdentityMapping } func (f *tmpfs) Mount(ctx context.Context, readonly bool) (snapshot.Mountable, error) { return &tmpfsMount{readonly: readonly, idmap: f.idmap}, nil } type tmpfsMount struct { readonly bool idmap *idtools.IdentityMapping } func (m *tmpfsMount) Mount() ([]mount.Mount, func() error, error) { opt := []string{"nosuid"} if m.readonly { opt = append(opt, "ro") } return []mount.Mount{{ Type: "tmpfs", Source: "tmpfs", Options: opt, }}, func() error { return nil }, nil } func (m *tmpfsMount) IdentityMapping() *idtools.IdentityMapping { return m.idmap } var cacheRefsLocker = locker.New() var sharedCacheRefs = &cacheRefs{} type cacheRefs struct { mu sync.Mutex shares map[string]*cacheRefShare } // ClearActiveCacheMounts clears shared cache mounts currently in use. // Caller needs to hold CacheMountsLocker before calling func ClearActiveCacheMounts() { sharedCacheRefs.shares = nil } func CacheMountsLocker() sync.Locker { return &sharedCacheRefs.mu } func (r *cacheRefs) get(key string, fn func() (cache.MutableRef, error)) (cache.MutableRef, error) { r.mu.Lock() defer r.mu.Unlock() if r.shares == nil { r.shares = map[string]*cacheRefShare{} } share, ok := r.shares[key] if ok { return share.clone(), nil } mref, err := fn() if err != nil { return nil, err } share = &cacheRefShare{MutableRef: mref, main: r, key: key, refs: map[*cacheRef]struct{}{}} r.shares[key] = share return share.clone(), nil } type cacheRefShare struct { cache.MutableRef mu sync.Mutex refs map[*cacheRef]struct{} main *cacheRefs key string } func (r *cacheRefShare) clone() cache.MutableRef { cacheRef := &cacheRef{cacheRefShare: r} if cacheRefCloneHijack != nil { cacheRefCloneHijack() } r.mu.Lock() r.refs[cacheRef] = struct{}{} r.mu.Unlock() return cacheRef } func (r *cacheRefShare) release(ctx context.Context) error { if r.main != nil { delete(r.main.shares, r.key) } return r.MutableRef.Release(ctx) } var cacheRefReleaseHijack func() var cacheRefCloneHijack func() type cacheRef struct { *cacheRefShare } func (r *cacheRef) Release(ctx context.Context) error { if r.main != nil { r.main.mu.Lock() defer r.main.mu.Unlock() } r.mu.Lock() defer r.mu.Unlock() delete(r.refs, r) if len(r.refs) == 0 { if cacheRefReleaseHijack != nil { cacheRefReleaseHijack() } return r.release(ctx) } return nil } func parseExtraHosts(ips []*pb.HostIP) ([]executor.HostIP, error) { out := make([]executor.HostIP, len(ips)) for i, hip := range ips { ip := net.ParseIP(hip.IP) if ip == nil { return nil, errors.Errorf("failed to parse IP %s", hip.IP) } out[i] = executor.HostIP{ IP: ip, Host: hip.Host, } } return out, nil }
[ "\"BUILDKIT_DEBUG_EXEC_OUTPUT\"" ]
[]
[ "BUILDKIT_DEBUG_EXEC_OUTPUT" ]
[]
["BUILDKIT_DEBUG_EXEC_OUTPUT"]
go
1
0
rowboat/sql.py
import os import psycogreen.gevent from peewee import Expression from peewee import Proxy, OP, Model from playhouse.postgres_ext import PostgresqlExtDatabase psycogreen.gevent.patch_psycopg() REGISTERED_MODELS = [] # Create a database proxy we can setup post-init database = Proxy() OP['IRGX'] = 'irgx' def pg_regex_i(lhs, rhs): return Expression(lhs, OP.IRGX, rhs) class ModelBase(Model): class Meta: database = database @staticmethod def register(cls): REGISTERED_MODELS.append(cls) return cls def init_db(env): if env == 'docker': database.initialize(PostgresqlExtDatabase( 'rowboat', host='db', user='rowboat', port=int(os.getenv('PG_PORT', 5432)), autorollback=True)) else: database.initialize(PostgresqlExtDatabase( 'rowboat', user='rowboat', port=int(os.getenv('PG_PORT', 5432)), autorollback=True)) for model in REGISTERED_MODELS: model.create_table(True) if hasattr(model, 'SQL'): database.execute_sql(model.SQL) def reset_db(): init_db() for model in REGISTERED_MODELS: model.drop_table(True) model.create_table(True)
[]
[]
[ "PG_PORT" ]
[]
["PG_PORT"]
python
1
0
clients/google-api-services-content/v2.1/1.31.0/com/google/api/services/content/ShoppingContent.java
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.content; /** * Service definition for ShoppingContent (v2.1). * * <p> * Manage your product listings and accounts for Google Shopping * </p> * * <p> * For more information about this service, see the * <a href="https://developers.google.com/shopping-content/v2/" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link ShoppingContentRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class ShoppingContent extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 || (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 && com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)), "You are currently running with version %s of google-api-client. " + "You need at least version 1.31.1 of google-api-client to run version " + "1.31.0 of the Content API for Shopping library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://shoppingcontent.googleapis.com/"; /** * The default encoded mTLS root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.31 */ public static final String DEFAULT_MTLS_ROOT_URL = "https://shoppingcontent.mtls.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "content/v2.1/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public ShoppingContent(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ ShoppingContent(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Accounts collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Accounts.List request = content.accounts().list(parameters ...)} * </pre> * * @return the resource collection */ public Accounts accounts() { return new Accounts(); } /** * The "accounts" collection of methods. */ public class Accounts { /** * Returns information about the authenticated user. * * Create a request for the method "accounts.authinfo". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Authinfo#execute()} method to invoke the remote operation. * * @return the request */ public Authinfo authinfo() throws java.io.IOException { Authinfo result = new Authinfo(); initialize(result); return result; } public class Authinfo extends ShoppingContentRequest<com.google.api.services.content.model.AccountsAuthInfoResponse> { private static final String REST_PATH = "accounts/authinfo"; /** * Returns information about the authenticated user. * * Create a request for the method "accounts.authinfo". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Authinfo#execute()} method to invoke the remote operation. <p> * {@link * Authinfo#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected Authinfo() { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccountsAuthInfoResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Authinfo set$Xgafv(java.lang.String $Xgafv) { return (Authinfo) super.set$Xgafv($Xgafv); } @Override public Authinfo setAccessToken(java.lang.String accessToken) { return (Authinfo) super.setAccessToken(accessToken); } @Override public Authinfo setAlt(java.lang.String alt) { return (Authinfo) super.setAlt(alt); } @Override public Authinfo setCallback(java.lang.String callback) { return (Authinfo) super.setCallback(callback); } @Override public Authinfo setFields(java.lang.String fields) { return (Authinfo) super.setFields(fields); } @Override public Authinfo setKey(java.lang.String key) { return (Authinfo) super.setKey(key); } @Override public Authinfo setOauthToken(java.lang.String oauthToken) { return (Authinfo) super.setOauthToken(oauthToken); } @Override public Authinfo setPrettyPrint(java.lang.Boolean prettyPrint) { return (Authinfo) super.setPrettyPrint(prettyPrint); } @Override public Authinfo setQuotaUser(java.lang.String quotaUser) { return (Authinfo) super.setQuotaUser(quotaUser); } @Override public Authinfo setUploadType(java.lang.String uploadType) { return (Authinfo) super.setUploadType(uploadType); } @Override public Authinfo setUploadProtocol(java.lang.String uploadProtocol) { return (Authinfo) super.setUploadProtocol(uploadProtocol); } @Override public Authinfo set(String parameterName, Object value) { return (Authinfo) super.set(parameterName, value); } } /** * Claims the website of a Merchant Center sub-account. * * Create a request for the method "accounts.claimwebsite". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Claimwebsite#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account whose website is claimed. * @return the request */ public Claimwebsite claimwebsite(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Claimwebsite result = new Claimwebsite(merchantId, accountId); initialize(result); return result; } public class Claimwebsite extends ShoppingContentRequest<com.google.api.services.content.model.AccountsClaimWebsiteResponse> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}/claimwebsite"; /** * Claims the website of a Merchant Center sub-account. * * Create a request for the method "accounts.claimwebsite". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Claimwebsite#execute()} method to invoke the remote operation. <p> * {@link * Claimwebsite#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account whose website is claimed. * @since 1.13 */ protected Claimwebsite(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.AccountsClaimWebsiteResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Claimwebsite set$Xgafv(java.lang.String $Xgafv) { return (Claimwebsite) super.set$Xgafv($Xgafv); } @Override public Claimwebsite setAccessToken(java.lang.String accessToken) { return (Claimwebsite) super.setAccessToken(accessToken); } @Override public Claimwebsite setAlt(java.lang.String alt) { return (Claimwebsite) super.setAlt(alt); } @Override public Claimwebsite setCallback(java.lang.String callback) { return (Claimwebsite) super.setCallback(callback); } @Override public Claimwebsite setFields(java.lang.String fields) { return (Claimwebsite) super.setFields(fields); } @Override public Claimwebsite setKey(java.lang.String key) { return (Claimwebsite) super.setKey(key); } @Override public Claimwebsite setOauthToken(java.lang.String oauthToken) { return (Claimwebsite) super.setOauthToken(oauthToken); } @Override public Claimwebsite setPrettyPrint(java.lang.Boolean prettyPrint) { return (Claimwebsite) super.setPrettyPrint(prettyPrint); } @Override public Claimwebsite setQuotaUser(java.lang.String quotaUser) { return (Claimwebsite) super.setQuotaUser(quotaUser); } @Override public Claimwebsite setUploadType(java.lang.String uploadType) { return (Claimwebsite) super.setUploadType(uploadType); } @Override public Claimwebsite setUploadProtocol(java.lang.String uploadProtocol) { return (Claimwebsite) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Claimwebsite setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account whose website is claimed. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account whose website is claimed. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account whose website is claimed. */ public Claimwebsite setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** * Only available to selected merchants. When set to `True`, this flag removes any existing * claim on the requested website by another account and replaces it with a claim from this * account. */ @com.google.api.client.util.Key private java.lang.Boolean overwrite; /** Only available to selected merchants. When set to `True`, this flag removes any existing claim on the requested website by another account and replaces it with a claim from this account. */ public java.lang.Boolean getOverwrite() { return overwrite; } /** * Only available to selected merchants. When set to `True`, this flag removes any existing * claim on the requested website by another account and replaces it with a claim from this * account. */ public Claimwebsite setOverwrite(java.lang.Boolean overwrite) { this.overwrite = overwrite; return this; } @Override public Claimwebsite set(String parameterName, Object value) { return (Claimwebsite) super.set(parameterName, value); } } /** * Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-)accounts in a single * request. * * Create a request for the method "accounts.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.AccountsCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.AccountsCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.AccountsCustomBatchResponse> { private static final String REST_PATH = "accounts/batch"; /** * Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-)accounts in a single * request. * * Create a request for the method "accounts.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.AccountsCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.AccountsCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountsCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Deletes a Merchant Center sub-account. * * Create a request for the method "accounts.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account, and accountId must be the ID of * a sub-account of this account. * @param accountId The ID of the account. * @return the request */ public Delete delete(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Delete result = new Delete(merchantId, accountId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}"; /** * Deletes a Merchant Center sub-account. * * Create a request for the method "accounts.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account, and accountId must be the ID of * a sub-account of this account. * @param accountId The ID of the account. * @since 1.13 */ protected Delete(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. This must be a multi-client account, and accountId must be * the ID of a sub-account of this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account, and accountId must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. This must be a multi-client account, and accountId must be * the ID of a sub-account of this account. */ public Delete setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account. */ public Delete setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** Flag to delete sub-accounts with products. The default value is false. */ @com.google.api.client.util.Key private java.lang.Boolean force; /** Flag to delete sub-accounts with products. The default value is false. [default: false] */ public java.lang.Boolean getForce() { return force; } /** Flag to delete sub-accounts with products. The default value is false. */ public Delete setForce(java.lang.Boolean force) { this.force = force; return this; } /** * Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}. * * <p> * Boolean properties can have four possible values: * {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE} * or {@link Boolean#FALSE}. * </p> * * <p> * This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE} * and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}. * {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and * it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}. * </p> * * <p> * Flag to delete sub-accounts with products. The default value is false. * </p> */ public boolean isForce() { if (force == null || force == com.google.api.client.util.Data.NULL_BOOLEAN) { return false; } return force; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves a Merchant Center account. * * Create a request for the method "accounts.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Get result = new Get(merchantId, accountId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Account> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}"; /** * Retrieves a Merchant Center account. * * Create a request for the method "accounts.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Account.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account. */ public Get setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** * Controls which fields will be populated. Acceptable values are: "merchant" and "css". The * default value is "merchant". */ @com.google.api.client.util.Key private java.lang.String view; /** Controls which fields will be populated. Acceptable values are: "merchant" and "css". The default value is "merchant". */ public java.lang.String getView() { return view; } /** * Controls which fields will be populated. Acceptable values are: "merchant" and "css". The * default value is "merchant". */ public Get setView(java.lang.String view) { this.view = view; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Creates a Merchant Center sub-account. * * Create a request for the method "accounts.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account. * @param content the {@link com.google.api.services.content.model.Account} * @return the request */ public Insert insert(java.math.BigInteger merchantId, com.google.api.services.content.model.Account content) throws java.io.IOException { Insert result = new Insert(merchantId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.Account> { private static final String REST_PATH = "{merchantId}/accounts"; /** * Creates a Merchant Center sub-account. * * Create a request for the method "accounts.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account. * @param content the {@link com.google.api.services.content.model.Account} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, com.google.api.services.content.model.Account content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.Account.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. This must be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. This must be a multi-client account. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Performs an action on a link between two Merchant Center accounts, namely accountId and * linkedAccountId. * * Create a request for the method "accounts.link". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Link#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account that should be linked. * @param content the {@link com.google.api.services.content.model.AccountsLinkRequest} * @return the request */ public Link link(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.AccountsLinkRequest content) throws java.io.IOException { Link result = new Link(merchantId, accountId, content); initialize(result); return result; } public class Link extends ShoppingContentRequest<com.google.api.services.content.model.AccountsLinkResponse> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}/link"; /** * Performs an action on a link between two Merchant Center accounts, namely accountId and * linkedAccountId. * * Create a request for the method "accounts.link". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Link#execute()} method to invoke the remote operation. <p> {@link * Link#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account that should be linked. * @param content the {@link com.google.api.services.content.model.AccountsLinkRequest} * @since 1.13 */ protected Link(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.AccountsLinkRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountsLinkResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Link set$Xgafv(java.lang.String $Xgafv) { return (Link) super.set$Xgafv($Xgafv); } @Override public Link setAccessToken(java.lang.String accessToken) { return (Link) super.setAccessToken(accessToken); } @Override public Link setAlt(java.lang.String alt) { return (Link) super.setAlt(alt); } @Override public Link setCallback(java.lang.String callback) { return (Link) super.setCallback(callback); } @Override public Link setFields(java.lang.String fields) { return (Link) super.setFields(fields); } @Override public Link setKey(java.lang.String key) { return (Link) super.setKey(key); } @Override public Link setOauthToken(java.lang.String oauthToken) { return (Link) super.setOauthToken(oauthToken); } @Override public Link setPrettyPrint(java.lang.Boolean prettyPrint) { return (Link) super.setPrettyPrint(prettyPrint); } @Override public Link setQuotaUser(java.lang.String quotaUser) { return (Link) super.setQuotaUser(quotaUser); } @Override public Link setUploadType(java.lang.String uploadType) { return (Link) super.setUploadType(uploadType); } @Override public Link setUploadProtocol(java.lang.String uploadProtocol) { return (Link) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Link setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account that should be linked. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account that should be linked. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account that should be linked. */ public Link setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Link set(String parameterName, Object value) { return (Link) super.set(parameterName, value); } } /** * Lists the sub-accounts in your Merchant Center account. * * Create a request for the method "accounts.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.AccountsListResponse> { private static final String REST_PATH = "{merchantId}/accounts"; /** * Lists the sub-accounts in your Merchant Center account. * * Create a request for the method "accounts.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccountsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. This must be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. This must be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** If view is set to "css", only return accounts that are assigned label with given ID. */ @com.google.api.client.util.Key private java.math.BigInteger label; /** If view is set to "css", only return accounts that are assigned label with given ID. */ public java.math.BigInteger getLabel() { return label; } /** If view is set to "css", only return accounts that are assigned label with given ID. */ public List setLabel(java.math.BigInteger label) { this.label = label; return this; } /** The maximum number of accounts to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of accounts to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of accounts to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * Controls which fields will be populated. Acceptable values are: "merchant" and "css". The * default value is "merchant". */ @com.google.api.client.util.Key private java.lang.String view; /** Controls which fields will be populated. Acceptable values are: "merchant" and "css". The default value is "merchant". */ public java.lang.String getView() { return view; } /** * Controls which fields will be populated. Acceptable values are: "merchant" and "css". The * default value is "merchant". */ public List setView(java.lang.String view) { this.view = view; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Returns the list of accounts linked to your Merchant Center account. * * Create a request for the method "accounts.listlinks". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Listlinks#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to list links. * @return the request */ public Listlinks listlinks(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Listlinks result = new Listlinks(merchantId, accountId); initialize(result); return result; } public class Listlinks extends ShoppingContentRequest<com.google.api.services.content.model.AccountsListLinksResponse> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}/listlinks"; /** * Returns the list of accounts linked to your Merchant Center account. * * Create a request for the method "accounts.listlinks". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Listlinks#execute()} method to invoke the remote operation. <p> * {@link * Listlinks#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to list links. * @since 1.13 */ protected Listlinks(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccountsListLinksResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Listlinks set$Xgafv(java.lang.String $Xgafv) { return (Listlinks) super.set$Xgafv($Xgafv); } @Override public Listlinks setAccessToken(java.lang.String accessToken) { return (Listlinks) super.setAccessToken(accessToken); } @Override public Listlinks setAlt(java.lang.String alt) { return (Listlinks) super.setAlt(alt); } @Override public Listlinks setCallback(java.lang.String callback) { return (Listlinks) super.setCallback(callback); } @Override public Listlinks setFields(java.lang.String fields) { return (Listlinks) super.setFields(fields); } @Override public Listlinks setKey(java.lang.String key) { return (Listlinks) super.setKey(key); } @Override public Listlinks setOauthToken(java.lang.String oauthToken) { return (Listlinks) super.setOauthToken(oauthToken); } @Override public Listlinks setPrettyPrint(java.lang.Boolean prettyPrint) { return (Listlinks) super.setPrettyPrint(prettyPrint); } @Override public Listlinks setQuotaUser(java.lang.String quotaUser) { return (Listlinks) super.setQuotaUser(quotaUser); } @Override public Listlinks setUploadType(java.lang.String uploadType) { return (Listlinks) super.setUploadType(uploadType); } @Override public Listlinks setUploadProtocol(java.lang.String uploadProtocol) { return (Listlinks) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Listlinks setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to list links. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to list links. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to list links. */ public Listlinks setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** The maximum number of links to return in the response, used for pagination. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of links to return in the response, used for pagination. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of links to return in the response, used for pagination. */ public Listlinks setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public Listlinks setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public Listlinks set(String parameterName, Object value) { return (Listlinks) super.set(parameterName, value); } } /** * Updates a Merchant Center account. Any fields that are not provided are deleted from the * resource. * * Create a request for the method "accounts.update". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account. * @param content the {@link com.google.api.services.content.model.Account} * @return the request */ public Update update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.Account content) throws java.io.IOException { Update result = new Update(merchantId, accountId, content); initialize(result); return result; } public class Update extends ShoppingContentRequest<com.google.api.services.content.model.Account> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}"; /** * Updates a Merchant Center account. Any fields that are not provided are deleted from the * resource. * * Create a request for the method "accounts.update". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account. * @param content the {@link com.google.api.services.content.model.Account} * @since 1.13 */ protected Update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.Account content) { super(ShoppingContent.this, "PUT", REST_PATH, content, com.google.api.services.content.model.Account.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Update setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account. */ public Update setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } /** * Updates labels that are assigned to the Merchant Center account by CSS user. * * Create a request for the method "accounts.updatelabels". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Updatelabels#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. * @param accountId The ID of the account whose labels are updated. * @param content the {@link com.google.api.services.content.model.AccountsUpdateLabelsRequest} * @return the request */ public Updatelabels updatelabels(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.AccountsUpdateLabelsRequest content) throws java.io.IOException { Updatelabels result = new Updatelabels(merchantId, accountId, content); initialize(result); return result; } public class Updatelabels extends ShoppingContentRequest<com.google.api.services.content.model.AccountsUpdateLabelsResponse> { private static final String REST_PATH = "{merchantId}/accounts/{accountId}/updatelabels"; /** * Updates labels that are assigned to the Merchant Center account by CSS user. * * Create a request for the method "accounts.updatelabels". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Updatelabels#execute()} method to invoke the remote operation. <p> * {@link * Updatelabels#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. * @param accountId The ID of the account whose labels are updated. * @param content the {@link com.google.api.services.content.model.AccountsUpdateLabelsRequest} * @since 1.13 */ protected Updatelabels(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.AccountsUpdateLabelsRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountsUpdateLabelsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Updatelabels set$Xgafv(java.lang.String $Xgafv) { return (Updatelabels) super.set$Xgafv($Xgafv); } @Override public Updatelabels setAccessToken(java.lang.String accessToken) { return (Updatelabels) super.setAccessToken(accessToken); } @Override public Updatelabels setAlt(java.lang.String alt) { return (Updatelabels) super.setAlt(alt); } @Override public Updatelabels setCallback(java.lang.String callback) { return (Updatelabels) super.setCallback(callback); } @Override public Updatelabels setFields(java.lang.String fields) { return (Updatelabels) super.setFields(fields); } @Override public Updatelabels setKey(java.lang.String key) { return (Updatelabels) super.setKey(key); } @Override public Updatelabels setOauthToken(java.lang.String oauthToken) { return (Updatelabels) super.setOauthToken(oauthToken); } @Override public Updatelabels setPrettyPrint(java.lang.Boolean prettyPrint) { return (Updatelabels) super.setPrettyPrint(prettyPrint); } @Override public Updatelabels setQuotaUser(java.lang.String quotaUser) { return (Updatelabels) super.setQuotaUser(quotaUser); } @Override public Updatelabels setUploadType(java.lang.String uploadType) { return (Updatelabels) super.setUploadType(uploadType); } @Override public Updatelabels setUploadProtocol(java.lang.String uploadProtocol) { return (Updatelabels) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. */ public Updatelabels setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account whose labels are updated. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account whose labels are updated. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account whose labels are updated. */ public Updatelabels setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Updatelabels set(String parameterName, Object value) { return (Updatelabels) super.set(parameterName, value); } } /** * An accessor for creating requests from the Credentials collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Credentials.List request = content.credentials().list(parameters ...)} * </pre> * * @return the resource collection */ public Credentials credentials() { return new Credentials(); } /** * The "credentials" collection of methods. */ public class Credentials { /** * Uploads credentials for the Merchant Center account. If credentials already exist for this * Merchant Center account and purpose, this method updates them. * * Create a request for the method "credentials.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param accountId Required. The merchant id of the account these credentials belong to. * @param content the {@link com.google.api.services.content.model.AccountCredentials} * @return the request */ public Create create(java.lang.Long accountId, com.google.api.services.content.model.AccountCredentials content) throws java.io.IOException { Create result = new Create(accountId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.AccountCredentials> { private static final String REST_PATH = "accounts/{accountId}/credentials"; /** * Uploads credentials for the Merchant Center account. If credentials already exist for this * Merchant Center account and purpose, this method updates them. * * Create a request for the method "credentials.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The merchant id of the account these credentials belong to. * @param content the {@link com.google.api.services.content.model.AccountCredentials} * @since 1.13 */ protected Create(java.lang.Long accountId, com.google.api.services.content.model.AccountCredentials content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountCredentials.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** Required. The merchant id of the account these credentials belong to. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The merchant id of the account these credentials belong to. */ public java.lang.Long getAccountId() { return accountId; } /** Required. The merchant id of the account these credentials belong to. */ public Create setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Labels collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Labels.List request = content.labels().list(parameters ...)} * </pre> * * @return the resource collection */ public Labels labels() { return new Labels(); } /** * The "labels" collection of methods. */ public class Labels { /** * Creates a new label, not assigned to any account. * * Create a request for the method "labels.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param accountId Required. The id of the account this label belongs to. * @param content the {@link com.google.api.services.content.model.AccountLabel} * @return the request */ public Create create(java.lang.Long accountId, com.google.api.services.content.model.AccountLabel content) throws java.io.IOException { Create result = new Create(accountId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.AccountLabel> { private static final String REST_PATH = "accounts/{accountId}/labels"; /** * Creates a new label, not assigned to any account. * * Create a request for the method "labels.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The id of the account this label belongs to. * @param content the {@link com.google.api.services.content.model.AccountLabel} * @since 1.13 */ protected Create(java.lang.Long accountId, com.google.api.services.content.model.AccountLabel content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountLabel.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the account this label belongs to. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The id of the account this label belongs to. */ public java.lang.Long getAccountId() { return accountId; } /** Required. The id of the account this label belongs to. */ public Create setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a label and removes it from all accounts to which it was assigned. * * Create a request for the method "labels.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param accountId Required. The id of the account that owns the label. * @param labelId Required. The id of the label to delete. * @return the request */ public Delete delete(java.lang.Long accountId, java.lang.Long labelId) throws java.io.IOException { Delete result = new Delete(accountId, labelId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "accounts/{accountId}/labels/{labelId}"; /** * Deletes a label and removes it from all accounts to which it was assigned. * * Create a request for the method "labels.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The id of the account that owns the label. * @param labelId Required. The id of the label to delete. * @since 1.13 */ protected Delete(java.lang.Long accountId, java.lang.Long labelId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.labelId = com.google.api.client.util.Preconditions.checkNotNull(labelId, "Required parameter labelId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the account that owns the label. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The id of the account that owns the label. */ public java.lang.Long getAccountId() { return accountId; } /** Required. The id of the account that owns the label. */ public Delete setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } /** Required. The id of the label to delete. */ @com.google.api.client.util.Key private java.lang.Long labelId; /** Required. The id of the label to delete. */ public java.lang.Long getLabelId() { return labelId; } /** Required. The id of the label to delete. */ public Delete setLabelId(java.lang.Long labelId) { this.labelId = labelId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Lists the labels assigned to an account. * * Create a request for the method "labels.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param accountId Required. The account id for whose labels are to be listed. * @return the request */ public List list(java.lang.Long accountId) throws java.io.IOException { List result = new List(accountId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListAccountLabelsResponse> { private static final String REST_PATH = "accounts/{accountId}/labels"; /** * Lists the labels assigned to an account. * * Create a request for the method "labels.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The account id for whose labels are to be listed. * @since 1.13 */ protected List(java.lang.Long accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListAccountLabelsResponse.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** Required. The account id for whose labels are to be listed. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The account id for whose labels are to be listed. */ public java.lang.Long getAccountId() { return accountId; } /** Required. The account id for whose labels are to be listed. */ public List setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } /** * The maximum number of labels to return. The service may return fewer than this value. If * unspecified, at most 50 labels will be returned. The maximum value is 1000; values above * 1000 will be coerced to 1000. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The maximum number of labels to return. The service may return fewer than this value. If unspecified, at most 50 labels will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. */ public java.lang.Integer getPageSize() { return pageSize; } /** * The maximum number of labels to return. The service may return fewer than this value. If * unspecified, at most 50 labels will be returned. The maximum value is 1000; values above * 1000 will be coerced to 1000. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A page token, received from a previous `ListAccountLabels` call. Provide this to retrieve * the subsequent page. When paginating, all other parameters provided to * `ListAccountLabels` must match the call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A page token, received from a previous `ListAccountLabels` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListAccountLabels` must match the call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * A page token, received from a previous `ListAccountLabels` call. Provide this to retrieve * the subsequent page. When paginating, all other parameters provided to * `ListAccountLabels` must match the call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a label. * * Create a request for the method "labels.patch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param accountId Required. The id of the account this label belongs to. * @param labelId Required. The id of the label to update. * @param content the {@link com.google.api.services.content.model.AccountLabel} * @return the request */ public Patch patch(java.lang.Long accountId, java.lang.Long labelId, com.google.api.services.content.model.AccountLabel content) throws java.io.IOException { Patch result = new Patch(accountId, labelId, content); initialize(result); return result; } public class Patch extends ShoppingContentRequest<com.google.api.services.content.model.AccountLabel> { private static final String REST_PATH = "accounts/{accountId}/labels/{labelId}"; /** * Updates a label. * * Create a request for the method "labels.patch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The id of the account this label belongs to. * @param labelId Required. The id of the label to update. * @param content the {@link com.google.api.services.content.model.AccountLabel} * @since 1.13 */ protected Patch(java.lang.Long accountId, java.lang.Long labelId, com.google.api.services.content.model.AccountLabel content) { super(ShoppingContent.this, "PATCH", REST_PATH, content, com.google.api.services.content.model.AccountLabel.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.labelId = com.google.api.client.util.Preconditions.checkNotNull(labelId, "Required parameter labelId must be specified."); } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the account this label belongs to. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The id of the account this label belongs to. */ public java.lang.Long getAccountId() { return accountId; } /** Required. The id of the account this label belongs to. */ public Patch setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } /** Required. The id of the label to update. */ @com.google.api.client.util.Key private java.lang.Long labelId; /** Required. The id of the label to update. */ public java.lang.Long getLabelId() { return labelId; } /** Required. The id of the label to update. */ public Patch setLabelId(java.lang.Long labelId) { this.labelId = labelId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Returncarrier collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Returncarrier.List request = content.returncarrier().list(parameters ...)} * </pre> * * @return the resource collection */ public Returncarrier returncarrier() { return new Returncarrier(); } /** * The "returncarrier" collection of methods. */ public class Returncarrier { /** * Links return carrier to a merchant account. * * Create a request for the method "returncarrier.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @param content the {@link com.google.api.services.content.model.AccountReturnCarrier} * @return the request */ public Create create(java.lang.Long accountId, com.google.api.services.content.model.AccountReturnCarrier content) throws java.io.IOException { Create result = new Create(accountId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.AccountReturnCarrier> { private static final String REST_PATH = "accounts/{accountId}/returncarrier"; /** * Links return carrier to a merchant account. * * Create a request for the method "returncarrier.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @param content the {@link com.google.api.services.content.model.AccountReturnCarrier} * @since 1.13 */ protected Create(java.lang.Long accountId, com.google.api.services.content.model.AccountReturnCarrier content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountReturnCarrier.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public java.lang.Long getAccountId() { return accountId; } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public Create setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Delete a return carrier in the merchant account. * * Create a request for the method "returncarrier.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @param carrierAccountId Required. The Google-provided unique carrier ID, used to update the resource. * @return the request */ public Delete delete(java.lang.Long accountId, java.lang.Long carrierAccountId) throws java.io.IOException { Delete result = new Delete(accountId, carrierAccountId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "accounts/{accountId}/returncarrier/{carrierAccountId}"; /** * Delete a return carrier in the merchant account. * * Create a request for the method "returncarrier.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @param carrierAccountId Required. The Google-provided unique carrier ID, used to update the resource. * @since 1.13 */ protected Delete(java.lang.Long accountId, java.lang.Long carrierAccountId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.carrierAccountId = com.google.api.client.util.Preconditions.checkNotNull(carrierAccountId, "Required parameter carrierAccountId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public java.lang.Long getAccountId() { return accountId; } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public Delete setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } /** Required. The Google-provided unique carrier ID, used to update the resource. */ @com.google.api.client.util.Key private java.lang.Long carrierAccountId; /** Required. The Google-provided unique carrier ID, used to update the resource. */ public java.lang.Long getCarrierAccountId() { return carrierAccountId; } /** Required. The Google-provided unique carrier ID, used to update the resource. */ public Delete setCarrierAccountId(java.lang.Long carrierAccountId) { this.carrierAccountId = carrierAccountId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Lists available return carriers in the merchant account. * * Create a request for the method "returncarrier.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @return the request */ public List list(java.lang.Long accountId) throws java.io.IOException { List result = new List(accountId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListAccountReturnCarrierResponse> { private static final String REST_PATH = "accounts/{accountId}/returncarrier"; /** * Lists available return carriers in the merchant account. * * Create a request for the method "returncarrier.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @since 1.13 */ protected List(java.lang.Long accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListAccountReturnCarrierResponse.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public java.lang.Long getAccountId() { return accountId; } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public List setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a return carrier in the merchant account. * * Create a request for the method "returncarrier.patch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @param carrierAccountId Required. The Google-provided unique carrier ID, used to update the resource. * @param content the {@link com.google.api.services.content.model.AccountReturnCarrier} * @return the request */ public Patch patch(java.lang.Long accountId, java.lang.Long carrierAccountId, com.google.api.services.content.model.AccountReturnCarrier content) throws java.io.IOException { Patch result = new Patch(accountId, carrierAccountId, content); initialize(result); return result; } public class Patch extends ShoppingContentRequest<com.google.api.services.content.model.AccountReturnCarrier> { private static final String REST_PATH = "accounts/{accountId}/returncarrier/{carrierAccountId}"; /** * Updates a return carrier in the merchant account. * * Create a request for the method "returncarrier.patch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param accountId Required. The Merchant Center Account Id under which the Return Carrier is to be linked. * @param carrierAccountId Required. The Google-provided unique carrier ID, used to update the resource. * @param content the {@link com.google.api.services.content.model.AccountReturnCarrier} * @since 1.13 */ protected Patch(java.lang.Long accountId, java.lang.Long carrierAccountId, com.google.api.services.content.model.AccountReturnCarrier content) { super(ShoppingContent.this, "PATCH", REST_PATH, content, com.google.api.services.content.model.AccountReturnCarrier.class); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.carrierAccountId = com.google.api.client.util.Preconditions.checkNotNull(carrierAccountId, "Required parameter carrierAccountId must be specified."); } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ @com.google.api.client.util.Key private java.lang.Long accountId; /** Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public java.lang.Long getAccountId() { return accountId; } /** * Required. The Merchant Center Account Id under which the Return Carrier is to be linked. */ public Patch setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } /** Required. The Google-provided unique carrier ID, used to update the resource. */ @com.google.api.client.util.Key private java.lang.Long carrierAccountId; /** Required. The Google-provided unique carrier ID, used to update the resource. */ public java.lang.Long getCarrierAccountId() { return carrierAccountId; } /** Required. The Google-provided unique carrier ID, used to update the resource. */ public Patch setCarrierAccountId(java.lang.Long carrierAccountId) { this.carrierAccountId = carrierAccountId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } } } /** * An accessor for creating requests from the Accountstatuses collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Accountstatuses.List request = content.accountstatuses().list(parameters ...)} * </pre> * * @return the resource collection */ public Accountstatuses accountstatuses() { return new Accountstatuses(); } /** * The "accountstatuses" collection of methods. */ public class Accountstatuses { /** * Retrieves multiple Merchant Center account statuses in a single request. * * Create a request for the method "accountstatuses.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.AccountstatusesCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.AccountstatusesCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.AccountstatusesCustomBatchResponse> { private static final String REST_PATH = "accountstatuses/batch"; /** * Retrieves multiple Merchant Center account statuses in a single request. * * Create a request for the method "accountstatuses.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.AccountstatusesCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.AccountstatusesCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccountstatusesCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Retrieves the status of a Merchant Center account. No itemLevelIssues are returned for multi- * client accounts. * * Create a request for the method "accountstatuses.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Get result = new Get(merchantId, accountId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.AccountStatus> { private static final String REST_PATH = "{merchantId}/accountstatuses/{accountId}"; /** * Retrieves the status of a Merchant Center account. No itemLevelIssues are returned for multi- * client accounts. * * Create a request for the method "accountstatuses.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccountStatus.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account. */ public Get setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinations; /** If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination. */ public java.util.List<java.lang.String> getDestinations() { return destinations; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ public Get setDestinations(java.util.List<java.lang.String> destinations) { this.destinations = destinations; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the statuses of the sub-accounts in your Merchant Center account. * * Create a request for the method "accountstatuses.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.AccountstatusesListResponse> { private static final String REST_PATH = "{merchantId}/accountstatuses"; /** * Lists the statuses of the sub-accounts in your Merchant Center account. * * Create a request for the method "accountstatuses.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccountstatusesListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. This must be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. This must be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinations; /** If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination. */ public java.util.List<java.lang.String> getDestinations() { return destinations; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ public List setDestinations(java.util.List<java.lang.String> destinations) { this.destinations = destinations; return this; } /** The maximum number of account statuses to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of account statuses to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of account statuses to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Accounttax collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Accounttax.List request = content.accounttax().list(parameters ...)} * </pre> * * @return the resource collection */ public Accounttax accounttax() { return new Accounttax(); } /** * The "accounttax" collection of methods. */ public class Accounttax { /** * Retrieves and updates tax settings of multiple accounts in a single request. * * Create a request for the method "accounttax.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.AccounttaxCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.AccounttaxCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.AccounttaxCustomBatchResponse> { private static final String REST_PATH = "accounttax/batch"; /** * Retrieves and updates tax settings of multiple accounts in a single request. * * Create a request for the method "accounttax.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.AccounttaxCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.AccounttaxCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.AccounttaxCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Retrieves the tax settings of the account. * * Create a request for the method "accounttax.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update account tax settings. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Get result = new Get(merchantId, accountId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.AccountTax> { private static final String REST_PATH = "{merchantId}/accounttax/{accountId}"; /** * Retrieves the tax settings of the account. * * Create a request for the method "accounttax.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update account tax settings. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccountTax.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to get/update account tax settings. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to get/update account tax settings. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to get/update account tax settings. */ public Get setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the tax settings of the sub-accounts in your Merchant Center account. * * Create a request for the method "accounttax.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.AccounttaxListResponse> { private static final String REST_PATH = "{merchantId}/accounttax"; /** * Lists the tax settings of the sub-accounts in your Merchant Center account. * * Create a request for the method "accounttax.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.AccounttaxListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. This must be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. This must be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The maximum number of tax settings to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of tax settings to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of tax settings to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates the tax settings of the account. Any fields that are not provided are deleted from the * resource. * * Create a request for the method "accounttax.update". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update account tax settings. * @param content the {@link com.google.api.services.content.model.AccountTax} * @return the request */ public Update update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.AccountTax content) throws java.io.IOException { Update result = new Update(merchantId, accountId, content); initialize(result); return result; } public class Update extends ShoppingContentRequest<com.google.api.services.content.model.AccountTax> { private static final String REST_PATH = "{merchantId}/accounttax/{accountId}"; /** * Updates the tax settings of the account. Any fields that are not provided are deleted from the * resource. * * Create a request for the method "accounttax.update". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update account tax settings. * @param content the {@link com.google.api.services.content.model.AccountTax} * @since 1.13 */ protected Update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.AccountTax content) { super(ShoppingContent.this, "PUT", REST_PATH, content, com.google.api.services.content.model.AccountTax.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Update setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to get/update account tax settings. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to get/update account tax settings. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to get/update account tax settings. */ public Update setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Buyongoogleprograms collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Buyongoogleprograms.List request = content.buyongoogleprograms().list(parameters ...)} * </pre> * * @return the resource collection */ public Buyongoogleprograms buyongoogleprograms() { return new Buyongoogleprograms(); } /** * The "buyongoogleprograms" collection of methods. */ public class Buyongoogleprograms { /** * Reactivates the BoG program in your Merchant Center account. Moves the program to the active * state when allowed, e.g. when paused. Important: This method is only whitelisted for selected * merchants. * * Create a request for the method "buyongoogleprograms.activate". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Activate#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.ActivateBuyOnGoogleProgramRequest} * @return the request */ public Activate activate(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.ActivateBuyOnGoogleProgramRequest content) throws java.io.IOException { Activate result = new Activate(merchantId, regionCode, content); initialize(result); return result; } public class Activate extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/buyongoogleprograms/{regionCode}/activate"; /** * Reactivates the BoG program in your Merchant Center account. Moves the program to the active * state when allowed, e.g. when paused. Important: This method is only whitelisted for selected * merchants. * * Create a request for the method "buyongoogleprograms.activate". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Activate#execute()} method to invoke the remote operation. <p> * {@link * Activate#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.ActivateBuyOnGoogleProgramRequest} * @since 1.13 */ protected Activate(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.ActivateBuyOnGoogleProgramRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionCode = com.google.api.client.util.Preconditions.checkNotNull(regionCode, "Required parameter regionCode must be specified."); } @Override public Activate set$Xgafv(java.lang.String $Xgafv) { return (Activate) super.set$Xgafv($Xgafv); } @Override public Activate setAccessToken(java.lang.String accessToken) { return (Activate) super.setAccessToken(accessToken); } @Override public Activate setAlt(java.lang.String alt) { return (Activate) super.setAlt(alt); } @Override public Activate setCallback(java.lang.String callback) { return (Activate) super.setCallback(callback); } @Override public Activate setFields(java.lang.String fields) { return (Activate) super.setFields(fields); } @Override public Activate setKey(java.lang.String key) { return (Activate) super.setKey(key); } @Override public Activate setOauthToken(java.lang.String oauthToken) { return (Activate) super.setOauthToken(oauthToken); } @Override public Activate setPrettyPrint(java.lang.Boolean prettyPrint) { return (Activate) super.setPrettyPrint(prettyPrint); } @Override public Activate setQuotaUser(java.lang.String quotaUser) { return (Activate) super.setQuotaUser(quotaUser); } @Override public Activate setUploadType(java.lang.String uploadType) { return (Activate) super.setUploadType(uploadType); } @Override public Activate setUploadProtocol(java.lang.String uploadProtocol) { return (Activate) super.setUploadProtocol(uploadProtocol); } /** Required. The ID of the account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The ID of the account. */ public Activate setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ @com.google.api.client.util.Key private java.lang.String regionCode; /** The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public java.lang.String getRegionCode() { return regionCode; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public Activate setRegionCode(java.lang.String regionCode) { this.regionCode = regionCode; return this; } @Override public Activate set(String parameterName, Object value) { return (Activate) super.set(parameterName, value); } } /** * Retrieves a status of the BoG program for your Merchant Center account. * * Create a request for the method "buyongoogleprograms.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account. * @param regionCode The Program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @return the request */ public Get get(java.lang.Long merchantId, java.lang.String regionCode) throws java.io.IOException { Get result = new Get(merchantId, regionCode); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.BuyOnGoogleProgramStatus> { private static final String REST_PATH = "{merchantId}/buyongoogleprograms/{regionCode}"; /** * Retrieves a status of the BoG program for your Merchant Center account. * * Create a request for the method "buyongoogleprograms.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account. * @param regionCode The Program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @since 1.13 */ protected Get(java.lang.Long merchantId, java.lang.String regionCode) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.BuyOnGoogleProgramStatus.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionCode = com.google.api.client.util.Preconditions.checkNotNull(regionCode, "Required parameter regionCode must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Required. The ID of the account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The ID of the account. */ public Get setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The Program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ @com.google.api.client.util.Key private java.lang.String regionCode; /** The Program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public java.lang.String getRegionCode() { return regionCode; } /** * The Program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public Get setRegionCode(java.lang.String regionCode) { this.regionCode = regionCode; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Onboards the BoG program in your Merchant Center account. By using this method, you agree to the * [Terms of Service](https://merchants.google.com/mc/termsofservice/transactions/US/latest). * Calling this method is only possible if the authenticated account is the same as the merchant id * in the request. Calling this method multiple times will only accept Terms of Service if the * latest version is not currently signed. * * Create a request for the method "buyongoogleprograms.onboard". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Onboard#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.OnboardBuyOnGoogleProgramRequest} * @return the request */ public Onboard onboard(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.OnboardBuyOnGoogleProgramRequest content) throws java.io.IOException { Onboard result = new Onboard(merchantId, regionCode, content); initialize(result); return result; } public class Onboard extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/buyongoogleprograms/{regionCode}/onboard"; /** * Onboards the BoG program in your Merchant Center account. By using this method, you agree to * the [Terms of Service](https://merchants.google.com/mc/termsofservice/transactions/US/latest). * Calling this method is only possible if the authenticated account is the same as the merchant * id in the request. Calling this method multiple times will only accept Terms of Service if the * latest version is not currently signed. * * Create a request for the method "buyongoogleprograms.onboard". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Onboard#execute()} method to invoke the remote operation. <p> * {@link * Onboard#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.OnboardBuyOnGoogleProgramRequest} * @since 1.13 */ protected Onboard(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.OnboardBuyOnGoogleProgramRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionCode = com.google.api.client.util.Preconditions.checkNotNull(regionCode, "Required parameter regionCode must be specified."); } @Override public Onboard set$Xgafv(java.lang.String $Xgafv) { return (Onboard) super.set$Xgafv($Xgafv); } @Override public Onboard setAccessToken(java.lang.String accessToken) { return (Onboard) super.setAccessToken(accessToken); } @Override public Onboard setAlt(java.lang.String alt) { return (Onboard) super.setAlt(alt); } @Override public Onboard setCallback(java.lang.String callback) { return (Onboard) super.setCallback(callback); } @Override public Onboard setFields(java.lang.String fields) { return (Onboard) super.setFields(fields); } @Override public Onboard setKey(java.lang.String key) { return (Onboard) super.setKey(key); } @Override public Onboard setOauthToken(java.lang.String oauthToken) { return (Onboard) super.setOauthToken(oauthToken); } @Override public Onboard setPrettyPrint(java.lang.Boolean prettyPrint) { return (Onboard) super.setPrettyPrint(prettyPrint); } @Override public Onboard setQuotaUser(java.lang.String quotaUser) { return (Onboard) super.setQuotaUser(quotaUser); } @Override public Onboard setUploadType(java.lang.String uploadType) { return (Onboard) super.setUploadType(uploadType); } @Override public Onboard setUploadProtocol(java.lang.String uploadProtocol) { return (Onboard) super.setUploadProtocol(uploadProtocol); } /** Required. The ID of the account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The ID of the account. */ public Onboard setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ @com.google.api.client.util.Key private java.lang.String regionCode; /** The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public java.lang.String getRegionCode() { return regionCode; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public Onboard setRegionCode(java.lang.String regionCode) { this.regionCode = regionCode; return this; } @Override public Onboard set(String parameterName, Object value) { return (Onboard) super.set(parameterName, value); } } /** * Pauses the BoG program in your Merchant Center account. Important: This method is only * whitelisted for selected merchants. * * Create a request for the method "buyongoogleprograms.pause". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Pause#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.PauseBuyOnGoogleProgramRequest} * @return the request */ public Pause pause(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.PauseBuyOnGoogleProgramRequest content) throws java.io.IOException { Pause result = new Pause(merchantId, regionCode, content); initialize(result); return result; } public class Pause extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/buyongoogleprograms/{regionCode}/pause"; /** * Pauses the BoG program in your Merchant Center account. Important: This method is only * whitelisted for selected merchants. * * Create a request for the method "buyongoogleprograms.pause". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Pause#execute()} method to invoke the remote operation. <p> {@link * Pause#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.PauseBuyOnGoogleProgramRequest} * @since 1.13 */ protected Pause(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.PauseBuyOnGoogleProgramRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionCode = com.google.api.client.util.Preconditions.checkNotNull(regionCode, "Required parameter regionCode must be specified."); } @Override public Pause set$Xgafv(java.lang.String $Xgafv) { return (Pause) super.set$Xgafv($Xgafv); } @Override public Pause setAccessToken(java.lang.String accessToken) { return (Pause) super.setAccessToken(accessToken); } @Override public Pause setAlt(java.lang.String alt) { return (Pause) super.setAlt(alt); } @Override public Pause setCallback(java.lang.String callback) { return (Pause) super.setCallback(callback); } @Override public Pause setFields(java.lang.String fields) { return (Pause) super.setFields(fields); } @Override public Pause setKey(java.lang.String key) { return (Pause) super.setKey(key); } @Override public Pause setOauthToken(java.lang.String oauthToken) { return (Pause) super.setOauthToken(oauthToken); } @Override public Pause setPrettyPrint(java.lang.Boolean prettyPrint) { return (Pause) super.setPrettyPrint(prettyPrint); } @Override public Pause setQuotaUser(java.lang.String quotaUser) { return (Pause) super.setQuotaUser(quotaUser); } @Override public Pause setUploadType(java.lang.String uploadType) { return (Pause) super.setUploadType(uploadType); } @Override public Pause setUploadProtocol(java.lang.String uploadProtocol) { return (Pause) super.setUploadProtocol(uploadProtocol); } /** Required. The ID of the account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The ID of the account. */ public Pause setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ @com.google.api.client.util.Key private java.lang.String regionCode; /** The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public java.lang.String getRegionCode() { return regionCode; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public Pause setRegionCode(java.lang.String regionCode) { this.regionCode = regionCode; return this; } @Override public Pause set(String parameterName, Object value) { return (Pause) super.set(parameterName, value); } } /** * Requests review and then activates the BoG program in your Merchant Center account for the first * time. Moves the program to the REVIEW_PENDING state. Important: This method is only whitelisted * for selected merchants. * * Create a request for the method "buyongoogleprograms.requestreview". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Requestreview#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.RequestReviewBuyOnGoogleProgramRequest} * @return the request */ public Requestreview requestreview(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.RequestReviewBuyOnGoogleProgramRequest content) throws java.io.IOException { Requestreview result = new Requestreview(merchantId, regionCode, content); initialize(result); return result; } public class Requestreview extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/buyongoogleprograms/{regionCode}/requestreview"; /** * Requests review and then activates the BoG program in your Merchant Center account for the * first time. Moves the program to the REVIEW_PENDING state. Important: This method is only * whitelisted for selected merchants. * * Create a request for the method "buyongoogleprograms.requestreview". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Requestreview#execute()} method to invoke the remote operation. <p> * {@link Requestreview#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR * equest)} must be called to initialize this instance immediately after invoking the constructor. * </p> * * @param merchantId Required. The ID of the account. * @param regionCode The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). * Currently only US is available. * @param content the {@link com.google.api.services.content.model.RequestReviewBuyOnGoogleProgramRequest} * @since 1.13 */ protected Requestreview(java.lang.Long merchantId, java.lang.String regionCode, com.google.api.services.content.model.RequestReviewBuyOnGoogleProgramRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionCode = com.google.api.client.util.Preconditions.checkNotNull(regionCode, "Required parameter regionCode must be specified."); } @Override public Requestreview set$Xgafv(java.lang.String $Xgafv) { return (Requestreview) super.set$Xgafv($Xgafv); } @Override public Requestreview setAccessToken(java.lang.String accessToken) { return (Requestreview) super.setAccessToken(accessToken); } @Override public Requestreview setAlt(java.lang.String alt) { return (Requestreview) super.setAlt(alt); } @Override public Requestreview setCallback(java.lang.String callback) { return (Requestreview) super.setCallback(callback); } @Override public Requestreview setFields(java.lang.String fields) { return (Requestreview) super.setFields(fields); } @Override public Requestreview setKey(java.lang.String key) { return (Requestreview) super.setKey(key); } @Override public Requestreview setOauthToken(java.lang.String oauthToken) { return (Requestreview) super.setOauthToken(oauthToken); } @Override public Requestreview setPrettyPrint(java.lang.Boolean prettyPrint) { return (Requestreview) super.setPrettyPrint(prettyPrint); } @Override public Requestreview setQuotaUser(java.lang.String quotaUser) { return (Requestreview) super.setQuotaUser(quotaUser); } @Override public Requestreview setUploadType(java.lang.String uploadType) { return (Requestreview) super.setUploadType(uploadType); } @Override public Requestreview setUploadProtocol(java.lang.String uploadProtocol) { return (Requestreview) super.setUploadProtocol(uploadProtocol); } /** Required. The ID of the account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The ID of the account. */ public Requestreview setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ @com.google.api.client.util.Key private java.lang.String regionCode; /** The program region code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public java.lang.String getRegionCode() { return regionCode; } /** * The program region code [ISO 3166-1 * alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). Currently only US is available. */ public Requestreview setRegionCode(java.lang.String regionCode) { this.regionCode = regionCode; return this; } @Override public Requestreview set(String parameterName, Object value) { return (Requestreview) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Collections collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Collections.List request = content.collections().list(parameters ...)} * </pre> * * @return the resource collection */ public Collections collections() { return new Collections(); } /** * The "collections" collection of methods. */ public class Collections { /** * Uploads a collection to your Merchant Center account. If a collection with the same collectionId * already exists, this method updates that entry. In each update, the collection is completely * replaced by the fields in the body of the update request. * * Create a request for the method "collections.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param content the {@link com.google.api.services.content.model.Collection} * @return the request */ public Create create(java.lang.Long merchantId, com.google.api.services.content.model.Collection content) throws java.io.IOException { Create result = new Create(merchantId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.Collection> { private static final String REST_PATH = "{merchantId}/collections"; /** * Uploads a collection to your Merchant Center account. If a collection with the same * collectionId already exists, this method updates that entry. In each update, the collection is * completely replaced by the fields in the body of the update request. * * Create a request for the method "collections.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param content the {@link com.google.api.services.content.model.Collection} * @since 1.13 */ protected Create(java.lang.Long merchantId, com.google.api.services.content.model.Collection content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.Collection.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account that contains the collection. This account cannot be a multi-client account. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ public Create setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a collection from your Merchant Center account. * * Create a request for the method "collections.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param collectionId Required. The collectionId of the collection. CollectionId is the same as the REST ID of the * collection. * @return the request */ public Delete delete(java.lang.Long merchantId, java.lang.String collectionId) throws java.io.IOException { Delete result = new Delete(merchantId, collectionId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/collections/{collectionId}"; /** * Deletes a collection from your Merchant Center account. * * Create a request for the method "collections.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param collectionId Required. The collectionId of the collection. CollectionId is the same as the REST ID of the * collection. * @since 1.13 */ protected Delete(java.lang.Long merchantId, java.lang.String collectionId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.collectionId = com.google.api.client.util.Preconditions.checkNotNull(collectionId, "Required parameter collectionId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account that contains the collection. This account cannot be a multi-client account. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ public Delete setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * Required. The collectionId of the collection. CollectionId is the same as the REST ID of * the collection. */ @com.google.api.client.util.Key private java.lang.String collectionId; /** Required. The collectionId of the collection. CollectionId is the same as the REST ID of the collection. */ public java.lang.String getCollectionId() { return collectionId; } /** * Required. The collectionId of the collection. CollectionId is the same as the REST ID of * the collection. */ public Delete setCollectionId(java.lang.String collectionId) { this.collectionId = collectionId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves a collection from your Merchant Center account. * * Create a request for the method "collections.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param collectionId Required. The REST ID of the collection. * @return the request */ public Get get(java.lang.Long merchantId, java.lang.String collectionId) throws java.io.IOException { Get result = new Get(merchantId, collectionId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Collection> { private static final String REST_PATH = "{merchantId}/collections/{collectionId}"; /** * Retrieves a collection from your Merchant Center account. * * Create a request for the method "collections.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param collectionId Required. The REST ID of the collection. * @since 1.13 */ protected Get(java.lang.Long merchantId, java.lang.String collectionId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Collection.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.collectionId = com.google.api.client.util.Preconditions.checkNotNull(collectionId, "Required parameter collectionId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account that contains the collection. This account cannot be a multi-client account. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ public Get setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The REST ID of the collection. */ @com.google.api.client.util.Key private java.lang.String collectionId; /** Required. The REST ID of the collection. */ public java.lang.String getCollectionId() { return collectionId; } /** Required. The REST ID of the collection. */ public Get setCollectionId(java.lang.String collectionId) { this.collectionId = collectionId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the collections in your Merchant Center account. The response might contain fewer items * than specified by page_size. Rely on next_page_token to determine if there are more items to be * requested. * * Create a request for the method "collections.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @return the request */ public List list(java.lang.Long merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListCollectionsResponse> { private static final String REST_PATH = "{merchantId}/collections"; /** * Lists the collections in your Merchant Center account. The response might contain fewer items * than specified by page_size. Rely on next_page_token to determine if there are more items to be * requested. * * Create a request for the method "collections.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @since 1.13 */ protected List(java.lang.Long merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListCollectionsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account that contains the collection. This account cannot be a multi-client account. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The maximum number of collections to return in the response, used for paging. Defaults to * 50; values above 1000 will be coerced to 1000. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The maximum number of collections to return in the response, used for paging. Defaults to 50; values above 1000 will be coerced to 1000. */ public java.lang.Integer getPageSize() { return pageSize; } /** * The maximum number of collections to return in the response, used for paging. Defaults to * 50; values above 1000 will be coerced to 1000. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** Token (if provided) to retrieve the subsequent page. All other parameters must match the original call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Collectionstatuses collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Collectionstatuses.List request = content.collectionstatuses().list(parameters ...)} * </pre> * * @return the resource collection */ public Collectionstatuses collectionstatuses() { return new Collectionstatuses(); } /** * The "collectionstatuses" collection of methods. */ public class Collectionstatuses { /** * Gets the status of a collection from your Merchant Center account. * * Create a request for the method "collectionstatuses.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param collectionId Required. The collectionId of the collection. CollectionId is the same as the REST ID of the * collection. * @return the request */ public Get get(java.lang.Long merchantId, java.lang.String collectionId) throws java.io.IOException { Get result = new Get(merchantId, collectionId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.CollectionStatus> { private static final String REST_PATH = "{merchantId}/collectionstatuses/{collectionId}"; /** * Gets the status of a collection from your Merchant Center account. * * Create a request for the method "collectionstatuses.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @param collectionId Required. The collectionId of the collection. CollectionId is the same as the REST ID of the * collection. * @since 1.13 */ protected Get(java.lang.Long merchantId, java.lang.String collectionId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.CollectionStatus.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.collectionId = com.google.api.client.util.Preconditions.checkNotNull(collectionId, "Required parameter collectionId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account that contains the collection. This account cannot be a multi-client account. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ public Get setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * Required. The collectionId of the collection. CollectionId is the same as the REST ID of * the collection. */ @com.google.api.client.util.Key private java.lang.String collectionId; /** Required. The collectionId of the collection. CollectionId is the same as the REST ID of the collection. */ public java.lang.String getCollectionId() { return collectionId; } /** * Required. The collectionId of the collection. CollectionId is the same as the REST ID of * the collection. */ public Get setCollectionId(java.lang.String collectionId) { this.collectionId = collectionId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the statuses of the collections in your Merchant Center account. * * Create a request for the method "collectionstatuses.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @return the request */ public List list(java.lang.Long merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListCollectionStatusesResponse> { private static final String REST_PATH = "{merchantId}/collectionstatuses"; /** * Lists the statuses of the collections in your Merchant Center account. * * Create a request for the method "collectionstatuses.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The ID of the account that contains the collection. This account cannot be a multi-client * account. * @since 1.13 */ protected List(java.lang.Long merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListCollectionStatusesResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The ID of the account that contains the collection. This account cannot be a multi-client account. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The ID of the account that contains the collection. This account cannot be a * multi-client account. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The maximum number of collection statuses to return in the response, used for paging. * Defaults to 50; values above 1000 will be coerced to 1000. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The maximum number of collection statuses to return in the response, used for paging. Defaults to 50; values above 1000 will be coerced to 1000. */ public java.lang.Integer getPageSize() { return pageSize; } /** * The maximum number of collection statuses to return in the response, used for paging. * Defaults to 50; values above 1000 will be coerced to 1000. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** Token (if provided) to retrieve the subsequent page. All other parameters must match the original call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Csses collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Csses.List request = content.csses().list(parameters ...)} * </pre> * * @return the resource collection */ public Csses csses() { return new Csses(); } /** * The "csses" collection of methods. */ public class Csses { /** * Retrieves a single CSS domain by ID. * * Create a request for the method "csses.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param cssGroupId Required. The ID of the managing account. If this parameter is not the same as * [cssDomainId](#cssDomainId), then this ID must be a CSS group ID and `cssDomainId` must be * the ID of a CSS domain affiliated with this group. * @param cssDomainId Required. The ID of the CSS domain to return. * @return the request */ public Get get(java.lang.Long cssGroupId, java.lang.Long cssDomainId) throws java.io.IOException { Get result = new Get(cssGroupId, cssDomainId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Css> { private static final String REST_PATH = "{cssGroupId}/csses/{cssDomainId}"; /** * Retrieves a single CSS domain by ID. * * Create a request for the method "csses.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param cssGroupId Required. The ID of the managing account. If this parameter is not the same as * [cssDomainId](#cssDomainId), then this ID must be a CSS group ID and `cssDomainId` must be * the ID of a CSS domain affiliated with this group. * @param cssDomainId Required. The ID of the CSS domain to return. * @since 1.13 */ protected Get(java.lang.Long cssGroupId, java.lang.Long cssDomainId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Css.class); this.cssGroupId = com.google.api.client.util.Preconditions.checkNotNull(cssGroupId, "Required parameter cssGroupId must be specified."); this.cssDomainId = com.google.api.client.util.Preconditions.checkNotNull(cssDomainId, "Required parameter cssDomainId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The ID of the managing account. If this parameter is not the same as * [cssDomainId](#cssDomainId), then this ID must be a CSS group ID and `cssDomainId` must be * the ID of a CSS domain affiliated with this group. */ @com.google.api.client.util.Key private java.lang.Long cssGroupId; /** Required. The ID of the managing account. If this parameter is not the same as [cssDomainId](#cssDomainId), then this ID must be a CSS group ID and `cssDomainId` must be the ID of a CSS domain affiliated with this group. */ public java.lang.Long getCssGroupId() { return cssGroupId; } /** * Required. The ID of the managing account. If this parameter is not the same as * [cssDomainId](#cssDomainId), then this ID must be a CSS group ID and `cssDomainId` must be * the ID of a CSS domain affiliated with this group. */ public Get setCssGroupId(java.lang.Long cssGroupId) { this.cssGroupId = cssGroupId; return this; } /** Required. The ID of the CSS domain to return. */ @com.google.api.client.util.Key private java.lang.Long cssDomainId; /** Required. The ID of the CSS domain to return. */ public java.lang.Long getCssDomainId() { return cssDomainId; } /** Required. The ID of the CSS domain to return. */ public Get setCssDomainId(java.lang.Long cssDomainId) { this.cssDomainId = cssDomainId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists CSS domains affiliated with a CSS group. * * Create a request for the method "csses.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param cssGroupId Required. The CSS group ID of CSS domains to be listed. * @return the request */ public List list(java.lang.Long cssGroupId) throws java.io.IOException { List result = new List(cssGroupId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListCssesResponse> { private static final String REST_PATH = "{cssGroupId}/csses"; /** * Lists CSS domains affiliated with a CSS group. * * Create a request for the method "csses.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param cssGroupId Required. The CSS group ID of CSS domains to be listed. * @since 1.13 */ protected List(java.lang.Long cssGroupId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListCssesResponse.class); this.cssGroupId = com.google.api.client.util.Preconditions.checkNotNull(cssGroupId, "Required parameter cssGroupId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** Required. The CSS group ID of CSS domains to be listed. */ @com.google.api.client.util.Key private java.lang.Long cssGroupId; /** Required. The CSS group ID of CSS domains to be listed. */ public java.lang.Long getCssGroupId() { return cssGroupId; } /** Required. The CSS group ID of CSS domains to be listed. */ public List setCssGroupId(java.lang.Long cssGroupId) { this.cssGroupId = cssGroupId; return this; } /** * The maximum number of CSS domains to return. The service may return fewer than this value. * If unspecified, at most 50 CSS domains will be returned. The maximum value is 1000; values * above 1000 will be coerced to 1000. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The maximum number of CSS domains to return. The service may return fewer than this value. If unspecified, at most 50 CSS domains will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. */ public java.lang.Integer getPageSize() { return pageSize; } /** * The maximum number of CSS domains to return. The service may return fewer than this value. * If unspecified, at most 50 CSS domains will be returned. The maximum value is 1000; values * above 1000 will be coerced to 1000. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A page token, received from a previous `ListCsses` call. Provide this to retrieve the * subsequent page. When paginating, all other parameters provided to `ListCsses` must match * the call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A page token, received from a previous `ListCsses` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListCsses` must match the call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * A page token, received from a previous `ListCsses` call. Provide this to retrieve the * subsequent page. When paginating, all other parameters provided to `ListCsses` must match * the call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates labels that are assigned to a CSS domain by its CSS group. * * Create a request for the method "csses.updatelabels". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Updatelabels#execute()} method to invoke the remote operation. * * @param cssGroupId Required. The CSS group ID of the updated CSS domain. * @param cssDomainId Required. The ID of the updated CSS domain. * @param content the {@link com.google.api.services.content.model.LabelIds} * @return the request */ public Updatelabels updatelabels(java.lang.Long cssGroupId, java.lang.Long cssDomainId, com.google.api.services.content.model.LabelIds content) throws java.io.IOException { Updatelabels result = new Updatelabels(cssGroupId, cssDomainId, content); initialize(result); return result; } public class Updatelabels extends ShoppingContentRequest<com.google.api.services.content.model.Css> { private static final String REST_PATH = "{cssGroupId}/csses/{cssDomainId}/updatelabels"; /** * Updates labels that are assigned to a CSS domain by its CSS group. * * Create a request for the method "csses.updatelabels". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Updatelabels#execute()} method to invoke the remote operation. <p> * {@link * Updatelabels#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param cssGroupId Required. The CSS group ID of the updated CSS domain. * @param cssDomainId Required. The ID of the updated CSS domain. * @param content the {@link com.google.api.services.content.model.LabelIds} * @since 1.13 */ protected Updatelabels(java.lang.Long cssGroupId, java.lang.Long cssDomainId, com.google.api.services.content.model.LabelIds content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.Css.class); this.cssGroupId = com.google.api.client.util.Preconditions.checkNotNull(cssGroupId, "Required parameter cssGroupId must be specified."); this.cssDomainId = com.google.api.client.util.Preconditions.checkNotNull(cssDomainId, "Required parameter cssDomainId must be specified."); } @Override public Updatelabels set$Xgafv(java.lang.String $Xgafv) { return (Updatelabels) super.set$Xgafv($Xgafv); } @Override public Updatelabels setAccessToken(java.lang.String accessToken) { return (Updatelabels) super.setAccessToken(accessToken); } @Override public Updatelabels setAlt(java.lang.String alt) { return (Updatelabels) super.setAlt(alt); } @Override public Updatelabels setCallback(java.lang.String callback) { return (Updatelabels) super.setCallback(callback); } @Override public Updatelabels setFields(java.lang.String fields) { return (Updatelabels) super.setFields(fields); } @Override public Updatelabels setKey(java.lang.String key) { return (Updatelabels) super.setKey(key); } @Override public Updatelabels setOauthToken(java.lang.String oauthToken) { return (Updatelabels) super.setOauthToken(oauthToken); } @Override public Updatelabels setPrettyPrint(java.lang.Boolean prettyPrint) { return (Updatelabels) super.setPrettyPrint(prettyPrint); } @Override public Updatelabels setQuotaUser(java.lang.String quotaUser) { return (Updatelabels) super.setQuotaUser(quotaUser); } @Override public Updatelabels setUploadType(java.lang.String uploadType) { return (Updatelabels) super.setUploadType(uploadType); } @Override public Updatelabels setUploadProtocol(java.lang.String uploadProtocol) { return (Updatelabels) super.setUploadProtocol(uploadProtocol); } /** Required. The CSS group ID of the updated CSS domain. */ @com.google.api.client.util.Key private java.lang.Long cssGroupId; /** Required. The CSS group ID of the updated CSS domain. */ public java.lang.Long getCssGroupId() { return cssGroupId; } /** Required. The CSS group ID of the updated CSS domain. */ public Updatelabels setCssGroupId(java.lang.Long cssGroupId) { this.cssGroupId = cssGroupId; return this; } /** Required. The ID of the updated CSS domain. */ @com.google.api.client.util.Key private java.lang.Long cssDomainId; /** Required. The ID of the updated CSS domain. */ public java.lang.Long getCssDomainId() { return cssDomainId; } /** Required. The ID of the updated CSS domain. */ public Updatelabels setCssDomainId(java.lang.Long cssDomainId) { this.cssDomainId = cssDomainId; return this; } @Override public Updatelabels set(String parameterName, Object value) { return (Updatelabels) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Datafeeds collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Datafeeds.List request = content.datafeeds().list(parameters ...)} * </pre> * * @return the resource collection */ public Datafeeds datafeeds() { return new Datafeeds(); } /** * The "datafeeds" collection of methods. */ public class Datafeeds { /** * Deletes, fetches, gets, inserts and updates multiple datafeeds in a single request. * * Create a request for the method "datafeeds.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.DatafeedsCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.DatafeedsCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.DatafeedsCustomBatchResponse> { private static final String REST_PATH = "datafeeds/batch"; /** * Deletes, fetches, gets, inserts and updates multiple datafeeds in a single request. * * Create a request for the method "datafeeds.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.DatafeedsCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.DatafeedsCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.DatafeedsCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Deletes a datafeed configuration from your Merchant Center account. * * Create a request for the method "datafeeds.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @return the request */ public Delete delete(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) throws java.io.IOException { Delete result = new Delete(merchantId, datafeedId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/datafeeds/{datafeedId}"; /** * Deletes a datafeed configuration from your Merchant Center account. * * Create a request for the method "datafeeds.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @since 1.13 */ protected Delete(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.datafeedId = com.google.api.client.util.Preconditions.checkNotNull(datafeedId, "Required parameter datafeedId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeed. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ public Delete setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the datafeed. */ @com.google.api.client.util.Key private java.math.BigInteger datafeedId; /** The ID of the datafeed. */ public java.math.BigInteger getDatafeedId() { return datafeedId; } /** The ID of the datafeed. */ public Delete setDatafeedId(java.math.BigInteger datafeedId) { this.datafeedId = datafeedId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Invokes a fetch for the datafeed in your Merchant Center account. If you need to call this method * more than once per day, we recommend you use the Products service to update your product data. * * Create a request for the method "datafeeds.fetchnow". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Fetchnow#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed to be fetched. * @return the request */ public Fetchnow fetchnow(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) throws java.io.IOException { Fetchnow result = new Fetchnow(merchantId, datafeedId); initialize(result); return result; } public class Fetchnow extends ShoppingContentRequest<com.google.api.services.content.model.DatafeedsFetchNowResponse> { private static final String REST_PATH = "{merchantId}/datafeeds/{datafeedId}/fetchNow"; /** * Invokes a fetch for the datafeed in your Merchant Center account. If you need to call this * method more than once per day, we recommend you use the Products service to update your product * data. * * Create a request for the method "datafeeds.fetchnow". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Fetchnow#execute()} method to invoke the remote operation. <p> * {@link * Fetchnow#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed to be fetched. * @since 1.13 */ protected Fetchnow(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.DatafeedsFetchNowResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.datafeedId = com.google.api.client.util.Preconditions.checkNotNull(datafeedId, "Required parameter datafeedId must be specified."); } @Override public Fetchnow set$Xgafv(java.lang.String $Xgafv) { return (Fetchnow) super.set$Xgafv($Xgafv); } @Override public Fetchnow setAccessToken(java.lang.String accessToken) { return (Fetchnow) super.setAccessToken(accessToken); } @Override public Fetchnow setAlt(java.lang.String alt) { return (Fetchnow) super.setAlt(alt); } @Override public Fetchnow setCallback(java.lang.String callback) { return (Fetchnow) super.setCallback(callback); } @Override public Fetchnow setFields(java.lang.String fields) { return (Fetchnow) super.setFields(fields); } @Override public Fetchnow setKey(java.lang.String key) { return (Fetchnow) super.setKey(key); } @Override public Fetchnow setOauthToken(java.lang.String oauthToken) { return (Fetchnow) super.setOauthToken(oauthToken); } @Override public Fetchnow setPrettyPrint(java.lang.Boolean prettyPrint) { return (Fetchnow) super.setPrettyPrint(prettyPrint); } @Override public Fetchnow setQuotaUser(java.lang.String quotaUser) { return (Fetchnow) super.setQuotaUser(quotaUser); } @Override public Fetchnow setUploadType(java.lang.String uploadType) { return (Fetchnow) super.setUploadType(uploadType); } @Override public Fetchnow setUploadProtocol(java.lang.String uploadProtocol) { return (Fetchnow) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeed. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ public Fetchnow setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the datafeed to be fetched. */ @com.google.api.client.util.Key private java.math.BigInteger datafeedId; /** The ID of the datafeed to be fetched. */ public java.math.BigInteger getDatafeedId() { return datafeedId; } /** The ID of the datafeed to be fetched. */ public Fetchnow setDatafeedId(java.math.BigInteger datafeedId) { this.datafeedId = datafeedId; return this; } @Override public Fetchnow set(String parameterName, Object value) { return (Fetchnow) super.set(parameterName, value); } } /** * Retrieves a datafeed configuration from your Merchant Center account. * * Create a request for the method "datafeeds.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) throws java.io.IOException { Get result = new Get(merchantId, datafeedId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Datafeed> { private static final String REST_PATH = "{merchantId}/datafeeds/{datafeedId}"; /** * Retrieves a datafeed configuration from your Merchant Center account. * * Create a request for the method "datafeeds.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Datafeed.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.datafeedId = com.google.api.client.util.Preconditions.checkNotNull(datafeedId, "Required parameter datafeedId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeed. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the datafeed. */ @com.google.api.client.util.Key private java.math.BigInteger datafeedId; /** The ID of the datafeed. */ public java.math.BigInteger getDatafeedId() { return datafeedId; } /** The ID of the datafeed. */ public Get setDatafeedId(java.math.BigInteger datafeedId) { this.datafeedId = datafeedId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Registers a datafeed configuration with your Merchant Center account. * * Create a request for the method "datafeeds.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.Datafeed} * @return the request */ public Insert insert(java.math.BigInteger merchantId, com.google.api.services.content.model.Datafeed content) throws java.io.IOException { Insert result = new Insert(merchantId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.Datafeed> { private static final String REST_PATH = "{merchantId}/datafeeds"; /** * Registers a datafeed configuration with your Merchant Center account. * * Create a request for the method "datafeeds.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.Datafeed} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, com.google.api.services.content.model.Datafeed content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.Datafeed.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeed. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Lists the configurations for datafeeds in your Merchant Center account. * * Create a request for the method "datafeeds.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeeds. This account cannot be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.DatafeedsListResponse> { private static final String REST_PATH = "{merchantId}/datafeeds"; /** * Lists the configurations for datafeeds in your Merchant Center account. * * Create a request for the method "datafeeds.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeeds. This account cannot be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.DatafeedsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeeds. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeeds. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeeds. This account cannot be a multi-client * account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The maximum number of products to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of products to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of products to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a datafeed configuration of your Merchant Center account. Any fields that are not * provided are deleted from the resource. * * Create a request for the method "datafeeds.update". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @param content the {@link com.google.api.services.content.model.Datafeed} * @return the request */ public Update update(java.math.BigInteger merchantId, java.math.BigInteger datafeedId, com.google.api.services.content.model.Datafeed content) throws java.io.IOException { Update result = new Update(merchantId, datafeedId, content); initialize(result); return result; } public class Update extends ShoppingContentRequest<com.google.api.services.content.model.Datafeed> { private static final String REST_PATH = "{merchantId}/datafeeds/{datafeedId}"; /** * Updates a datafeed configuration of your Merchant Center account. Any fields that are not * provided are deleted from the resource. * * Create a request for the method "datafeeds.update". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @param content the {@link com.google.api.services.content.model.Datafeed} * @since 1.13 */ protected Update(java.math.BigInteger merchantId, java.math.BigInteger datafeedId, com.google.api.services.content.model.Datafeed content) { super(ShoppingContent.this, "PUT", REST_PATH, content, com.google.api.services.content.model.Datafeed.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.datafeedId = com.google.api.client.util.Preconditions.checkNotNull(datafeedId, "Required parameter datafeedId must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeed. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ public Update setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the datafeed. */ @com.google.api.client.util.Key private java.math.BigInteger datafeedId; /** The ID of the datafeed. */ public java.math.BigInteger getDatafeedId() { return datafeedId; } /** The ID of the datafeed. */ public Update setDatafeedId(java.math.BigInteger datafeedId) { this.datafeedId = datafeedId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Datafeedstatuses collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Datafeedstatuses.List request = content.datafeedstatuses().list(parameters ...)} * </pre> * * @return the resource collection */ public Datafeedstatuses datafeedstatuses() { return new Datafeedstatuses(); } /** * The "datafeedstatuses" collection of methods. */ public class Datafeedstatuses { /** * Gets multiple Merchant Center datafeed statuses in a single request. * * Create a request for the method "datafeedstatuses.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.DatafeedstatusesCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.DatafeedstatusesCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.DatafeedstatusesCustomBatchResponse> { private static final String REST_PATH = "datafeedstatuses/batch"; /** * Gets multiple Merchant Center datafeed statuses in a single request. * * Create a request for the method "datafeedstatuses.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.DatafeedstatusesCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.DatafeedstatusesCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.DatafeedstatusesCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Retrieves the status of a datafeed from your Merchant Center account. * * Create a request for the method "datafeedstatuses.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) throws java.io.IOException { Get result = new Get(merchantId, datafeedId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.DatafeedStatus> { private static final String REST_PATH = "{merchantId}/datafeedstatuses/{datafeedId}"; /** * Retrieves the status of a datafeed from your Merchant Center account. * * Create a request for the method "datafeedstatuses.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeed. This account cannot be a multi-client account. * @param datafeedId The ID of the datafeed. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger datafeedId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.DatafeedStatus.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.datafeedId = com.google.api.client.util.Preconditions.checkNotNull(datafeedId, "Required parameter datafeedId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeed. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeed. This account cannot be a multi-client * account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the datafeed. */ @com.google.api.client.util.Key private java.math.BigInteger datafeedId; /** The ID of the datafeed. */ public java.math.BigInteger getDatafeedId() { return datafeedId; } /** The ID of the datafeed. */ public Get setDatafeedId(java.math.BigInteger datafeedId) { this.datafeedId = datafeedId; return this; } /** * The country for which to get the datafeed status. If this parameter is provided then * language must also be provided. Note that this parameter is required for feeds targeting * multiple countries and languages, since a feed may have a different status for each target. */ @com.google.api.client.util.Key private java.lang.String country; /** The country for which to get the datafeed status. If this parameter is provided then language must also be provided. Note that this parameter is required for feeds targeting multiple countries and languages, since a feed may have a different status for each target. */ public java.lang.String getCountry() { return country; } /** * The country for which to get the datafeed status. If this parameter is provided then * language must also be provided. Note that this parameter is required for feeds targeting * multiple countries and languages, since a feed may have a different status for each target. */ public Get setCountry(java.lang.String country) { this.country = country; return this; } /** * The language for which to get the datafeed status. If this parameter is provided then * country must also be provided. Note that this parameter is required for feeds targeting * multiple countries and languages, since a feed may have a different status for each target. */ @com.google.api.client.util.Key private java.lang.String language; /** The language for which to get the datafeed status. If this parameter is provided then country must also be provided. Note that this parameter is required for feeds targeting multiple countries and languages, since a feed may have a different status for each target. */ public java.lang.String getLanguage() { return language; } /** * The language for which to get the datafeed status. If this parameter is provided then * country must also be provided. Note that this parameter is required for feeds targeting * multiple countries and languages, since a feed may have a different status for each target. */ public Get setLanguage(java.lang.String language) { this.language = language; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the statuses of the datafeeds in your Merchant Center account. * * Create a request for the method "datafeedstatuses.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the datafeeds. This account cannot be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.DatafeedstatusesListResponse> { private static final String REST_PATH = "{merchantId}/datafeedstatuses"; /** * Lists the statuses of the datafeeds in your Merchant Center account. * * Create a request for the method "datafeedstatuses.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the datafeeds. This account cannot be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.DatafeedstatusesListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that manages the datafeeds. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the datafeeds. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that manages the datafeeds. This account cannot be a multi-client * account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The maximum number of products to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of products to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of products to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Liasettings collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Liasettings.List request = content.liasettings().list(parameters ...)} * </pre> * * @return the resource collection */ public Liasettings liasettings() { return new Liasettings(); } /** * The "liasettings" collection of methods. */ public class Liasettings { /** * Retrieves and/or updates the LIA settings of multiple accounts in a single request. * * Create a request for the method "liasettings.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.LiasettingsCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.LiasettingsCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsCustomBatchResponse> { private static final String REST_PATH = "liasettings/batch"; /** * Retrieves and/or updates the LIA settings of multiple accounts in a single request. * * Create a request for the method "liasettings.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.LiasettingsCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.LiasettingsCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.LiasettingsCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Retrieves the LIA settings of the account. * * Create a request for the method "liasettings.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get or update LIA settings. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Get result = new Get(merchantId, accountId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.LiaSettings> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}"; /** * Retrieves the LIA settings of the account. * * Create a request for the method "liasettings.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get or update LIA settings. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.LiaSettings.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to get or update LIA settings. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to get or update LIA settings. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to get or update LIA settings. */ public Get setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves the list of accessible Google My Business accounts. * * Create a request for the method "liasettings.getaccessiblegmbaccounts". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Getaccessiblegmbaccounts#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to retrieve accessible Google My Business accounts. * @return the request */ public Getaccessiblegmbaccounts getaccessiblegmbaccounts(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Getaccessiblegmbaccounts result = new Getaccessiblegmbaccounts(merchantId, accountId); initialize(result); return result; } public class Getaccessiblegmbaccounts extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsGetAccessibleGmbAccountsResponse> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}/accessiblegmbaccounts"; /** * Retrieves the list of accessible Google My Business accounts. * * Create a request for the method "liasettings.getaccessiblegmbaccounts". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Getaccessiblegmbaccounts#execute()} method to invoke the remote * operation. <p> {@link Getaccessiblegmbaccounts#initialize(com.google.api.client.googleapis.serv * ices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to retrieve accessible Google My Business accounts. * @since 1.13 */ protected Getaccessiblegmbaccounts(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.LiasettingsGetAccessibleGmbAccountsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Getaccessiblegmbaccounts set$Xgafv(java.lang.String $Xgafv) { return (Getaccessiblegmbaccounts) super.set$Xgafv($Xgafv); } @Override public Getaccessiblegmbaccounts setAccessToken(java.lang.String accessToken) { return (Getaccessiblegmbaccounts) super.setAccessToken(accessToken); } @Override public Getaccessiblegmbaccounts setAlt(java.lang.String alt) { return (Getaccessiblegmbaccounts) super.setAlt(alt); } @Override public Getaccessiblegmbaccounts setCallback(java.lang.String callback) { return (Getaccessiblegmbaccounts) super.setCallback(callback); } @Override public Getaccessiblegmbaccounts setFields(java.lang.String fields) { return (Getaccessiblegmbaccounts) super.setFields(fields); } @Override public Getaccessiblegmbaccounts setKey(java.lang.String key) { return (Getaccessiblegmbaccounts) super.setKey(key); } @Override public Getaccessiblegmbaccounts setOauthToken(java.lang.String oauthToken) { return (Getaccessiblegmbaccounts) super.setOauthToken(oauthToken); } @Override public Getaccessiblegmbaccounts setPrettyPrint(java.lang.Boolean prettyPrint) { return (Getaccessiblegmbaccounts) super.setPrettyPrint(prettyPrint); } @Override public Getaccessiblegmbaccounts setQuotaUser(java.lang.String quotaUser) { return (Getaccessiblegmbaccounts) super.setQuotaUser(quotaUser); } @Override public Getaccessiblegmbaccounts setUploadType(java.lang.String uploadType) { return (Getaccessiblegmbaccounts) super.setUploadType(uploadType); } @Override public Getaccessiblegmbaccounts setUploadProtocol(java.lang.String uploadProtocol) { return (Getaccessiblegmbaccounts) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Getaccessiblegmbaccounts setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to retrieve accessible Google My Business accounts. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to retrieve accessible Google My Business accounts. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to retrieve accessible Google My Business accounts. */ public Getaccessiblegmbaccounts setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Getaccessiblegmbaccounts set(String parameterName, Object value) { return (Getaccessiblegmbaccounts) super.set(parameterName, value); } } /** * Lists the LIA settings of the sub-accounts in your Merchant Center account. * * Create a request for the method "liasettings.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsListResponse> { private static final String REST_PATH = "{merchantId}/liasettings"; /** * Lists the LIA settings of the sub-accounts in your Merchant Center account. * * Create a request for the method "liasettings.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.LiasettingsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. This must be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. This must be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The maximum number of LIA settings to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of LIA settings to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of LIA settings to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Retrieves the list of POS data providers that have active settings for the all eiligible * countries. * * Create a request for the method "liasettings.listposdataproviders". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Listposdataproviders#execute()} method to invoke the remote * operation. * * @return the request */ public Listposdataproviders listposdataproviders() throws java.io.IOException { Listposdataproviders result = new Listposdataproviders(); initialize(result); return result; } public class Listposdataproviders extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsListPosDataProvidersResponse> { private static final String REST_PATH = "liasettings/posdataproviders"; /** * Retrieves the list of POS data providers that have active settings for the all eiligible * countries. * * Create a request for the method "liasettings.listposdataproviders". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Listposdataproviders#execute()} method to invoke the remote * operation. <p> {@link Listposdataproviders#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @since 1.13 */ protected Listposdataproviders() { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.LiasettingsListPosDataProvidersResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Listposdataproviders set$Xgafv(java.lang.String $Xgafv) { return (Listposdataproviders) super.set$Xgafv($Xgafv); } @Override public Listposdataproviders setAccessToken(java.lang.String accessToken) { return (Listposdataproviders) super.setAccessToken(accessToken); } @Override public Listposdataproviders setAlt(java.lang.String alt) { return (Listposdataproviders) super.setAlt(alt); } @Override public Listposdataproviders setCallback(java.lang.String callback) { return (Listposdataproviders) super.setCallback(callback); } @Override public Listposdataproviders setFields(java.lang.String fields) { return (Listposdataproviders) super.setFields(fields); } @Override public Listposdataproviders setKey(java.lang.String key) { return (Listposdataproviders) super.setKey(key); } @Override public Listposdataproviders setOauthToken(java.lang.String oauthToken) { return (Listposdataproviders) super.setOauthToken(oauthToken); } @Override public Listposdataproviders setPrettyPrint(java.lang.Boolean prettyPrint) { return (Listposdataproviders) super.setPrettyPrint(prettyPrint); } @Override public Listposdataproviders setQuotaUser(java.lang.String quotaUser) { return (Listposdataproviders) super.setQuotaUser(quotaUser); } @Override public Listposdataproviders setUploadType(java.lang.String uploadType) { return (Listposdataproviders) super.setUploadType(uploadType); } @Override public Listposdataproviders setUploadProtocol(java.lang.String uploadProtocol) { return (Listposdataproviders) super.setUploadProtocol(uploadProtocol); } @Override public Listposdataproviders set(String parameterName, Object value) { return (Listposdataproviders) super.set(parameterName, value); } } /** * Requests access to a specified Google My Business account. * * Create a request for the method "liasettings.requestgmbaccess". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Requestgmbaccess#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which GMB access is requested. * @param gmbEmail The email of the Google My Business account. * @return the request */ public Requestgmbaccess requestgmbaccess(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String gmbEmail) throws java.io.IOException { Requestgmbaccess result = new Requestgmbaccess(merchantId, accountId, gmbEmail); initialize(result); return result; } public class Requestgmbaccess extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsRequestGmbAccessResponse> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}/requestgmbaccess"; /** * Requests access to a specified Google My Business account. * * Create a request for the method "liasettings.requestgmbaccess". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Requestgmbaccess#execute()} method to invoke the remote operation. * <p> {@link Requestgmbaccess#initialize(com.google.api.client.googleapis.services.AbstractGoogle * ClientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which GMB access is requested. * @param gmbEmail The email of the Google My Business account. * @since 1.13 */ protected Requestgmbaccess(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String gmbEmail) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.LiasettingsRequestGmbAccessResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.gmbEmail = com.google.api.client.util.Preconditions.checkNotNull(gmbEmail, "Required parameter gmbEmail must be specified."); } @Override public Requestgmbaccess set$Xgafv(java.lang.String $Xgafv) { return (Requestgmbaccess) super.set$Xgafv($Xgafv); } @Override public Requestgmbaccess setAccessToken(java.lang.String accessToken) { return (Requestgmbaccess) super.setAccessToken(accessToken); } @Override public Requestgmbaccess setAlt(java.lang.String alt) { return (Requestgmbaccess) super.setAlt(alt); } @Override public Requestgmbaccess setCallback(java.lang.String callback) { return (Requestgmbaccess) super.setCallback(callback); } @Override public Requestgmbaccess setFields(java.lang.String fields) { return (Requestgmbaccess) super.setFields(fields); } @Override public Requestgmbaccess setKey(java.lang.String key) { return (Requestgmbaccess) super.setKey(key); } @Override public Requestgmbaccess setOauthToken(java.lang.String oauthToken) { return (Requestgmbaccess) super.setOauthToken(oauthToken); } @Override public Requestgmbaccess setPrettyPrint(java.lang.Boolean prettyPrint) { return (Requestgmbaccess) super.setPrettyPrint(prettyPrint); } @Override public Requestgmbaccess setQuotaUser(java.lang.String quotaUser) { return (Requestgmbaccess) super.setQuotaUser(quotaUser); } @Override public Requestgmbaccess setUploadType(java.lang.String uploadType) { return (Requestgmbaccess) super.setUploadType(uploadType); } @Override public Requestgmbaccess setUploadProtocol(java.lang.String uploadProtocol) { return (Requestgmbaccess) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Requestgmbaccess setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which GMB access is requested. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which GMB access is requested. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which GMB access is requested. */ public Requestgmbaccess setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** The email of the Google My Business account. */ @com.google.api.client.util.Key private java.lang.String gmbEmail; /** The email of the Google My Business account. */ public java.lang.String getGmbEmail() { return gmbEmail; } /** The email of the Google My Business account. */ public Requestgmbaccess setGmbEmail(java.lang.String gmbEmail) { this.gmbEmail = gmbEmail; return this; } @Override public Requestgmbaccess set(String parameterName, Object value) { return (Requestgmbaccess) super.set(parameterName, value); } } /** * Requests inventory validation for the specified country. * * Create a request for the method "liasettings.requestinventoryverification". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Requestinventoryverification#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account that manages the order. This cannot be a multi-client account. * @param country The country for which inventory validation is requested. * @return the request */ public Requestinventoryverification requestinventoryverification(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String country) throws java.io.IOException { Requestinventoryverification result = new Requestinventoryverification(merchantId, accountId, country); initialize(result); return result; } public class Requestinventoryverification extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsRequestInventoryVerificationResponse> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}/requestinventoryverification/{country}"; /** * Requests inventory validation for the specified country. * * Create a request for the method "liasettings.requestinventoryverification". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Requestinventoryverification#execute()} method to invoke the remote * operation. <p> {@link Requestinventoryverification#initialize(com.google.api.client.googleapis. * services.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account that manages the order. This cannot be a multi-client account. * @param country The country for which inventory validation is requested. * @since 1.13 */ protected Requestinventoryverification(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String country) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.LiasettingsRequestInventoryVerificationResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.country = com.google.api.client.util.Preconditions.checkNotNull(country, "Required parameter country must be specified."); } @Override public Requestinventoryverification set$Xgafv(java.lang.String $Xgafv) { return (Requestinventoryverification) super.set$Xgafv($Xgafv); } @Override public Requestinventoryverification setAccessToken(java.lang.String accessToken) { return (Requestinventoryverification) super.setAccessToken(accessToken); } @Override public Requestinventoryverification setAlt(java.lang.String alt) { return (Requestinventoryverification) super.setAlt(alt); } @Override public Requestinventoryverification setCallback(java.lang.String callback) { return (Requestinventoryverification) super.setCallback(callback); } @Override public Requestinventoryverification setFields(java.lang.String fields) { return (Requestinventoryverification) super.setFields(fields); } @Override public Requestinventoryverification setKey(java.lang.String key) { return (Requestinventoryverification) super.setKey(key); } @Override public Requestinventoryverification setOauthToken(java.lang.String oauthToken) { return (Requestinventoryverification) super.setOauthToken(oauthToken); } @Override public Requestinventoryverification setPrettyPrint(java.lang.Boolean prettyPrint) { return (Requestinventoryverification) super.setPrettyPrint(prettyPrint); } @Override public Requestinventoryverification setQuotaUser(java.lang.String quotaUser) { return (Requestinventoryverification) super.setQuotaUser(quotaUser); } @Override public Requestinventoryverification setUploadType(java.lang.String uploadType) { return (Requestinventoryverification) super.setUploadType(uploadType); } @Override public Requestinventoryverification setUploadProtocol(java.lang.String uploadProtocol) { return (Requestinventoryverification) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Requestinventoryverification setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Requestinventoryverification setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** The country for which inventory validation is requested. */ @com.google.api.client.util.Key private java.lang.String country; /** The country for which inventory validation is requested. */ public java.lang.String getCountry() { return country; } /** The country for which inventory validation is requested. */ public Requestinventoryverification setCountry(java.lang.String country) { this.country = country; return this; } @Override public Requestinventoryverification set(String parameterName, Object value) { return (Requestinventoryverification) super.set(parameterName, value); } } /** * Sets the inventory verification contract for the specified country. * * Create a request for the method "liasettings.setinventoryverificationcontact". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Setinventoryverificationcontact#execute()} method to invoke the * remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account that manages the order. This cannot be a multi-client account. * @param country The country for which inventory verification is requested. * @param language The language for which inventory verification is requested. * @param contactName The name of the inventory verification contact. * @param contactEmail The email of the inventory verification contact. * @return the request */ public Setinventoryverificationcontact setinventoryverificationcontact(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String country, java.lang.String language, java.lang.String contactName, java.lang.String contactEmail) throws java.io.IOException { Setinventoryverificationcontact result = new Setinventoryverificationcontact(merchantId, accountId, country, language, contactName, contactEmail); initialize(result); return result; } public class Setinventoryverificationcontact extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsSetInventoryVerificationContactResponse> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}/setinventoryverificationcontact"; /** * Sets the inventory verification contract for the specified country. * * Create a request for the method "liasettings.setinventoryverificationcontact". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Setinventoryverificationcontact#execute()} method to invoke the * remote operation. <p> {@link Setinventoryverificationcontact#initialize(com.google.api.client.g * oogleapis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account that manages the order. This cannot be a multi-client account. * @param country The country for which inventory verification is requested. * @param language The language for which inventory verification is requested. * @param contactName The name of the inventory verification contact. * @param contactEmail The email of the inventory verification contact. * @since 1.13 */ protected Setinventoryverificationcontact(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String country, java.lang.String language, java.lang.String contactName, java.lang.String contactEmail) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.LiasettingsSetInventoryVerificationContactResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.country = com.google.api.client.util.Preconditions.checkNotNull(country, "Required parameter country must be specified."); this.language = com.google.api.client.util.Preconditions.checkNotNull(language, "Required parameter language must be specified."); this.contactName = com.google.api.client.util.Preconditions.checkNotNull(contactName, "Required parameter contactName must be specified."); this.contactEmail = com.google.api.client.util.Preconditions.checkNotNull(contactEmail, "Required parameter contactEmail must be specified."); } @Override public Setinventoryverificationcontact set$Xgafv(java.lang.String $Xgafv) { return (Setinventoryverificationcontact) super.set$Xgafv($Xgafv); } @Override public Setinventoryverificationcontact setAccessToken(java.lang.String accessToken) { return (Setinventoryverificationcontact) super.setAccessToken(accessToken); } @Override public Setinventoryverificationcontact setAlt(java.lang.String alt) { return (Setinventoryverificationcontact) super.setAlt(alt); } @Override public Setinventoryverificationcontact setCallback(java.lang.String callback) { return (Setinventoryverificationcontact) super.setCallback(callback); } @Override public Setinventoryverificationcontact setFields(java.lang.String fields) { return (Setinventoryverificationcontact) super.setFields(fields); } @Override public Setinventoryverificationcontact setKey(java.lang.String key) { return (Setinventoryverificationcontact) super.setKey(key); } @Override public Setinventoryverificationcontact setOauthToken(java.lang.String oauthToken) { return (Setinventoryverificationcontact) super.setOauthToken(oauthToken); } @Override public Setinventoryverificationcontact setPrettyPrint(java.lang.Boolean prettyPrint) { return (Setinventoryverificationcontact) super.setPrettyPrint(prettyPrint); } @Override public Setinventoryverificationcontact setQuotaUser(java.lang.String quotaUser) { return (Setinventoryverificationcontact) super.setQuotaUser(quotaUser); } @Override public Setinventoryverificationcontact setUploadType(java.lang.String uploadType) { return (Setinventoryverificationcontact) super.setUploadType(uploadType); } @Override public Setinventoryverificationcontact setUploadProtocol(java.lang.String uploadProtocol) { return (Setinventoryverificationcontact) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Setinventoryverificationcontact setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Setinventoryverificationcontact setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** The country for which inventory verification is requested. */ @com.google.api.client.util.Key private java.lang.String country; /** The country for which inventory verification is requested. */ public java.lang.String getCountry() { return country; } /** The country for which inventory verification is requested. */ public Setinventoryverificationcontact setCountry(java.lang.String country) { this.country = country; return this; } /** The language for which inventory verification is requested. */ @com.google.api.client.util.Key private java.lang.String language; /** The language for which inventory verification is requested. */ public java.lang.String getLanguage() { return language; } /** The language for which inventory verification is requested. */ public Setinventoryverificationcontact setLanguage(java.lang.String language) { this.language = language; return this; } /** The name of the inventory verification contact. */ @com.google.api.client.util.Key private java.lang.String contactName; /** The name of the inventory verification contact. */ public java.lang.String getContactName() { return contactName; } /** The name of the inventory verification contact. */ public Setinventoryverificationcontact setContactName(java.lang.String contactName) { this.contactName = contactName; return this; } /** The email of the inventory verification contact. */ @com.google.api.client.util.Key private java.lang.String contactEmail; /** The email of the inventory verification contact. */ public java.lang.String getContactEmail() { return contactEmail; } /** The email of the inventory verification contact. */ public Setinventoryverificationcontact setContactEmail(java.lang.String contactEmail) { this.contactEmail = contactEmail; return this; } @Override public Setinventoryverificationcontact set(String parameterName, Object value) { return (Setinventoryverificationcontact) super.set(parameterName, value); } } /** * Sets the POS data provider for the specified country. * * Create a request for the method "liasettings.setposdataprovider". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Setposdataprovider#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to retrieve accessible Google My Business accounts. * @param country The country for which the POS data provider is selected. * @return the request */ public Setposdataprovider setposdataprovider(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String country) throws java.io.IOException { Setposdataprovider result = new Setposdataprovider(merchantId, accountId, country); initialize(result); return result; } public class Setposdataprovider extends ShoppingContentRequest<com.google.api.services.content.model.LiasettingsSetPosDataProviderResponse> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}/setposdataprovider"; /** * Sets the POS data provider for the specified country. * * Create a request for the method "liasettings.setposdataprovider". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Setposdataprovider#execute()} method to invoke the remote * operation. <p> {@link Setposdataprovider#initialize(com.google.api.client.googleapis.services.A * bstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to retrieve accessible Google My Business accounts. * @param country The country for which the POS data provider is selected. * @since 1.13 */ protected Setposdataprovider(java.math.BigInteger merchantId, java.math.BigInteger accountId, java.lang.String country) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.LiasettingsSetPosDataProviderResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); this.country = com.google.api.client.util.Preconditions.checkNotNull(country, "Required parameter country must be specified."); } @Override public Setposdataprovider set$Xgafv(java.lang.String $Xgafv) { return (Setposdataprovider) super.set$Xgafv($Xgafv); } @Override public Setposdataprovider setAccessToken(java.lang.String accessToken) { return (Setposdataprovider) super.setAccessToken(accessToken); } @Override public Setposdataprovider setAlt(java.lang.String alt) { return (Setposdataprovider) super.setAlt(alt); } @Override public Setposdataprovider setCallback(java.lang.String callback) { return (Setposdataprovider) super.setCallback(callback); } @Override public Setposdataprovider setFields(java.lang.String fields) { return (Setposdataprovider) super.setFields(fields); } @Override public Setposdataprovider setKey(java.lang.String key) { return (Setposdataprovider) super.setKey(key); } @Override public Setposdataprovider setOauthToken(java.lang.String oauthToken) { return (Setposdataprovider) super.setOauthToken(oauthToken); } @Override public Setposdataprovider setPrettyPrint(java.lang.Boolean prettyPrint) { return (Setposdataprovider) super.setPrettyPrint(prettyPrint); } @Override public Setposdataprovider setQuotaUser(java.lang.String quotaUser) { return (Setposdataprovider) super.setQuotaUser(quotaUser); } @Override public Setposdataprovider setUploadType(java.lang.String uploadType) { return (Setposdataprovider) super.setUploadType(uploadType); } @Override public Setposdataprovider setUploadProtocol(java.lang.String uploadProtocol) { return (Setposdataprovider) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Setposdataprovider setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to retrieve accessible Google My Business accounts. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to retrieve accessible Google My Business accounts. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to retrieve accessible Google My Business accounts. */ public Setposdataprovider setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } /** The country for which the POS data provider is selected. */ @com.google.api.client.util.Key private java.lang.String country; /** The country for which the POS data provider is selected. */ public java.lang.String getCountry() { return country; } /** The country for which the POS data provider is selected. */ public Setposdataprovider setCountry(java.lang.String country) { this.country = country; return this; } /** The ID of POS data provider. */ @com.google.api.client.util.Key private java.math.BigInteger posDataProviderId; /** The ID of POS data provider. */ public java.math.BigInteger getPosDataProviderId() { return posDataProviderId; } /** The ID of POS data provider. */ public Setposdataprovider setPosDataProviderId(java.math.BigInteger posDataProviderId) { this.posDataProviderId = posDataProviderId; return this; } /** The account ID by which this merchant is known to the POS data provider. */ @com.google.api.client.util.Key private java.lang.String posExternalAccountId; /** The account ID by which this merchant is known to the POS data provider. */ public java.lang.String getPosExternalAccountId() { return posExternalAccountId; } /** The account ID by which this merchant is known to the POS data provider. */ public Setposdataprovider setPosExternalAccountId(java.lang.String posExternalAccountId) { this.posExternalAccountId = posExternalAccountId; return this; } @Override public Setposdataprovider set(String parameterName, Object value) { return (Setposdataprovider) super.set(parameterName, value); } } /** * Updates the LIA settings of the account. Any fields that are not provided are deleted from the * resource. * * Create a request for the method "liasettings.update". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get or update LIA settings. * @param content the {@link com.google.api.services.content.model.LiaSettings} * @return the request */ public Update update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.LiaSettings content) throws java.io.IOException { Update result = new Update(merchantId, accountId, content); initialize(result); return result; } public class Update extends ShoppingContentRequest<com.google.api.services.content.model.LiaSettings> { private static final String REST_PATH = "{merchantId}/liasettings/{accountId}"; /** * Updates the LIA settings of the account. Any fields that are not provided are deleted from the * resource. * * Create a request for the method "liasettings.update". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get or update LIA settings. * @param content the {@link com.google.api.services.content.model.LiaSettings} * @since 1.13 */ protected Update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.LiaSettings content) { super(ShoppingContent.this, "PUT", REST_PATH, content, com.google.api.services.content.model.LiaSettings.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Update setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to get or update LIA settings. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to get or update LIA settings. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to get or update LIA settings. */ public Update setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Localinventory collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Localinventory.List request = content.localinventory().list(parameters ...)} * </pre> * * @return the resource collection */ public Localinventory localinventory() { return new Localinventory(); } /** * The "localinventory" collection of methods. */ public class Localinventory { /** * Updates local inventory for multiple products or stores in a single request. * * Create a request for the method "localinventory.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.LocalinventoryCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.LocalinventoryCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.LocalinventoryCustomBatchResponse> { private static final String REST_PATH = "localinventory/batch"; /** * Updates local inventory for multiple products or stores in a single request. * * Create a request for the method "localinventory.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.LocalinventoryCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.LocalinventoryCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.LocalinventoryCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Updates the local inventory of a product in your Merchant Center account. * * Create a request for the method "localinventory.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product for which to update local inventory. * @param content the {@link com.google.api.services.content.model.LocalInventory} * @return the request */ public Insert insert(java.math.BigInteger merchantId, java.lang.String productId, com.google.api.services.content.model.LocalInventory content) throws java.io.IOException { Insert result = new Insert(merchantId, productId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.LocalInventory> { private static final String REST_PATH = "{merchantId}/products/{productId}/localinventory"; /** * Updates the local inventory of a product in your Merchant Center account. * * Create a request for the method "localinventory.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product for which to update local inventory. * @param content the {@link com.google.api.services.content.model.LocalInventory} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, java.lang.String productId, com.google.api.services.content.model.LocalInventory content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.LocalInventory.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the product. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The REST ID of the product for which to update local inventory. */ @com.google.api.client.util.Key private java.lang.String productId; /** The REST ID of the product for which to update local inventory. */ public java.lang.String getProductId() { return productId; } /** The REST ID of the product for which to update local inventory. */ public Insert setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Orderinvoices collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Orderinvoices.List request = content.orderinvoices().list(parameters ...)} * </pre> * * @return the resource collection */ public Orderinvoices orderinvoices() { return new Orderinvoices(); } /** * The "orderinvoices" collection of methods. */ public class Orderinvoices { /** * Creates a charge invoice for a shipment group, and triggers a charge capture for orderinvoice * enabled orders. * * Create a request for the method "orderinvoices.createchargeinvoice". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Createchargeinvoice#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrderinvoicesCreateChargeInvoiceRequest} * @return the request */ public Createchargeinvoice createchargeinvoice(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrderinvoicesCreateChargeInvoiceRequest content) throws java.io.IOException { Createchargeinvoice result = new Createchargeinvoice(merchantId, orderId, content); initialize(result); return result; } public class Createchargeinvoice extends ShoppingContentRequest<com.google.api.services.content.model.OrderinvoicesCreateChargeInvoiceResponse> { private static final String REST_PATH = "{merchantId}/orderinvoices/{orderId}/createChargeInvoice"; /** * Creates a charge invoice for a shipment group, and triggers a charge capture for orderinvoice * enabled orders. * * Create a request for the method "orderinvoices.createchargeinvoice". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Createchargeinvoice#execute()} method to invoke the remote * operation. <p> {@link Createchargeinvoice#initialize(com.google.api.client.googleapis.services. * AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrderinvoicesCreateChargeInvoiceRequest} * @since 1.13 */ protected Createchargeinvoice(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrderinvoicesCreateChargeInvoiceRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrderinvoicesCreateChargeInvoiceResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Createchargeinvoice set$Xgafv(java.lang.String $Xgafv) { return (Createchargeinvoice) super.set$Xgafv($Xgafv); } @Override public Createchargeinvoice setAccessToken(java.lang.String accessToken) { return (Createchargeinvoice) super.setAccessToken(accessToken); } @Override public Createchargeinvoice setAlt(java.lang.String alt) { return (Createchargeinvoice) super.setAlt(alt); } @Override public Createchargeinvoice setCallback(java.lang.String callback) { return (Createchargeinvoice) super.setCallback(callback); } @Override public Createchargeinvoice setFields(java.lang.String fields) { return (Createchargeinvoice) super.setFields(fields); } @Override public Createchargeinvoice setKey(java.lang.String key) { return (Createchargeinvoice) super.setKey(key); } @Override public Createchargeinvoice setOauthToken(java.lang.String oauthToken) { return (Createchargeinvoice) super.setOauthToken(oauthToken); } @Override public Createchargeinvoice setPrettyPrint(java.lang.Boolean prettyPrint) { return (Createchargeinvoice) super.setPrettyPrint(prettyPrint); } @Override public Createchargeinvoice setQuotaUser(java.lang.String quotaUser) { return (Createchargeinvoice) super.setQuotaUser(quotaUser); } @Override public Createchargeinvoice setUploadType(java.lang.String uploadType) { return (Createchargeinvoice) super.setUploadType(uploadType); } @Override public Createchargeinvoice setUploadProtocol(java.lang.String uploadProtocol) { return (Createchargeinvoice) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Createchargeinvoice setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Createchargeinvoice setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Createchargeinvoice set(String parameterName, Object value) { return (Createchargeinvoice) super.set(parameterName, value); } } /** * Creates a refund invoice for one or more shipment groups, and triggers a refund for orderinvoice * enabled orders. This can only be used for line items that have previously been charged using * `createChargeInvoice`. All amounts (except for the summary) are incremental with respect to the * previous invoice. * * Create a request for the method "orderinvoices.createrefundinvoice". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Createrefundinvoice#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrderinvoicesCreateRefundInvoiceRequest} * @return the request */ public Createrefundinvoice createrefundinvoice(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrderinvoicesCreateRefundInvoiceRequest content) throws java.io.IOException { Createrefundinvoice result = new Createrefundinvoice(merchantId, orderId, content); initialize(result); return result; } public class Createrefundinvoice extends ShoppingContentRequest<com.google.api.services.content.model.OrderinvoicesCreateRefundInvoiceResponse> { private static final String REST_PATH = "{merchantId}/orderinvoices/{orderId}/createRefundInvoice"; /** * Creates a refund invoice for one or more shipment groups, and triggers a refund for * orderinvoice enabled orders. This can only be used for line items that have previously been * charged using `createChargeInvoice`. All amounts (except for the summary) are incremental with * respect to the previous invoice. * * Create a request for the method "orderinvoices.createrefundinvoice". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Createrefundinvoice#execute()} method to invoke the remote * operation. <p> {@link Createrefundinvoice#initialize(com.google.api.client.googleapis.services. * AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrderinvoicesCreateRefundInvoiceRequest} * @since 1.13 */ protected Createrefundinvoice(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrderinvoicesCreateRefundInvoiceRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrderinvoicesCreateRefundInvoiceResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Createrefundinvoice set$Xgafv(java.lang.String $Xgafv) { return (Createrefundinvoice) super.set$Xgafv($Xgafv); } @Override public Createrefundinvoice setAccessToken(java.lang.String accessToken) { return (Createrefundinvoice) super.setAccessToken(accessToken); } @Override public Createrefundinvoice setAlt(java.lang.String alt) { return (Createrefundinvoice) super.setAlt(alt); } @Override public Createrefundinvoice setCallback(java.lang.String callback) { return (Createrefundinvoice) super.setCallback(callback); } @Override public Createrefundinvoice setFields(java.lang.String fields) { return (Createrefundinvoice) super.setFields(fields); } @Override public Createrefundinvoice setKey(java.lang.String key) { return (Createrefundinvoice) super.setKey(key); } @Override public Createrefundinvoice setOauthToken(java.lang.String oauthToken) { return (Createrefundinvoice) super.setOauthToken(oauthToken); } @Override public Createrefundinvoice setPrettyPrint(java.lang.Boolean prettyPrint) { return (Createrefundinvoice) super.setPrettyPrint(prettyPrint); } @Override public Createrefundinvoice setQuotaUser(java.lang.String quotaUser) { return (Createrefundinvoice) super.setQuotaUser(quotaUser); } @Override public Createrefundinvoice setUploadType(java.lang.String uploadType) { return (Createrefundinvoice) super.setUploadType(uploadType); } @Override public Createrefundinvoice setUploadProtocol(java.lang.String uploadProtocol) { return (Createrefundinvoice) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Createrefundinvoice setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Createrefundinvoice setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Createrefundinvoice set(String parameterName, Object value) { return (Createrefundinvoice) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Orderreports collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Orderreports.List request = content.orderreports().list(parameters ...)} * </pre> * * @return the resource collection */ public Orderreports orderreports() { return new Orderreports(); } /** * The "orderreports" collection of methods. */ public class Orderreports { /** * Retrieves a report for disbursements from your Merchant Center account. * * Create a request for the method "orderreports.listdisbursements". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Listdisbursements#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @return the request */ public Listdisbursements listdisbursements(java.math.BigInteger merchantId) throws java.io.IOException { Listdisbursements result = new Listdisbursements(merchantId); initialize(result); return result; } public class Listdisbursements extends ShoppingContentRequest<com.google.api.services.content.model.OrderreportsListDisbursementsResponse> { private static final String REST_PATH = "{merchantId}/orderreports/disbursements"; /** * Retrieves a report for disbursements from your Merchant Center account. * * Create a request for the method "orderreports.listdisbursements". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Listdisbursements#execute()} method to invoke the remote operation. * <p> {@link Listdisbursements#initialize(com.google.api.client.googleapis.services.AbstractGoogl * eClientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @since 1.13 */ protected Listdisbursements(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.OrderreportsListDisbursementsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Listdisbursements set$Xgafv(java.lang.String $Xgafv) { return (Listdisbursements) super.set$Xgafv($Xgafv); } @Override public Listdisbursements setAccessToken(java.lang.String accessToken) { return (Listdisbursements) super.setAccessToken(accessToken); } @Override public Listdisbursements setAlt(java.lang.String alt) { return (Listdisbursements) super.setAlt(alt); } @Override public Listdisbursements setCallback(java.lang.String callback) { return (Listdisbursements) super.setCallback(callback); } @Override public Listdisbursements setFields(java.lang.String fields) { return (Listdisbursements) super.setFields(fields); } @Override public Listdisbursements setKey(java.lang.String key) { return (Listdisbursements) super.setKey(key); } @Override public Listdisbursements setOauthToken(java.lang.String oauthToken) { return (Listdisbursements) super.setOauthToken(oauthToken); } @Override public Listdisbursements setPrettyPrint(java.lang.Boolean prettyPrint) { return (Listdisbursements) super.setPrettyPrint(prettyPrint); } @Override public Listdisbursements setQuotaUser(java.lang.String quotaUser) { return (Listdisbursements) super.setQuotaUser(quotaUser); } @Override public Listdisbursements setUploadType(java.lang.String uploadType) { return (Listdisbursements) super.setUploadType(uploadType); } @Override public Listdisbursements setUploadProtocol(java.lang.String uploadProtocol) { return (Listdisbursements) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Listdisbursements setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The last date which disbursements occurred. In ISO 8601 format. Default: current date. */ @com.google.api.client.util.Key private java.lang.String disbursementEndDate; /** The last date which disbursements occurred. In ISO 8601 format. Default: current date. */ public java.lang.String getDisbursementEndDate() { return disbursementEndDate; } /** The last date which disbursements occurred. In ISO 8601 format. Default: current date. */ public Listdisbursements setDisbursementEndDate(java.lang.String disbursementEndDate) { this.disbursementEndDate = disbursementEndDate; return this; } /** The first date which disbursements occurred. In ISO 8601 format. */ @com.google.api.client.util.Key private java.lang.String disbursementStartDate; /** The first date which disbursements occurred. In ISO 8601 format. */ public java.lang.String getDisbursementStartDate() { return disbursementStartDate; } /** The first date which disbursements occurred. In ISO 8601 format. */ public Listdisbursements setDisbursementStartDate(java.lang.String disbursementStartDate) { this.disbursementStartDate = disbursementStartDate; return this; } /** The maximum number of disbursements to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of disbursements to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of disbursements to return in the response, used for paging. */ public Listdisbursements setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public Listdisbursements setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public Listdisbursements set(String parameterName, Object value) { return (Listdisbursements) super.set(parameterName, value); } } /** * Retrieves a list of transactions for a disbursement from your Merchant Center account. * * Create a request for the method "orderreports.listtransactions". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Listtransactions#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param disbursementId The Google-provided ID of the disbursement (found in Wallet). * @return the request */ public Listtransactions listtransactions(java.math.BigInteger merchantId, java.lang.String disbursementId) throws java.io.IOException { Listtransactions result = new Listtransactions(merchantId, disbursementId); initialize(result); return result; } public class Listtransactions extends ShoppingContentRequest<com.google.api.services.content.model.OrderreportsListTransactionsResponse> { private static final String REST_PATH = "{merchantId}/orderreports/disbursements/{disbursementId}/transactions"; /** * Retrieves a list of transactions for a disbursement from your Merchant Center account. * * Create a request for the method "orderreports.listtransactions". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Listtransactions#execute()} method to invoke the remote operation. * <p> {@link Listtransactions#initialize(com.google.api.client.googleapis.services.AbstractGoogle * ClientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param disbursementId The Google-provided ID of the disbursement (found in Wallet). * @since 1.13 */ protected Listtransactions(java.math.BigInteger merchantId, java.lang.String disbursementId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.OrderreportsListTransactionsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.disbursementId = com.google.api.client.util.Preconditions.checkNotNull(disbursementId, "Required parameter disbursementId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Listtransactions set$Xgafv(java.lang.String $Xgafv) { return (Listtransactions) super.set$Xgafv($Xgafv); } @Override public Listtransactions setAccessToken(java.lang.String accessToken) { return (Listtransactions) super.setAccessToken(accessToken); } @Override public Listtransactions setAlt(java.lang.String alt) { return (Listtransactions) super.setAlt(alt); } @Override public Listtransactions setCallback(java.lang.String callback) { return (Listtransactions) super.setCallback(callback); } @Override public Listtransactions setFields(java.lang.String fields) { return (Listtransactions) super.setFields(fields); } @Override public Listtransactions setKey(java.lang.String key) { return (Listtransactions) super.setKey(key); } @Override public Listtransactions setOauthToken(java.lang.String oauthToken) { return (Listtransactions) super.setOauthToken(oauthToken); } @Override public Listtransactions setPrettyPrint(java.lang.Boolean prettyPrint) { return (Listtransactions) super.setPrettyPrint(prettyPrint); } @Override public Listtransactions setQuotaUser(java.lang.String quotaUser) { return (Listtransactions) super.setQuotaUser(quotaUser); } @Override public Listtransactions setUploadType(java.lang.String uploadType) { return (Listtransactions) super.setUploadType(uploadType); } @Override public Listtransactions setUploadProtocol(java.lang.String uploadProtocol) { return (Listtransactions) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Listtransactions setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The Google-provided ID of the disbursement (found in Wallet). */ @com.google.api.client.util.Key private java.lang.String disbursementId; /** The Google-provided ID of the disbursement (found in Wallet). */ public java.lang.String getDisbursementId() { return disbursementId; } /** The Google-provided ID of the disbursement (found in Wallet). */ public Listtransactions setDisbursementId(java.lang.String disbursementId) { this.disbursementId = disbursementId; return this; } /** The maximum number of disbursements to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of disbursements to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of disbursements to return in the response, used for paging. */ public Listtransactions setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public Listtransactions setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * The last date in which transaction occurred. In ISO 8601 format. Default: current date. */ @com.google.api.client.util.Key private java.lang.String transactionEndDate; /** The last date in which transaction occurred. In ISO 8601 format. Default: current date. */ public java.lang.String getTransactionEndDate() { return transactionEndDate; } /** * The last date in which transaction occurred. In ISO 8601 format. Default: current date. */ public Listtransactions setTransactionEndDate(java.lang.String transactionEndDate) { this.transactionEndDate = transactionEndDate; return this; } /** The first date in which transaction occurred. In ISO 8601 format. */ @com.google.api.client.util.Key private java.lang.String transactionStartDate; /** The first date in which transaction occurred. In ISO 8601 format. */ public java.lang.String getTransactionStartDate() { return transactionStartDate; } /** The first date in which transaction occurred. In ISO 8601 format. */ public Listtransactions setTransactionStartDate(java.lang.String transactionStartDate) { this.transactionStartDate = transactionStartDate; return this; } @Override public Listtransactions set(String parameterName, Object value) { return (Listtransactions) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Orderreturns collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Orderreturns.List request = content.orderreturns().list(parameters ...)} * </pre> * * @return the resource collection */ public Orderreturns orderreturns() { return new Orderreturns(); } /** * The "orderreturns" collection of methods. */ public class Orderreturns { /** * Acks an order return in your Merchant Center account. * * Create a request for the method "orderreturns.acknowledge". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Acknowledge#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param returnId The ID of the return. * @param content the {@link com.google.api.services.content.model.OrderreturnsAcknowledgeRequest} * @return the request */ public Acknowledge acknowledge(java.math.BigInteger merchantId, java.lang.String returnId, com.google.api.services.content.model.OrderreturnsAcknowledgeRequest content) throws java.io.IOException { Acknowledge result = new Acknowledge(merchantId, returnId, content); initialize(result); return result; } public class Acknowledge extends ShoppingContentRequest<com.google.api.services.content.model.OrderreturnsAcknowledgeResponse> { private static final String REST_PATH = "{merchantId}/orderreturns/{returnId}/acknowledge"; /** * Acks an order return in your Merchant Center account. * * Create a request for the method "orderreturns.acknowledge". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Acknowledge#execute()} method to invoke the remote operation. <p> * {@link * Acknowledge#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param returnId The ID of the return. * @param content the {@link com.google.api.services.content.model.OrderreturnsAcknowledgeRequest} * @since 1.13 */ protected Acknowledge(java.math.BigInteger merchantId, java.lang.String returnId, com.google.api.services.content.model.OrderreturnsAcknowledgeRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrderreturnsAcknowledgeResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnId = com.google.api.client.util.Preconditions.checkNotNull(returnId, "Required parameter returnId must be specified."); } @Override public Acknowledge set$Xgafv(java.lang.String $Xgafv) { return (Acknowledge) super.set$Xgafv($Xgafv); } @Override public Acknowledge setAccessToken(java.lang.String accessToken) { return (Acknowledge) super.setAccessToken(accessToken); } @Override public Acknowledge setAlt(java.lang.String alt) { return (Acknowledge) super.setAlt(alt); } @Override public Acknowledge setCallback(java.lang.String callback) { return (Acknowledge) super.setCallback(callback); } @Override public Acknowledge setFields(java.lang.String fields) { return (Acknowledge) super.setFields(fields); } @Override public Acknowledge setKey(java.lang.String key) { return (Acknowledge) super.setKey(key); } @Override public Acknowledge setOauthToken(java.lang.String oauthToken) { return (Acknowledge) super.setOauthToken(oauthToken); } @Override public Acknowledge setPrettyPrint(java.lang.Boolean prettyPrint) { return (Acknowledge) super.setPrettyPrint(prettyPrint); } @Override public Acknowledge setQuotaUser(java.lang.String quotaUser) { return (Acknowledge) super.setQuotaUser(quotaUser); } @Override public Acknowledge setUploadType(java.lang.String uploadType) { return (Acknowledge) super.setUploadType(uploadType); } @Override public Acknowledge setUploadProtocol(java.lang.String uploadProtocol) { return (Acknowledge) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Acknowledge setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the return. */ @com.google.api.client.util.Key private java.lang.String returnId; /** The ID of the return. */ public java.lang.String getReturnId() { return returnId; } /** The ID of the return. */ public Acknowledge setReturnId(java.lang.String returnId) { this.returnId = returnId; return this; } @Override public Acknowledge set(String parameterName, Object value) { return (Acknowledge) super.set(parameterName, value); } } /** * Create return in your Merchant Center account. * * Create a request for the method "orderreturns.createorderreturn". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Createorderreturn#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.OrderreturnsCreateOrderReturnRequest} * @return the request */ public Createorderreturn createorderreturn(java.math.BigInteger merchantId, com.google.api.services.content.model.OrderreturnsCreateOrderReturnRequest content) throws java.io.IOException { Createorderreturn result = new Createorderreturn(merchantId, content); initialize(result); return result; } public class Createorderreturn extends ShoppingContentRequest<com.google.api.services.content.model.OrderreturnsCreateOrderReturnResponse> { private static final String REST_PATH = "{merchantId}/orderreturns/createOrderReturn"; /** * Create return in your Merchant Center account. * * Create a request for the method "orderreturns.createorderreturn". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Createorderreturn#execute()} method to invoke the remote operation. * <p> {@link Createorderreturn#initialize(com.google.api.client.googleapis.services.AbstractGoogl * eClientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.OrderreturnsCreateOrderReturnRequest} * @since 1.13 */ protected Createorderreturn(java.math.BigInteger merchantId, com.google.api.services.content.model.OrderreturnsCreateOrderReturnRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrderreturnsCreateOrderReturnResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Createorderreturn set$Xgafv(java.lang.String $Xgafv) { return (Createorderreturn) super.set$Xgafv($Xgafv); } @Override public Createorderreturn setAccessToken(java.lang.String accessToken) { return (Createorderreturn) super.setAccessToken(accessToken); } @Override public Createorderreturn setAlt(java.lang.String alt) { return (Createorderreturn) super.setAlt(alt); } @Override public Createorderreturn setCallback(java.lang.String callback) { return (Createorderreturn) super.setCallback(callback); } @Override public Createorderreturn setFields(java.lang.String fields) { return (Createorderreturn) super.setFields(fields); } @Override public Createorderreturn setKey(java.lang.String key) { return (Createorderreturn) super.setKey(key); } @Override public Createorderreturn setOauthToken(java.lang.String oauthToken) { return (Createorderreturn) super.setOauthToken(oauthToken); } @Override public Createorderreturn setPrettyPrint(java.lang.Boolean prettyPrint) { return (Createorderreturn) super.setPrettyPrint(prettyPrint); } @Override public Createorderreturn setQuotaUser(java.lang.String quotaUser) { return (Createorderreturn) super.setQuotaUser(quotaUser); } @Override public Createorderreturn setUploadType(java.lang.String uploadType) { return (Createorderreturn) super.setUploadType(uploadType); } @Override public Createorderreturn setUploadProtocol(java.lang.String uploadProtocol) { return (Createorderreturn) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Createorderreturn setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Createorderreturn set(String parameterName, Object value) { return (Createorderreturn) super.set(parameterName, value); } } /** * Retrieves an order return from your Merchant Center account. * * Create a request for the method "orderreturns.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param returnId Merchant order return ID generated by Google. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String returnId) throws java.io.IOException { Get result = new Get(merchantId, returnId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.MerchantOrderReturn> { private static final String REST_PATH = "{merchantId}/orderreturns/{returnId}"; /** * Retrieves an order return from your Merchant Center account. * * Create a request for the method "orderreturns.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param returnId Merchant order return ID generated by Google. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String returnId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.MerchantOrderReturn.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnId = com.google.api.client.util.Preconditions.checkNotNull(returnId, "Required parameter returnId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** Merchant order return ID generated by Google. */ @com.google.api.client.util.Key private java.lang.String returnId; /** Merchant order return ID generated by Google. */ public java.lang.String getReturnId() { return returnId; } /** Merchant order return ID generated by Google. */ public Get setReturnId(java.lang.String returnId) { this.returnId = returnId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists order returns in your Merchant Center account. * * Create a request for the method "orderreturns.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.OrderreturnsListResponse> { private static final String REST_PATH = "{merchantId}/orderreturns"; /** * Lists order returns in your Merchant Center account. * * Create a request for the method "orderreturns.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.OrderreturnsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** * Obtains order returns that match the acknowledgement status. When set to true, obtains * order returns that have been acknowledged. When false, obtains order returns that have not * been acknowledged. When not provided, obtains order returns regardless of their * acknowledgement status. We recommend using this filter set to `false`, in conjunction with * the `acknowledge` call, such that only un-acknowledged order returns are returned. */ @com.google.api.client.util.Key private java.lang.Boolean acknowledged; /** Obtains order returns that match the acknowledgement status. When set to true, obtains order returns that have been acknowledged. When false, obtains order returns that have not been acknowledged. When not provided, obtains order returns regardless of their acknowledgement status. We recommend using this filter set to `false`, in conjunction with the `acknowledge` call, such that only un-acknowledged order returns are returned. */ public java.lang.Boolean getAcknowledged() { return acknowledged; } /** * Obtains order returns that match the acknowledgement status. When set to true, obtains * order returns that have been acknowledged. When false, obtains order returns that have not * been acknowledged. When not provided, obtains order returns regardless of their * acknowledgement status. We recommend using this filter set to `false`, in conjunction with * the `acknowledge` call, such that only un-acknowledged order returns are returned. */ public List setAcknowledged(java.lang.Boolean acknowledged) { this.acknowledged = acknowledged; return this; } /** Obtains order returns created before this date (inclusively), in ISO 8601 format. */ @com.google.api.client.util.Key private java.lang.String createdEndDate; /** Obtains order returns created before this date (inclusively), in ISO 8601 format. */ public java.lang.String getCreatedEndDate() { return createdEndDate; } /** Obtains order returns created before this date (inclusively), in ISO 8601 format. */ public List setCreatedEndDate(java.lang.String createdEndDate) { this.createdEndDate = createdEndDate; return this; } /** Obtains order returns created after this date (inclusively), in ISO 8601 format. */ @com.google.api.client.util.Key private java.lang.String createdStartDate; /** Obtains order returns created after this date (inclusively), in ISO 8601 format. */ public java.lang.String getCreatedStartDate() { return createdStartDate; } /** Obtains order returns created after this date (inclusively), in ISO 8601 format. */ public List setCreatedStartDate(java.lang.String createdStartDate) { this.createdStartDate = createdStartDate; return this; } /** * Obtains order returns with the specified order ids. If this parameter is provided, * createdStartDate, createdEndDate, shipmentType, shipmentStatus, shipmentState and * acknowledged parameters must be not set. Note: if googleOrderId and shipmentTrackingNumber * parameters are provided, the obtained results will include all order returns that either * match the specified order id or the specified tracking number. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> googleOrderIds; /** Obtains order returns with the specified order ids. If this parameter is provided, createdStartDate, createdEndDate, shipmentType, shipmentStatus, shipmentState and acknowledged parameters must be not set. Note: if googleOrderId and shipmentTrackingNumber parameters are provided, the obtained results will include all order returns that either match the specified order id or the specified tracking number. */ public java.util.List<java.lang.String> getGoogleOrderIds() { return googleOrderIds; } /** * Obtains order returns with the specified order ids. If this parameter is provided, * createdStartDate, createdEndDate, shipmentType, shipmentStatus, shipmentState and * acknowledged parameters must be not set. Note: if googleOrderId and shipmentTrackingNumber * parameters are provided, the obtained results will include all order returns that either * match the specified order id or the specified tracking number. */ public List setGoogleOrderIds(java.util.List<java.lang.String> googleOrderIds) { this.googleOrderIds = googleOrderIds; return this; } /** * The maximum number of order returns to return in the response, used for paging. The default * value is 25 returns per page, and the maximum allowed value is 250 returns per page. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of order returns to return in the response, used for paging. The default value is 25 returns per page, and the maximum allowed value is 250 returns per page. */ public java.lang.Long getMaxResults() { return maxResults; } /** * The maximum number of order returns to return in the response, used for paging. The default * value is 25 returns per page, and the maximum allowed value is 250 returns per page. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** Return the results in the specified order. */ @com.google.api.client.util.Key private java.lang.String orderBy; /** Return the results in the specified order. */ public java.lang.String getOrderBy() { return orderBy; } /** Return the results in the specified order. */ public List setOrderBy(java.lang.String orderBy) { this.orderBy = orderBy; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * Obtains order returns that match any shipment state provided in this parameter. When this * parameter is not provided, order returns are obtained regardless of their shipment states. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> shipmentStates; /** Obtains order returns that match any shipment state provided in this parameter. When this parameter is not provided, order returns are obtained regardless of their shipment states. */ public java.util.List<java.lang.String> getShipmentStates() { return shipmentStates; } /** * Obtains order returns that match any shipment state provided in this parameter. When this * parameter is not provided, order returns are obtained regardless of their shipment states. */ public List setShipmentStates(java.util.List<java.lang.String> shipmentStates) { this.shipmentStates = shipmentStates; return this; } /** * Obtains order returns that match any shipment status provided in this parameter. When this * parameter is not provided, order returns are obtained regardless of their shipment * statuses. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> shipmentStatus; /** Obtains order returns that match any shipment status provided in this parameter. When this parameter is not provided, order returns are obtained regardless of their shipment statuses. */ public java.util.List<java.lang.String> getShipmentStatus() { return shipmentStatus; } /** * Obtains order returns that match any shipment status provided in this parameter. When this * parameter is not provided, order returns are obtained regardless of their shipment * statuses. */ public List setShipmentStatus(java.util.List<java.lang.String> shipmentStatus) { this.shipmentStatus = shipmentStatus; return this; } /** * Obtains order returns with the specified tracking numbers. If this parameter is provided, * createdStartDate, createdEndDate, shipmentType, shipmentStatus, shipmentState and * acknowledged parameters must be not set. Note: if googleOrderId and shipmentTrackingNumber * parameters are provided, the obtained results will include all order returns that either * match the specified order id or the specified tracking number. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> shipmentTrackingNumbers; /** Obtains order returns with the specified tracking numbers. If this parameter is provided, createdStartDate, createdEndDate, shipmentType, shipmentStatus, shipmentState and acknowledged parameters must be not set. Note: if googleOrderId and shipmentTrackingNumber parameters are provided, the obtained results will include all order returns that either match the specified order id or the specified tracking number. */ public java.util.List<java.lang.String> getShipmentTrackingNumbers() { return shipmentTrackingNumbers; } /** * Obtains order returns with the specified tracking numbers. If this parameter is provided, * createdStartDate, createdEndDate, shipmentType, shipmentStatus, shipmentState and * acknowledged parameters must be not set. Note: if googleOrderId and shipmentTrackingNumber * parameters are provided, the obtained results will include all order returns that either * match the specified order id or the specified tracking number. */ public List setShipmentTrackingNumbers(java.util.List<java.lang.String> shipmentTrackingNumbers) { this.shipmentTrackingNumbers = shipmentTrackingNumbers; return this; } /** * Obtains order returns that match any shipment type provided in this parameter. When this * parameter is not provided, order returns are obtained regardless of their shipment types. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> shipmentTypes; /** Obtains order returns that match any shipment type provided in this parameter. When this parameter is not provided, order returns are obtained regardless of their shipment types. */ public java.util.List<java.lang.String> getShipmentTypes() { return shipmentTypes; } /** * Obtains order returns that match any shipment type provided in this parameter. When this * parameter is not provided, order returns are obtained regardless of their shipment types. */ public List setShipmentTypes(java.util.List<java.lang.String> shipmentTypes) { this.shipmentTypes = shipmentTypes; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Processes return in your Merchant Center account. * * Create a request for the method "orderreturns.process". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Process#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param returnId The ID of the return. * @param content the {@link com.google.api.services.content.model.OrderreturnsProcessRequest} * @return the request */ public Process process(java.math.BigInteger merchantId, java.lang.String returnId, com.google.api.services.content.model.OrderreturnsProcessRequest content) throws java.io.IOException { Process result = new Process(merchantId, returnId, content); initialize(result); return result; } public class Process extends ShoppingContentRequest<com.google.api.services.content.model.OrderreturnsProcessResponse> { private static final String REST_PATH = "{merchantId}/orderreturns/{returnId}/process"; /** * Processes return in your Merchant Center account. * * Create a request for the method "orderreturns.process". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Process#execute()} method to invoke the remote operation. <p> * {@link * Process#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param returnId The ID of the return. * @param content the {@link com.google.api.services.content.model.OrderreturnsProcessRequest} * @since 1.13 */ protected Process(java.math.BigInteger merchantId, java.lang.String returnId, com.google.api.services.content.model.OrderreturnsProcessRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrderreturnsProcessResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnId = com.google.api.client.util.Preconditions.checkNotNull(returnId, "Required parameter returnId must be specified."); } @Override public Process set$Xgafv(java.lang.String $Xgafv) { return (Process) super.set$Xgafv($Xgafv); } @Override public Process setAccessToken(java.lang.String accessToken) { return (Process) super.setAccessToken(accessToken); } @Override public Process setAlt(java.lang.String alt) { return (Process) super.setAlt(alt); } @Override public Process setCallback(java.lang.String callback) { return (Process) super.setCallback(callback); } @Override public Process setFields(java.lang.String fields) { return (Process) super.setFields(fields); } @Override public Process setKey(java.lang.String key) { return (Process) super.setKey(key); } @Override public Process setOauthToken(java.lang.String oauthToken) { return (Process) super.setOauthToken(oauthToken); } @Override public Process setPrettyPrint(java.lang.Boolean prettyPrint) { return (Process) super.setPrettyPrint(prettyPrint); } @Override public Process setQuotaUser(java.lang.String quotaUser) { return (Process) super.setQuotaUser(quotaUser); } @Override public Process setUploadType(java.lang.String uploadType) { return (Process) super.setUploadType(uploadType); } @Override public Process setUploadProtocol(java.lang.String uploadProtocol) { return (Process) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Process setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the return. */ @com.google.api.client.util.Key private java.lang.String returnId; /** The ID of the return. */ public java.lang.String getReturnId() { return returnId; } /** The ID of the return. */ public Process setReturnId(java.lang.String returnId) { this.returnId = returnId; return this; } @Override public Process set(String parameterName, Object value) { return (Process) super.set(parameterName, value); } } /** * An accessor for creating requests from the Labels collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Labels.List request = content.labels().list(parameters ...)} * </pre> * * @return the resource collection */ public Labels labels() { return new Labels(); } /** * The "labels" collection of methods. */ public class Labels { /** * Links a return shipping label to a return id. You can only create one return label per return id. * Since the label is sent to the buyer, the linked return label cannot be updated or deleted. If * you try to create multiple return shipping labels for a single return id, every create request * except the first will fail. * * Create a request for the method "labels.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param merchantId Required. The merchant the Return Shipping Label belongs to. * @param returnId Required. Provide the Google-generated merchant order return ID. * @param content the {@link com.google.api.services.content.model.ReturnShippingLabel} * @return the request */ public Create create(java.lang.Long merchantId, java.lang.String returnId, com.google.api.services.content.model.ReturnShippingLabel content) throws java.io.IOException { Create result = new Create(merchantId, returnId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.ReturnShippingLabel> { private static final String REST_PATH = "{merchantId}/orderreturns/{returnId}/labels"; /** * Links a return shipping label to a return id. You can only create one return label per return * id. Since the label is sent to the buyer, the linked return label cannot be updated or deleted. * If you try to create multiple return shipping labels for a single return id, every create * request except the first will fail. * * Create a request for the method "labels.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The merchant the Return Shipping Label belongs to. * @param returnId Required. Provide the Google-generated merchant order return ID. * @param content the {@link com.google.api.services.content.model.ReturnShippingLabel} * @since 1.13 */ protected Create(java.lang.Long merchantId, java.lang.String returnId, com.google.api.services.content.model.ReturnShippingLabel content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ReturnShippingLabel.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnId = com.google.api.client.util.Preconditions.checkNotNull(returnId, "Required parameter returnId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** Required. The merchant the Return Shipping Label belongs to. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The merchant the Return Shipping Label belongs to. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The merchant the Return Shipping Label belongs to. */ public Create setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. Provide the Google-generated merchant order return ID. */ @com.google.api.client.util.Key private java.lang.String returnId; /** Required. Provide the Google-generated merchant order return ID. */ public java.lang.String getReturnId() { return returnId; } /** Required. Provide the Google-generated merchant order return ID. */ public Create setReturnId(java.lang.String returnId) { this.returnId = returnId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } } } /** * An accessor for creating requests from the Orders collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Orders.List request = content.orders().list(parameters ...)} * </pre> * * @return the resource collection */ public Orders orders() { return new Orders(); } /** * The "orders" collection of methods. */ public class Orders { /** * Marks an order as acknowledged. * * Create a request for the method "orders.acknowledge". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Acknowledge#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersAcknowledgeRequest} * @return the request */ public Acknowledge acknowledge(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersAcknowledgeRequest content) throws java.io.IOException { Acknowledge result = new Acknowledge(merchantId, orderId, content); initialize(result); return result; } public class Acknowledge extends ShoppingContentRequest<com.google.api.services.content.model.OrdersAcknowledgeResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/acknowledge"; /** * Marks an order as acknowledged. * * Create a request for the method "orders.acknowledge". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Acknowledge#execute()} method to invoke the remote operation. <p> * {@link * Acknowledge#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersAcknowledgeRequest} * @since 1.13 */ protected Acknowledge(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersAcknowledgeRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersAcknowledgeResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Acknowledge set$Xgafv(java.lang.String $Xgafv) { return (Acknowledge) super.set$Xgafv($Xgafv); } @Override public Acknowledge setAccessToken(java.lang.String accessToken) { return (Acknowledge) super.setAccessToken(accessToken); } @Override public Acknowledge setAlt(java.lang.String alt) { return (Acknowledge) super.setAlt(alt); } @Override public Acknowledge setCallback(java.lang.String callback) { return (Acknowledge) super.setCallback(callback); } @Override public Acknowledge setFields(java.lang.String fields) { return (Acknowledge) super.setFields(fields); } @Override public Acknowledge setKey(java.lang.String key) { return (Acknowledge) super.setKey(key); } @Override public Acknowledge setOauthToken(java.lang.String oauthToken) { return (Acknowledge) super.setOauthToken(oauthToken); } @Override public Acknowledge setPrettyPrint(java.lang.Boolean prettyPrint) { return (Acknowledge) super.setPrettyPrint(prettyPrint); } @Override public Acknowledge setQuotaUser(java.lang.String quotaUser) { return (Acknowledge) super.setQuotaUser(quotaUser); } @Override public Acknowledge setUploadType(java.lang.String uploadType) { return (Acknowledge) super.setUploadType(uploadType); } @Override public Acknowledge setUploadProtocol(java.lang.String uploadProtocol) { return (Acknowledge) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Acknowledge setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Acknowledge setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Acknowledge set(String parameterName, Object value) { return (Acknowledge) super.set(parameterName, value); } } /** * Sandbox only. Moves a test order from state "`inProgress`" to state "`pendingShipment`". * * Create a request for the method "orders.advancetestorder". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Advancetestorder#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the test order to modify. * @return the request */ public Advancetestorder advancetestorder(java.math.BigInteger merchantId, java.lang.String orderId) throws java.io.IOException { Advancetestorder result = new Advancetestorder(merchantId, orderId); initialize(result); return result; } public class Advancetestorder extends ShoppingContentRequest<com.google.api.services.content.model.OrdersAdvanceTestOrderResponse> { private static final String REST_PATH = "{merchantId}/testorders/{orderId}/advance"; /** * Sandbox only. Moves a test order from state "`inProgress`" to state "`pendingShipment`". * * Create a request for the method "orders.advancetestorder". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Advancetestorder#execute()} method to invoke the remote operation. * <p> {@link Advancetestorder#initialize(com.google.api.client.googleapis.services.AbstractGoogle * ClientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the test order to modify. * @since 1.13 */ protected Advancetestorder(java.math.BigInteger merchantId, java.lang.String orderId) { super(ShoppingContent.this, "POST", REST_PATH, null, com.google.api.services.content.model.OrdersAdvanceTestOrderResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Advancetestorder set$Xgafv(java.lang.String $Xgafv) { return (Advancetestorder) super.set$Xgafv($Xgafv); } @Override public Advancetestorder setAccessToken(java.lang.String accessToken) { return (Advancetestorder) super.setAccessToken(accessToken); } @Override public Advancetestorder setAlt(java.lang.String alt) { return (Advancetestorder) super.setAlt(alt); } @Override public Advancetestorder setCallback(java.lang.String callback) { return (Advancetestorder) super.setCallback(callback); } @Override public Advancetestorder setFields(java.lang.String fields) { return (Advancetestorder) super.setFields(fields); } @Override public Advancetestorder setKey(java.lang.String key) { return (Advancetestorder) super.setKey(key); } @Override public Advancetestorder setOauthToken(java.lang.String oauthToken) { return (Advancetestorder) super.setOauthToken(oauthToken); } @Override public Advancetestorder setPrettyPrint(java.lang.Boolean prettyPrint) { return (Advancetestorder) super.setPrettyPrint(prettyPrint); } @Override public Advancetestorder setQuotaUser(java.lang.String quotaUser) { return (Advancetestorder) super.setQuotaUser(quotaUser); } @Override public Advancetestorder setUploadType(java.lang.String uploadType) { return (Advancetestorder) super.setUploadType(uploadType); } @Override public Advancetestorder setUploadProtocol(java.lang.String uploadProtocol) { return (Advancetestorder) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Advancetestorder setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the test order to modify. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the test order to modify. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the test order to modify. */ public Advancetestorder setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Advancetestorder set(String parameterName, Object value) { return (Advancetestorder) super.set(parameterName, value); } } /** * Cancels all line items in an order, making a full refund. * * Create a request for the method "orders.cancel". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Cancel#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order to cancel. * @param content the {@link com.google.api.services.content.model.OrdersCancelRequest} * @return the request */ public Cancel cancel(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCancelRequest content) throws java.io.IOException { Cancel result = new Cancel(merchantId, orderId, content); initialize(result); return result; } public class Cancel extends ShoppingContentRequest<com.google.api.services.content.model.OrdersCancelResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/cancel"; /** * Cancels all line items in an order, making a full refund. * * Create a request for the method "orders.cancel". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Cancel#execute()} method to invoke the remote operation. <p> {@link * Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order to cancel. * @param content the {@link com.google.api.services.content.model.OrdersCancelRequest} * @since 1.13 */ protected Cancel(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCancelRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersCancelResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Cancel set$Xgafv(java.lang.String $Xgafv) { return (Cancel) super.set$Xgafv($Xgafv); } @Override public Cancel setAccessToken(java.lang.String accessToken) { return (Cancel) super.setAccessToken(accessToken); } @Override public Cancel setAlt(java.lang.String alt) { return (Cancel) super.setAlt(alt); } @Override public Cancel setCallback(java.lang.String callback) { return (Cancel) super.setCallback(callback); } @Override public Cancel setFields(java.lang.String fields) { return (Cancel) super.setFields(fields); } @Override public Cancel setKey(java.lang.String key) { return (Cancel) super.setKey(key); } @Override public Cancel setOauthToken(java.lang.String oauthToken) { return (Cancel) super.setOauthToken(oauthToken); } @Override public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) { return (Cancel) super.setPrettyPrint(prettyPrint); } @Override public Cancel setQuotaUser(java.lang.String quotaUser) { return (Cancel) super.setQuotaUser(quotaUser); } @Override public Cancel setUploadType(java.lang.String uploadType) { return (Cancel) super.setUploadType(uploadType); } @Override public Cancel setUploadProtocol(java.lang.String uploadProtocol) { return (Cancel) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Cancel setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order to cancel. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order to cancel. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order to cancel. */ public Cancel setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Cancel set(String parameterName, Object value) { return (Cancel) super.set(parameterName, value); } } /** * Cancels a line item, making a full refund. * * Create a request for the method "orders.cancellineitem". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Cancellineitem#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersCancelLineItemRequest} * @return the request */ public Cancellineitem cancellineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCancelLineItemRequest content) throws java.io.IOException { Cancellineitem result = new Cancellineitem(merchantId, orderId, content); initialize(result); return result; } public class Cancellineitem extends ShoppingContentRequest<com.google.api.services.content.model.OrdersCancelLineItemResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/cancelLineItem"; /** * Cancels a line item, making a full refund. * * Create a request for the method "orders.cancellineitem". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Cancellineitem#execute()} method to invoke the remote operation. * <p> {@link Cancellineitem#initialize(com.google.api.client.googleapis.services.AbstractGoogleCl * ientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersCancelLineItemRequest} * @since 1.13 */ protected Cancellineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCancelLineItemRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersCancelLineItemResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Cancellineitem set$Xgafv(java.lang.String $Xgafv) { return (Cancellineitem) super.set$Xgafv($Xgafv); } @Override public Cancellineitem setAccessToken(java.lang.String accessToken) { return (Cancellineitem) super.setAccessToken(accessToken); } @Override public Cancellineitem setAlt(java.lang.String alt) { return (Cancellineitem) super.setAlt(alt); } @Override public Cancellineitem setCallback(java.lang.String callback) { return (Cancellineitem) super.setCallback(callback); } @Override public Cancellineitem setFields(java.lang.String fields) { return (Cancellineitem) super.setFields(fields); } @Override public Cancellineitem setKey(java.lang.String key) { return (Cancellineitem) super.setKey(key); } @Override public Cancellineitem setOauthToken(java.lang.String oauthToken) { return (Cancellineitem) super.setOauthToken(oauthToken); } @Override public Cancellineitem setPrettyPrint(java.lang.Boolean prettyPrint) { return (Cancellineitem) super.setPrettyPrint(prettyPrint); } @Override public Cancellineitem setQuotaUser(java.lang.String quotaUser) { return (Cancellineitem) super.setQuotaUser(quotaUser); } @Override public Cancellineitem setUploadType(java.lang.String uploadType) { return (Cancellineitem) super.setUploadType(uploadType); } @Override public Cancellineitem setUploadProtocol(java.lang.String uploadProtocol) { return (Cancellineitem) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Cancellineitem setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Cancellineitem setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Cancellineitem set(String parameterName, Object value) { return (Cancellineitem) super.set(parameterName, value); } } /** * Sandbox only. Cancels a test order for customer-initiated cancellation. * * Create a request for the method "orders.canceltestorderbycustomer". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Canceltestorderbycustomer#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the test order to cancel. * @param content the {@link com.google.api.services.content.model.OrdersCancelTestOrderByCustomerRequest} * @return the request */ public Canceltestorderbycustomer canceltestorderbycustomer(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCancelTestOrderByCustomerRequest content) throws java.io.IOException { Canceltestorderbycustomer result = new Canceltestorderbycustomer(merchantId, orderId, content); initialize(result); return result; } public class Canceltestorderbycustomer extends ShoppingContentRequest<com.google.api.services.content.model.OrdersCancelTestOrderByCustomerResponse> { private static final String REST_PATH = "{merchantId}/testorders/{orderId}/cancelByCustomer"; /** * Sandbox only. Cancels a test order for customer-initiated cancellation. * * Create a request for the method "orders.canceltestorderbycustomer". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Canceltestorderbycustomer#execute()} method to invoke the remote * operation. <p> {@link Canceltestorderbycustomer#initialize(com.google.api.client.googleapis.ser * vices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the test order to cancel. * @param content the {@link com.google.api.services.content.model.OrdersCancelTestOrderByCustomerRequest} * @since 1.13 */ protected Canceltestorderbycustomer(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCancelTestOrderByCustomerRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersCancelTestOrderByCustomerResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Canceltestorderbycustomer set$Xgafv(java.lang.String $Xgafv) { return (Canceltestorderbycustomer) super.set$Xgafv($Xgafv); } @Override public Canceltestorderbycustomer setAccessToken(java.lang.String accessToken) { return (Canceltestorderbycustomer) super.setAccessToken(accessToken); } @Override public Canceltestorderbycustomer setAlt(java.lang.String alt) { return (Canceltestorderbycustomer) super.setAlt(alt); } @Override public Canceltestorderbycustomer setCallback(java.lang.String callback) { return (Canceltestorderbycustomer) super.setCallback(callback); } @Override public Canceltestorderbycustomer setFields(java.lang.String fields) { return (Canceltestorderbycustomer) super.setFields(fields); } @Override public Canceltestorderbycustomer setKey(java.lang.String key) { return (Canceltestorderbycustomer) super.setKey(key); } @Override public Canceltestorderbycustomer setOauthToken(java.lang.String oauthToken) { return (Canceltestorderbycustomer) super.setOauthToken(oauthToken); } @Override public Canceltestorderbycustomer setPrettyPrint(java.lang.Boolean prettyPrint) { return (Canceltestorderbycustomer) super.setPrettyPrint(prettyPrint); } @Override public Canceltestorderbycustomer setQuotaUser(java.lang.String quotaUser) { return (Canceltestorderbycustomer) super.setQuotaUser(quotaUser); } @Override public Canceltestorderbycustomer setUploadType(java.lang.String uploadType) { return (Canceltestorderbycustomer) super.setUploadType(uploadType); } @Override public Canceltestorderbycustomer setUploadProtocol(java.lang.String uploadProtocol) { return (Canceltestorderbycustomer) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Canceltestorderbycustomer setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the test order to cancel. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the test order to cancel. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the test order to cancel. */ public Canceltestorderbycustomer setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Canceltestorderbycustomer set(String parameterName, Object value) { return (Canceltestorderbycustomer) super.set(parameterName, value); } } /** * Sandbox only. Creates a test order. * * Create a request for the method "orders.createtestorder". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Createtestorder#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that should manage the order. This cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.OrdersCreateTestOrderRequest} * @return the request */ public Createtestorder createtestorder(java.math.BigInteger merchantId, com.google.api.services.content.model.OrdersCreateTestOrderRequest content) throws java.io.IOException { Createtestorder result = new Createtestorder(merchantId, content); initialize(result); return result; } public class Createtestorder extends ShoppingContentRequest<com.google.api.services.content.model.OrdersCreateTestOrderResponse> { private static final String REST_PATH = "{merchantId}/testorders"; /** * Sandbox only. Creates a test order. * * Create a request for the method "orders.createtestorder". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Createtestorder#execute()} method to invoke the remote operation. * <p> {@link Createtestorder#initialize(com.google.api.client.googleapis.services.AbstractGoogleC * lientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that should manage the order. This cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.OrdersCreateTestOrderRequest} * @since 1.13 */ protected Createtestorder(java.math.BigInteger merchantId, com.google.api.services.content.model.OrdersCreateTestOrderRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersCreateTestOrderResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Createtestorder set$Xgafv(java.lang.String $Xgafv) { return (Createtestorder) super.set$Xgafv($Xgafv); } @Override public Createtestorder setAccessToken(java.lang.String accessToken) { return (Createtestorder) super.setAccessToken(accessToken); } @Override public Createtestorder setAlt(java.lang.String alt) { return (Createtestorder) super.setAlt(alt); } @Override public Createtestorder setCallback(java.lang.String callback) { return (Createtestorder) super.setCallback(callback); } @Override public Createtestorder setFields(java.lang.String fields) { return (Createtestorder) super.setFields(fields); } @Override public Createtestorder setKey(java.lang.String key) { return (Createtestorder) super.setKey(key); } @Override public Createtestorder setOauthToken(java.lang.String oauthToken) { return (Createtestorder) super.setOauthToken(oauthToken); } @Override public Createtestorder setPrettyPrint(java.lang.Boolean prettyPrint) { return (Createtestorder) super.setPrettyPrint(prettyPrint); } @Override public Createtestorder setQuotaUser(java.lang.String quotaUser) { return (Createtestorder) super.setQuotaUser(quotaUser); } @Override public Createtestorder setUploadType(java.lang.String uploadType) { return (Createtestorder) super.setUploadType(uploadType); } @Override public Createtestorder setUploadProtocol(java.lang.String uploadProtocol) { return (Createtestorder) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that should manage the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that should manage the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that should manage the order. This cannot be a multi-client account. */ public Createtestorder setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Createtestorder set(String parameterName, Object value) { return (Createtestorder) super.set(parameterName, value); } } /** * Sandbox only. Creates a test return. * * Create a request for the method "orders.createtestreturn". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Createtestreturn#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersCreateTestReturnRequest} * @return the request */ public Createtestreturn createtestreturn(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCreateTestReturnRequest content) throws java.io.IOException { Createtestreturn result = new Createtestreturn(merchantId, orderId, content); initialize(result); return result; } public class Createtestreturn extends ShoppingContentRequest<com.google.api.services.content.model.OrdersCreateTestReturnResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/testreturn"; /** * Sandbox only. Creates a test return. * * Create a request for the method "orders.createtestreturn". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Createtestreturn#execute()} method to invoke the remote operation. * <p> {@link Createtestreturn#initialize(com.google.api.client.googleapis.services.AbstractGoogle * ClientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersCreateTestReturnRequest} * @since 1.13 */ protected Createtestreturn(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersCreateTestReturnRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersCreateTestReturnResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Createtestreturn set$Xgafv(java.lang.String $Xgafv) { return (Createtestreturn) super.set$Xgafv($Xgafv); } @Override public Createtestreturn setAccessToken(java.lang.String accessToken) { return (Createtestreturn) super.setAccessToken(accessToken); } @Override public Createtestreturn setAlt(java.lang.String alt) { return (Createtestreturn) super.setAlt(alt); } @Override public Createtestreturn setCallback(java.lang.String callback) { return (Createtestreturn) super.setCallback(callback); } @Override public Createtestreturn setFields(java.lang.String fields) { return (Createtestreturn) super.setFields(fields); } @Override public Createtestreturn setKey(java.lang.String key) { return (Createtestreturn) super.setKey(key); } @Override public Createtestreturn setOauthToken(java.lang.String oauthToken) { return (Createtestreturn) super.setOauthToken(oauthToken); } @Override public Createtestreturn setPrettyPrint(java.lang.Boolean prettyPrint) { return (Createtestreturn) super.setPrettyPrint(prettyPrint); } @Override public Createtestreturn setQuotaUser(java.lang.String quotaUser) { return (Createtestreturn) super.setQuotaUser(quotaUser); } @Override public Createtestreturn setUploadType(java.lang.String uploadType) { return (Createtestreturn) super.setUploadType(uploadType); } @Override public Createtestreturn setUploadProtocol(java.lang.String uploadProtocol) { return (Createtestreturn) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Createtestreturn setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Createtestreturn setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Createtestreturn set(String parameterName, Object value) { return (Createtestreturn) super.set(parameterName, value); } } /** * Retrieves an order from your Merchant Center account. * * Create a request for the method "orders.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String orderId) throws java.io.IOException { Get result = new Get(merchantId, orderId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Order> { private static final String REST_PATH = "{merchantId}/orders/{orderId}"; /** * Retrieves an order from your Merchant Center account. * * Create a request for the method "orders.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String orderId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Order.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Get setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves an order using merchant order ID. * * Create a request for the method "orders.getbymerchantorderid". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Getbymerchantorderid#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param merchantOrderId The merchant order ID to be looked for. * @return the request */ public Getbymerchantorderid getbymerchantorderid(java.math.BigInteger merchantId, java.lang.String merchantOrderId) throws java.io.IOException { Getbymerchantorderid result = new Getbymerchantorderid(merchantId, merchantOrderId); initialize(result); return result; } public class Getbymerchantorderid extends ShoppingContentRequest<com.google.api.services.content.model.OrdersGetByMerchantOrderIdResponse> { private static final String REST_PATH = "{merchantId}/ordersbymerchantid/{merchantOrderId}"; /** * Retrieves an order using merchant order ID. * * Create a request for the method "orders.getbymerchantorderid". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Getbymerchantorderid#execute()} method to invoke the remote * operation. <p> {@link Getbymerchantorderid#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param merchantOrderId The merchant order ID to be looked for. * @since 1.13 */ protected Getbymerchantorderid(java.math.BigInteger merchantId, java.lang.String merchantOrderId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.OrdersGetByMerchantOrderIdResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.merchantOrderId = com.google.api.client.util.Preconditions.checkNotNull(merchantOrderId, "Required parameter merchantOrderId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Getbymerchantorderid set$Xgafv(java.lang.String $Xgafv) { return (Getbymerchantorderid) super.set$Xgafv($Xgafv); } @Override public Getbymerchantorderid setAccessToken(java.lang.String accessToken) { return (Getbymerchantorderid) super.setAccessToken(accessToken); } @Override public Getbymerchantorderid setAlt(java.lang.String alt) { return (Getbymerchantorderid) super.setAlt(alt); } @Override public Getbymerchantorderid setCallback(java.lang.String callback) { return (Getbymerchantorderid) super.setCallback(callback); } @Override public Getbymerchantorderid setFields(java.lang.String fields) { return (Getbymerchantorderid) super.setFields(fields); } @Override public Getbymerchantorderid setKey(java.lang.String key) { return (Getbymerchantorderid) super.setKey(key); } @Override public Getbymerchantorderid setOauthToken(java.lang.String oauthToken) { return (Getbymerchantorderid) super.setOauthToken(oauthToken); } @Override public Getbymerchantorderid setPrettyPrint(java.lang.Boolean prettyPrint) { return (Getbymerchantorderid) super.setPrettyPrint(prettyPrint); } @Override public Getbymerchantorderid setQuotaUser(java.lang.String quotaUser) { return (Getbymerchantorderid) super.setQuotaUser(quotaUser); } @Override public Getbymerchantorderid setUploadType(java.lang.String uploadType) { return (Getbymerchantorderid) super.setUploadType(uploadType); } @Override public Getbymerchantorderid setUploadProtocol(java.lang.String uploadProtocol) { return (Getbymerchantorderid) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Getbymerchantorderid setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The merchant order ID to be looked for. */ @com.google.api.client.util.Key private java.lang.String merchantOrderId; /** The merchant order ID to be looked for. */ public java.lang.String getMerchantOrderId() { return merchantOrderId; } /** The merchant order ID to be looked for. */ public Getbymerchantorderid setMerchantOrderId(java.lang.String merchantOrderId) { this.merchantOrderId = merchantOrderId; return this; } @Override public Getbymerchantorderid set(String parameterName, Object value) { return (Getbymerchantorderid) super.set(parameterName, value); } } /** * Sandbox only. Retrieves an order template that can be used to quickly create a new order in * sandbox. * * Create a request for the method "orders.gettestordertemplate". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Gettestordertemplate#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that should manage the order. This cannot be a multi-client account. * @param templateName The name of the template to retrieve. * @return the request */ public Gettestordertemplate gettestordertemplate(java.math.BigInteger merchantId, java.lang.String templateName) throws java.io.IOException { Gettestordertemplate result = new Gettestordertemplate(merchantId, templateName); initialize(result); return result; } public class Gettestordertemplate extends ShoppingContentRequest<com.google.api.services.content.model.OrdersGetTestOrderTemplateResponse> { private static final String REST_PATH = "{merchantId}/testordertemplates/{templateName}"; /** * Sandbox only. Retrieves an order template that can be used to quickly create a new order in * sandbox. * * Create a request for the method "orders.gettestordertemplate". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Gettestordertemplate#execute()} method to invoke the remote * operation. <p> {@link Gettestordertemplate#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that should manage the order. This cannot be a multi-client account. * @param templateName The name of the template to retrieve. * @since 1.13 */ protected Gettestordertemplate(java.math.BigInteger merchantId, java.lang.String templateName) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.OrdersGetTestOrderTemplateResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.templateName = com.google.api.client.util.Preconditions.checkNotNull(templateName, "Required parameter templateName must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Gettestordertemplate set$Xgafv(java.lang.String $Xgafv) { return (Gettestordertemplate) super.set$Xgafv($Xgafv); } @Override public Gettestordertemplate setAccessToken(java.lang.String accessToken) { return (Gettestordertemplate) super.setAccessToken(accessToken); } @Override public Gettestordertemplate setAlt(java.lang.String alt) { return (Gettestordertemplate) super.setAlt(alt); } @Override public Gettestordertemplate setCallback(java.lang.String callback) { return (Gettestordertemplate) super.setCallback(callback); } @Override public Gettestordertemplate setFields(java.lang.String fields) { return (Gettestordertemplate) super.setFields(fields); } @Override public Gettestordertemplate setKey(java.lang.String key) { return (Gettestordertemplate) super.setKey(key); } @Override public Gettestordertemplate setOauthToken(java.lang.String oauthToken) { return (Gettestordertemplate) super.setOauthToken(oauthToken); } @Override public Gettestordertemplate setPrettyPrint(java.lang.Boolean prettyPrint) { return (Gettestordertemplate) super.setPrettyPrint(prettyPrint); } @Override public Gettestordertemplate setQuotaUser(java.lang.String quotaUser) { return (Gettestordertemplate) super.setQuotaUser(quotaUser); } @Override public Gettestordertemplate setUploadType(java.lang.String uploadType) { return (Gettestordertemplate) super.setUploadType(uploadType); } @Override public Gettestordertemplate setUploadProtocol(java.lang.String uploadProtocol) { return (Gettestordertemplate) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that should manage the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that should manage the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that should manage the order. This cannot be a multi-client account. */ public Gettestordertemplate setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The name of the template to retrieve. */ @com.google.api.client.util.Key private java.lang.String templateName; /** The name of the template to retrieve. */ public java.lang.String getTemplateName() { return templateName; } /** The name of the template to retrieve. */ public Gettestordertemplate setTemplateName(java.lang.String templateName) { this.templateName = templateName; return this; } /** The country of the template to retrieve. Defaults to `US`. */ @com.google.api.client.util.Key private java.lang.String country; /** The country of the template to retrieve. Defaults to `US`. */ public java.lang.String getCountry() { return country; } /** The country of the template to retrieve. Defaults to `US`. */ public Gettestordertemplate setCountry(java.lang.String country) { this.country = country; return this; } @Override public Gettestordertemplate set(String parameterName, Object value) { return (Gettestordertemplate) super.set(parameterName, value); } } /** * Deprecated. Notifies that item return and refund was handled directly by merchant outside of * Google payments processing (e.g. cash refund done in store). Note: We recommend calling the * returnrefundlineitem method to refund in-store returns. We will issue the refund directly to the * customer. This helps to prevent possible differences arising between merchant and Google * transaction records. We also recommend having the point of sale system communicate with Google to * ensure that customers do not receive a double refund by first refunding via Google then via an * in-store return. * * Create a request for the method "orders.instorerefundlineitem". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Instorerefundlineitem#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersInStoreRefundLineItemRequest} * @return the request */ public Instorerefundlineitem instorerefundlineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersInStoreRefundLineItemRequest content) throws java.io.IOException { Instorerefundlineitem result = new Instorerefundlineitem(merchantId, orderId, content); initialize(result); return result; } public class Instorerefundlineitem extends ShoppingContentRequest<com.google.api.services.content.model.OrdersInStoreRefundLineItemResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/inStoreRefundLineItem"; /** * Deprecated. Notifies that item return and refund was handled directly by merchant outside of * Google payments processing (e.g. cash refund done in store). Note: We recommend calling the * returnrefundlineitem method to refund in-store returns. We will issue the refund directly to * the customer. This helps to prevent possible differences arising between merchant and Google * transaction records. We also recommend having the point of sale system communicate with Google * to ensure that customers do not receive a double refund by first refunding via Google then via * an in-store return. * * Create a request for the method "orders.instorerefundlineitem". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Instorerefundlineitem#execute()} method to invoke the remote * operation. <p> {@link Instorerefundlineitem#initialize(com.google.api.client.googleapis.service * s.AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersInStoreRefundLineItemRequest} * @since 1.13 */ protected Instorerefundlineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersInStoreRefundLineItemRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersInStoreRefundLineItemResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Instorerefundlineitem set$Xgafv(java.lang.String $Xgafv) { return (Instorerefundlineitem) super.set$Xgafv($Xgafv); } @Override public Instorerefundlineitem setAccessToken(java.lang.String accessToken) { return (Instorerefundlineitem) super.setAccessToken(accessToken); } @Override public Instorerefundlineitem setAlt(java.lang.String alt) { return (Instorerefundlineitem) super.setAlt(alt); } @Override public Instorerefundlineitem setCallback(java.lang.String callback) { return (Instorerefundlineitem) super.setCallback(callback); } @Override public Instorerefundlineitem setFields(java.lang.String fields) { return (Instorerefundlineitem) super.setFields(fields); } @Override public Instorerefundlineitem setKey(java.lang.String key) { return (Instorerefundlineitem) super.setKey(key); } @Override public Instorerefundlineitem setOauthToken(java.lang.String oauthToken) { return (Instorerefundlineitem) super.setOauthToken(oauthToken); } @Override public Instorerefundlineitem setPrettyPrint(java.lang.Boolean prettyPrint) { return (Instorerefundlineitem) super.setPrettyPrint(prettyPrint); } @Override public Instorerefundlineitem setQuotaUser(java.lang.String quotaUser) { return (Instorerefundlineitem) super.setQuotaUser(quotaUser); } @Override public Instorerefundlineitem setUploadType(java.lang.String uploadType) { return (Instorerefundlineitem) super.setUploadType(uploadType); } @Override public Instorerefundlineitem setUploadProtocol(java.lang.String uploadProtocol) { return (Instorerefundlineitem) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Instorerefundlineitem setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Instorerefundlineitem setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Instorerefundlineitem set(String parameterName, Object value) { return (Instorerefundlineitem) super.set(parameterName, value); } } /** * Lists the orders in your Merchant Center account. * * Create a request for the method "orders.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.OrdersListResponse> { private static final String REST_PATH = "{merchantId}/orders"; /** * Lists the orders in your Merchant Center account. * * Create a request for the method "orders.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.OrdersListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** * Obtains orders that match the acknowledgement status. When set to true, obtains orders that * have been acknowledged. When false, obtains orders that have not been acknowledged. We * recommend using this filter set to `false`, in conjunction with the `acknowledge` call, * such that only un-acknowledged orders are returned. */ @com.google.api.client.util.Key private java.lang.Boolean acknowledged; /** Obtains orders that match the acknowledgement status. When set to true, obtains orders that have been acknowledged. When false, obtains orders that have not been acknowledged. We recommend using this filter set to `false`, in conjunction with the `acknowledge` call, such that only un- acknowledged orders are returned. */ public java.lang.Boolean getAcknowledged() { return acknowledged; } /** * Obtains orders that match the acknowledgement status. When set to true, obtains orders that * have been acknowledged. When false, obtains orders that have not been acknowledged. We * recommend using this filter set to `false`, in conjunction with the `acknowledge` call, * such that only un-acknowledged orders are returned. */ public List setAcknowledged(java.lang.Boolean acknowledged) { this.acknowledged = acknowledged; return this; } /** * The maximum number of orders to return in the response, used for paging. The default value * is 25 orders per page, and the maximum allowed value is 250 orders per page. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of orders to return in the response, used for paging. The default value is 25 orders per page, and the maximum allowed value is 250 orders per page. */ public java.lang.Long getMaxResults() { return maxResults; } /** * The maximum number of orders to return in the response, used for paging. The default value * is 25 orders per page, and the maximum allowed value is 250 orders per page. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** * Order results by placement date in descending or ascending order. Acceptable values are: - * placedDateAsc - placedDateDesc */ @com.google.api.client.util.Key private java.lang.String orderBy; /** Order results by placement date in descending or ascending order. Acceptable values are: - placedDateAsc - placedDateDesc */ public java.lang.String getOrderBy() { return orderBy; } /** * Order results by placement date in descending or ascending order. Acceptable values are: - * placedDateAsc - placedDateDesc */ public List setOrderBy(java.lang.String orderBy) { this.orderBy = orderBy; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** Obtains orders placed before this date (exclusively), in ISO 8601 format. */ @com.google.api.client.util.Key private java.lang.String placedDateEnd; /** Obtains orders placed before this date (exclusively), in ISO 8601 format. */ public java.lang.String getPlacedDateEnd() { return placedDateEnd; } /** Obtains orders placed before this date (exclusively), in ISO 8601 format. */ public List setPlacedDateEnd(java.lang.String placedDateEnd) { this.placedDateEnd = placedDateEnd; return this; } /** Obtains orders placed after this date (inclusively), in ISO 8601 format. */ @com.google.api.client.util.Key private java.lang.String placedDateStart; /** Obtains orders placed after this date (inclusively), in ISO 8601 format. */ public java.lang.String getPlacedDateStart() { return placedDateStart; } /** Obtains orders placed after this date (inclusively), in ISO 8601 format. */ public List setPlacedDateStart(java.lang.String placedDateStart) { this.placedDateStart = placedDateStart; return this; } /** * Obtains orders that match any of the specified statuses. Please note that `active` is a * shortcut for `pendingShipment` and `partiallyShipped`, and `completed` is a shortcut for * `shipped`, `partiallyDelivered`, `delivered`, `partiallyReturned`, `returned`, and * `canceled`. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> statuses; /** Obtains orders that match any of the specified statuses. Please note that `active` is a shortcut for `pendingShipment` and `partiallyShipped`, and `completed` is a shortcut for `shipped`, `partiallyDelivered`, `delivered`, `partiallyReturned`, `returned`, and `canceled`. */ public java.util.List<java.lang.String> getStatuses() { return statuses; } /** * Obtains orders that match any of the specified statuses. Please note that `active` is a * shortcut for `pendingShipment` and `partiallyShipped`, and `completed` is a shortcut for * `shipped`, `partiallyDelivered`, `delivered`, `partiallyReturned`, `returned`, and * `canceled`. */ public List setStatuses(java.util.List<java.lang.String> statuses) { this.statuses = statuses; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Issues a partial or total refund for items and shipment. * * Create a request for the method "orders.refunditem". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Refunditem#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order to refund. * @param content the {@link com.google.api.services.content.model.OrdersRefundItemRequest} * @return the request */ public Refunditem refunditem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersRefundItemRequest content) throws java.io.IOException { Refunditem result = new Refunditem(merchantId, orderId, content); initialize(result); return result; } public class Refunditem extends ShoppingContentRequest<com.google.api.services.content.model.OrdersRefundItemResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/refunditem"; /** * Issues a partial or total refund for items and shipment. * * Create a request for the method "orders.refunditem". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Refunditem#execute()} method to invoke the remote operation. <p> * {@link * Refunditem#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order to refund. * @param content the {@link com.google.api.services.content.model.OrdersRefundItemRequest} * @since 1.13 */ protected Refunditem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersRefundItemRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersRefundItemResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Refunditem set$Xgafv(java.lang.String $Xgafv) { return (Refunditem) super.set$Xgafv($Xgafv); } @Override public Refunditem setAccessToken(java.lang.String accessToken) { return (Refunditem) super.setAccessToken(accessToken); } @Override public Refunditem setAlt(java.lang.String alt) { return (Refunditem) super.setAlt(alt); } @Override public Refunditem setCallback(java.lang.String callback) { return (Refunditem) super.setCallback(callback); } @Override public Refunditem setFields(java.lang.String fields) { return (Refunditem) super.setFields(fields); } @Override public Refunditem setKey(java.lang.String key) { return (Refunditem) super.setKey(key); } @Override public Refunditem setOauthToken(java.lang.String oauthToken) { return (Refunditem) super.setOauthToken(oauthToken); } @Override public Refunditem setPrettyPrint(java.lang.Boolean prettyPrint) { return (Refunditem) super.setPrettyPrint(prettyPrint); } @Override public Refunditem setQuotaUser(java.lang.String quotaUser) { return (Refunditem) super.setQuotaUser(quotaUser); } @Override public Refunditem setUploadType(java.lang.String uploadType) { return (Refunditem) super.setUploadType(uploadType); } @Override public Refunditem setUploadProtocol(java.lang.String uploadProtocol) { return (Refunditem) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Refunditem setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order to refund. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order to refund. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order to refund. */ public Refunditem setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Refunditem set(String parameterName, Object value) { return (Refunditem) super.set(parameterName, value); } } /** * Issues a partial or total refund for an order. * * Create a request for the method "orders.refundorder". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Refundorder#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order to refund. * @param content the {@link com.google.api.services.content.model.OrdersRefundOrderRequest} * @return the request */ public Refundorder refundorder(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersRefundOrderRequest content) throws java.io.IOException { Refundorder result = new Refundorder(merchantId, orderId, content); initialize(result); return result; } public class Refundorder extends ShoppingContentRequest<com.google.api.services.content.model.OrdersRefundOrderResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/refundorder"; /** * Issues a partial or total refund for an order. * * Create a request for the method "orders.refundorder". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Refundorder#execute()} method to invoke the remote operation. <p> * {@link * Refundorder#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order to refund. * @param content the {@link com.google.api.services.content.model.OrdersRefundOrderRequest} * @since 1.13 */ protected Refundorder(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersRefundOrderRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersRefundOrderResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Refundorder set$Xgafv(java.lang.String $Xgafv) { return (Refundorder) super.set$Xgafv($Xgafv); } @Override public Refundorder setAccessToken(java.lang.String accessToken) { return (Refundorder) super.setAccessToken(accessToken); } @Override public Refundorder setAlt(java.lang.String alt) { return (Refundorder) super.setAlt(alt); } @Override public Refundorder setCallback(java.lang.String callback) { return (Refundorder) super.setCallback(callback); } @Override public Refundorder setFields(java.lang.String fields) { return (Refundorder) super.setFields(fields); } @Override public Refundorder setKey(java.lang.String key) { return (Refundorder) super.setKey(key); } @Override public Refundorder setOauthToken(java.lang.String oauthToken) { return (Refundorder) super.setOauthToken(oauthToken); } @Override public Refundorder setPrettyPrint(java.lang.Boolean prettyPrint) { return (Refundorder) super.setPrettyPrint(prettyPrint); } @Override public Refundorder setQuotaUser(java.lang.String quotaUser) { return (Refundorder) super.setQuotaUser(quotaUser); } @Override public Refundorder setUploadType(java.lang.String uploadType) { return (Refundorder) super.setUploadType(uploadType); } @Override public Refundorder setUploadProtocol(java.lang.String uploadProtocol) { return (Refundorder) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Refundorder setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order to refund. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order to refund. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order to refund. */ public Refundorder setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Refundorder set(String parameterName, Object value) { return (Refundorder) super.set(parameterName, value); } } /** * Rejects return on an line item. * * Create a request for the method "orders.rejectreturnlineitem". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Rejectreturnlineitem#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersRejectReturnLineItemRequest} * @return the request */ public Rejectreturnlineitem rejectreturnlineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersRejectReturnLineItemRequest content) throws java.io.IOException { Rejectreturnlineitem result = new Rejectreturnlineitem(merchantId, orderId, content); initialize(result); return result; } public class Rejectreturnlineitem extends ShoppingContentRequest<com.google.api.services.content.model.OrdersRejectReturnLineItemResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/rejectReturnLineItem"; /** * Rejects return on an line item. * * Create a request for the method "orders.rejectreturnlineitem". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Rejectreturnlineitem#execute()} method to invoke the remote * operation. <p> {@link Rejectreturnlineitem#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersRejectReturnLineItemRequest} * @since 1.13 */ protected Rejectreturnlineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersRejectReturnLineItemRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersRejectReturnLineItemResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Rejectreturnlineitem set$Xgafv(java.lang.String $Xgafv) { return (Rejectreturnlineitem) super.set$Xgafv($Xgafv); } @Override public Rejectreturnlineitem setAccessToken(java.lang.String accessToken) { return (Rejectreturnlineitem) super.setAccessToken(accessToken); } @Override public Rejectreturnlineitem setAlt(java.lang.String alt) { return (Rejectreturnlineitem) super.setAlt(alt); } @Override public Rejectreturnlineitem setCallback(java.lang.String callback) { return (Rejectreturnlineitem) super.setCallback(callback); } @Override public Rejectreturnlineitem setFields(java.lang.String fields) { return (Rejectreturnlineitem) super.setFields(fields); } @Override public Rejectreturnlineitem setKey(java.lang.String key) { return (Rejectreturnlineitem) super.setKey(key); } @Override public Rejectreturnlineitem setOauthToken(java.lang.String oauthToken) { return (Rejectreturnlineitem) super.setOauthToken(oauthToken); } @Override public Rejectreturnlineitem setPrettyPrint(java.lang.Boolean prettyPrint) { return (Rejectreturnlineitem) super.setPrettyPrint(prettyPrint); } @Override public Rejectreturnlineitem setQuotaUser(java.lang.String quotaUser) { return (Rejectreturnlineitem) super.setQuotaUser(quotaUser); } @Override public Rejectreturnlineitem setUploadType(java.lang.String uploadType) { return (Rejectreturnlineitem) super.setUploadType(uploadType); } @Override public Rejectreturnlineitem setUploadProtocol(java.lang.String uploadProtocol) { return (Rejectreturnlineitem) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Rejectreturnlineitem setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Rejectreturnlineitem setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Rejectreturnlineitem set(String parameterName, Object value) { return (Rejectreturnlineitem) super.set(parameterName, value); } } /** * Returns and refunds a line item. Note that this method can only be called on fully shipped * orders. Please also note that the Orderreturns API is the preferred way to handle returns after * you receive a return from a customer. You can use Orderreturns.list or Orderreturns.get to search * for the return, and then use Orderreturns.processreturn to issue the refund. If the return cannot * be found, then we recommend using this API to issue a refund. * * Create a request for the method "orders.returnrefundlineitem". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Returnrefundlineitem#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersReturnRefundLineItemRequest} * @return the request */ public Returnrefundlineitem returnrefundlineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersReturnRefundLineItemRequest content) throws java.io.IOException { Returnrefundlineitem result = new Returnrefundlineitem(merchantId, orderId, content); initialize(result); return result; } public class Returnrefundlineitem extends ShoppingContentRequest<com.google.api.services.content.model.OrdersReturnRefundLineItemResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/returnRefundLineItem"; /** * Returns and refunds a line item. Note that this method can only be called on fully shipped * orders. Please also note that the Orderreturns API is the preferred way to handle returns after * you receive a return from a customer. You can use Orderreturns.list or Orderreturns.get to * search for the return, and then use Orderreturns.processreturn to issue the refund. If the * return cannot be found, then we recommend using this API to issue a refund. * * Create a request for the method "orders.returnrefundlineitem". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Returnrefundlineitem#execute()} method to invoke the remote * operation. <p> {@link Returnrefundlineitem#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersReturnRefundLineItemRequest} * @since 1.13 */ protected Returnrefundlineitem(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersReturnRefundLineItemRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersReturnRefundLineItemResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Returnrefundlineitem set$Xgafv(java.lang.String $Xgafv) { return (Returnrefundlineitem) super.set$Xgafv($Xgafv); } @Override public Returnrefundlineitem setAccessToken(java.lang.String accessToken) { return (Returnrefundlineitem) super.setAccessToken(accessToken); } @Override public Returnrefundlineitem setAlt(java.lang.String alt) { return (Returnrefundlineitem) super.setAlt(alt); } @Override public Returnrefundlineitem setCallback(java.lang.String callback) { return (Returnrefundlineitem) super.setCallback(callback); } @Override public Returnrefundlineitem setFields(java.lang.String fields) { return (Returnrefundlineitem) super.setFields(fields); } @Override public Returnrefundlineitem setKey(java.lang.String key) { return (Returnrefundlineitem) super.setKey(key); } @Override public Returnrefundlineitem setOauthToken(java.lang.String oauthToken) { return (Returnrefundlineitem) super.setOauthToken(oauthToken); } @Override public Returnrefundlineitem setPrettyPrint(java.lang.Boolean prettyPrint) { return (Returnrefundlineitem) super.setPrettyPrint(prettyPrint); } @Override public Returnrefundlineitem setQuotaUser(java.lang.String quotaUser) { return (Returnrefundlineitem) super.setQuotaUser(quotaUser); } @Override public Returnrefundlineitem setUploadType(java.lang.String uploadType) { return (Returnrefundlineitem) super.setUploadType(uploadType); } @Override public Returnrefundlineitem setUploadProtocol(java.lang.String uploadProtocol) { return (Returnrefundlineitem) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Returnrefundlineitem setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Returnrefundlineitem setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Returnrefundlineitem set(String parameterName, Object value) { return (Returnrefundlineitem) super.set(parameterName, value); } } /** * Sets (or overrides if it already exists) merchant provided annotations in the form of key-value * pairs. A common use case would be to supply us with additional structured information about a * line item that cannot be provided via other methods. Submitted key-value pairs can be retrieved * as part of the orders resource. * * Create a request for the method "orders.setlineitemmetadata". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Setlineitemmetadata#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersSetLineItemMetadataRequest} * @return the request */ public Setlineitemmetadata setlineitemmetadata(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersSetLineItemMetadataRequest content) throws java.io.IOException { Setlineitemmetadata result = new Setlineitemmetadata(merchantId, orderId, content); initialize(result); return result; } public class Setlineitemmetadata extends ShoppingContentRequest<com.google.api.services.content.model.OrdersSetLineItemMetadataResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/setLineItemMetadata"; /** * Sets (or overrides if it already exists) merchant provided annotations in the form of key-value * pairs. A common use case would be to supply us with additional structured information about a * line item that cannot be provided via other methods. Submitted key-value pairs can be retrieved * as part of the orders resource. * * Create a request for the method "orders.setlineitemmetadata". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Setlineitemmetadata#execute()} method to invoke the remote * operation. <p> {@link Setlineitemmetadata#initialize(com.google.api.client.googleapis.services. * AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersSetLineItemMetadataRequest} * @since 1.13 */ protected Setlineitemmetadata(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersSetLineItemMetadataRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersSetLineItemMetadataResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Setlineitemmetadata set$Xgafv(java.lang.String $Xgafv) { return (Setlineitemmetadata) super.set$Xgafv($Xgafv); } @Override public Setlineitemmetadata setAccessToken(java.lang.String accessToken) { return (Setlineitemmetadata) super.setAccessToken(accessToken); } @Override public Setlineitemmetadata setAlt(java.lang.String alt) { return (Setlineitemmetadata) super.setAlt(alt); } @Override public Setlineitemmetadata setCallback(java.lang.String callback) { return (Setlineitemmetadata) super.setCallback(callback); } @Override public Setlineitemmetadata setFields(java.lang.String fields) { return (Setlineitemmetadata) super.setFields(fields); } @Override public Setlineitemmetadata setKey(java.lang.String key) { return (Setlineitemmetadata) super.setKey(key); } @Override public Setlineitemmetadata setOauthToken(java.lang.String oauthToken) { return (Setlineitemmetadata) super.setOauthToken(oauthToken); } @Override public Setlineitemmetadata setPrettyPrint(java.lang.Boolean prettyPrint) { return (Setlineitemmetadata) super.setPrettyPrint(prettyPrint); } @Override public Setlineitemmetadata setQuotaUser(java.lang.String quotaUser) { return (Setlineitemmetadata) super.setQuotaUser(quotaUser); } @Override public Setlineitemmetadata setUploadType(java.lang.String uploadType) { return (Setlineitemmetadata) super.setUploadType(uploadType); } @Override public Setlineitemmetadata setUploadProtocol(java.lang.String uploadProtocol) { return (Setlineitemmetadata) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Setlineitemmetadata setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Setlineitemmetadata setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Setlineitemmetadata set(String parameterName, Object value) { return (Setlineitemmetadata) super.set(parameterName, value); } } /** * Marks line item(s) as shipped. * * Create a request for the method "orders.shiplineitems". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Shiplineitems#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersShipLineItemsRequest} * @return the request */ public Shiplineitems shiplineitems(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersShipLineItemsRequest content) throws java.io.IOException { Shiplineitems result = new Shiplineitems(merchantId, orderId, content); initialize(result); return result; } public class Shiplineitems extends ShoppingContentRequest<com.google.api.services.content.model.OrdersShipLineItemsResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/shipLineItems"; /** * Marks line item(s) as shipped. * * Create a request for the method "orders.shiplineitems". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Shiplineitems#execute()} method to invoke the remote operation. <p> * {@link Shiplineitems#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR * equest)} must be called to initialize this instance immediately after invoking the constructor. * </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersShipLineItemsRequest} * @since 1.13 */ protected Shiplineitems(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersShipLineItemsRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersShipLineItemsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Shiplineitems set$Xgafv(java.lang.String $Xgafv) { return (Shiplineitems) super.set$Xgafv($Xgafv); } @Override public Shiplineitems setAccessToken(java.lang.String accessToken) { return (Shiplineitems) super.setAccessToken(accessToken); } @Override public Shiplineitems setAlt(java.lang.String alt) { return (Shiplineitems) super.setAlt(alt); } @Override public Shiplineitems setCallback(java.lang.String callback) { return (Shiplineitems) super.setCallback(callback); } @Override public Shiplineitems setFields(java.lang.String fields) { return (Shiplineitems) super.setFields(fields); } @Override public Shiplineitems setKey(java.lang.String key) { return (Shiplineitems) super.setKey(key); } @Override public Shiplineitems setOauthToken(java.lang.String oauthToken) { return (Shiplineitems) super.setOauthToken(oauthToken); } @Override public Shiplineitems setPrettyPrint(java.lang.Boolean prettyPrint) { return (Shiplineitems) super.setPrettyPrint(prettyPrint); } @Override public Shiplineitems setQuotaUser(java.lang.String quotaUser) { return (Shiplineitems) super.setQuotaUser(quotaUser); } @Override public Shiplineitems setUploadType(java.lang.String uploadType) { return (Shiplineitems) super.setUploadType(uploadType); } @Override public Shiplineitems setUploadProtocol(java.lang.String uploadProtocol) { return (Shiplineitems) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Shiplineitems setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Shiplineitems setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Shiplineitems set(String parameterName, Object value) { return (Shiplineitems) super.set(parameterName, value); } } /** * Updates ship by and delivery by dates for a line item. * * Create a request for the method "orders.updatelineitemshippingdetails". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Updatelineitemshippingdetails#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersUpdateLineItemShippingDetailsRequest} * @return the request */ public Updatelineitemshippingdetails updatelineitemshippingdetails(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersUpdateLineItemShippingDetailsRequest content) throws java.io.IOException { Updatelineitemshippingdetails result = new Updatelineitemshippingdetails(merchantId, orderId, content); initialize(result); return result; } public class Updatelineitemshippingdetails extends ShoppingContentRequest<com.google.api.services.content.model.OrdersUpdateLineItemShippingDetailsResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/updateLineItemShippingDetails"; /** * Updates ship by and delivery by dates for a line item. * * Create a request for the method "orders.updatelineitemshippingdetails". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Updatelineitemshippingdetails#execute()} method to invoke the * remote operation. <p> {@link Updatelineitemshippingdetails#initialize(com.google.api.client.goo * gleapis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersUpdateLineItemShippingDetailsRequest} * @since 1.13 */ protected Updatelineitemshippingdetails(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersUpdateLineItemShippingDetailsRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersUpdateLineItemShippingDetailsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Updatelineitemshippingdetails set$Xgafv(java.lang.String $Xgafv) { return (Updatelineitemshippingdetails) super.set$Xgafv($Xgafv); } @Override public Updatelineitemshippingdetails setAccessToken(java.lang.String accessToken) { return (Updatelineitemshippingdetails) super.setAccessToken(accessToken); } @Override public Updatelineitemshippingdetails setAlt(java.lang.String alt) { return (Updatelineitemshippingdetails) super.setAlt(alt); } @Override public Updatelineitemshippingdetails setCallback(java.lang.String callback) { return (Updatelineitemshippingdetails) super.setCallback(callback); } @Override public Updatelineitemshippingdetails setFields(java.lang.String fields) { return (Updatelineitemshippingdetails) super.setFields(fields); } @Override public Updatelineitemshippingdetails setKey(java.lang.String key) { return (Updatelineitemshippingdetails) super.setKey(key); } @Override public Updatelineitemshippingdetails setOauthToken(java.lang.String oauthToken) { return (Updatelineitemshippingdetails) super.setOauthToken(oauthToken); } @Override public Updatelineitemshippingdetails setPrettyPrint(java.lang.Boolean prettyPrint) { return (Updatelineitemshippingdetails) super.setPrettyPrint(prettyPrint); } @Override public Updatelineitemshippingdetails setQuotaUser(java.lang.String quotaUser) { return (Updatelineitemshippingdetails) super.setQuotaUser(quotaUser); } @Override public Updatelineitemshippingdetails setUploadType(java.lang.String uploadType) { return (Updatelineitemshippingdetails) super.setUploadType(uploadType); } @Override public Updatelineitemshippingdetails setUploadProtocol(java.lang.String uploadProtocol) { return (Updatelineitemshippingdetails) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Updatelineitemshippingdetails setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Updatelineitemshippingdetails setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Updatelineitemshippingdetails set(String parameterName, Object value) { return (Updatelineitemshippingdetails) super.set(parameterName, value); } } /** * Updates the merchant order ID for a given order. * * Create a request for the method "orders.updatemerchantorderid". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Updatemerchantorderid#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersUpdateMerchantOrderIdRequest} * @return the request */ public Updatemerchantorderid updatemerchantorderid(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersUpdateMerchantOrderIdRequest content) throws java.io.IOException { Updatemerchantorderid result = new Updatemerchantorderid(merchantId, orderId, content); initialize(result); return result; } public class Updatemerchantorderid extends ShoppingContentRequest<com.google.api.services.content.model.OrdersUpdateMerchantOrderIdResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/updateMerchantOrderId"; /** * Updates the merchant order ID for a given order. * * Create a request for the method "orders.updatemerchantorderid". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Updatemerchantorderid#execute()} method to invoke the remote * operation. <p> {@link Updatemerchantorderid#initialize(com.google.api.client.googleapis.service * s.AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersUpdateMerchantOrderIdRequest} * @since 1.13 */ protected Updatemerchantorderid(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersUpdateMerchantOrderIdRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersUpdateMerchantOrderIdResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Updatemerchantorderid set$Xgafv(java.lang.String $Xgafv) { return (Updatemerchantorderid) super.set$Xgafv($Xgafv); } @Override public Updatemerchantorderid setAccessToken(java.lang.String accessToken) { return (Updatemerchantorderid) super.setAccessToken(accessToken); } @Override public Updatemerchantorderid setAlt(java.lang.String alt) { return (Updatemerchantorderid) super.setAlt(alt); } @Override public Updatemerchantorderid setCallback(java.lang.String callback) { return (Updatemerchantorderid) super.setCallback(callback); } @Override public Updatemerchantorderid setFields(java.lang.String fields) { return (Updatemerchantorderid) super.setFields(fields); } @Override public Updatemerchantorderid setKey(java.lang.String key) { return (Updatemerchantorderid) super.setKey(key); } @Override public Updatemerchantorderid setOauthToken(java.lang.String oauthToken) { return (Updatemerchantorderid) super.setOauthToken(oauthToken); } @Override public Updatemerchantorderid setPrettyPrint(java.lang.Boolean prettyPrint) { return (Updatemerchantorderid) super.setPrettyPrint(prettyPrint); } @Override public Updatemerchantorderid setQuotaUser(java.lang.String quotaUser) { return (Updatemerchantorderid) super.setQuotaUser(quotaUser); } @Override public Updatemerchantorderid setUploadType(java.lang.String uploadType) { return (Updatemerchantorderid) super.setUploadType(uploadType); } @Override public Updatemerchantorderid setUploadProtocol(java.lang.String uploadProtocol) { return (Updatemerchantorderid) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Updatemerchantorderid setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Updatemerchantorderid setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Updatemerchantorderid set(String parameterName, Object value) { return (Updatemerchantorderid) super.set(parameterName, value); } } /** * Updates a shipment's status, carrier, and/or tracking ID. * * Create a request for the method "orders.updateshipment". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Updateshipment#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersUpdateShipmentRequest} * @return the request */ public Updateshipment updateshipment(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersUpdateShipmentRequest content) throws java.io.IOException { Updateshipment result = new Updateshipment(merchantId, orderId, content); initialize(result); return result; } public class Updateshipment extends ShoppingContentRequest<com.google.api.services.content.model.OrdersUpdateShipmentResponse> { private static final String REST_PATH = "{merchantId}/orders/{orderId}/updateShipment"; /** * Updates a shipment's status, carrier, and/or tracking ID. * * Create a request for the method "orders.updateshipment". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Updateshipment#execute()} method to invoke the remote operation. * <p> {@link Updateshipment#initialize(com.google.api.client.googleapis.services.AbstractGoogleCl * ientRequest)} must be called to initialize this instance immediately after invoking the * constructor. </p> * * @param merchantId The ID of the account that manages the order. This cannot be a multi-client account. * @param orderId The ID of the order. * @param content the {@link com.google.api.services.content.model.OrdersUpdateShipmentRequest} * @since 1.13 */ protected Updateshipment(java.math.BigInteger merchantId, java.lang.String orderId, com.google.api.services.content.model.OrdersUpdateShipmentRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrdersUpdateShipmentResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.orderId = com.google.api.client.util.Preconditions.checkNotNull(orderId, "Required parameter orderId must be specified."); } @Override public Updateshipment set$Xgafv(java.lang.String $Xgafv) { return (Updateshipment) super.set$Xgafv($Xgafv); } @Override public Updateshipment setAccessToken(java.lang.String accessToken) { return (Updateshipment) super.setAccessToken(accessToken); } @Override public Updateshipment setAlt(java.lang.String alt) { return (Updateshipment) super.setAlt(alt); } @Override public Updateshipment setCallback(java.lang.String callback) { return (Updateshipment) super.setCallback(callback); } @Override public Updateshipment setFields(java.lang.String fields) { return (Updateshipment) super.setFields(fields); } @Override public Updateshipment setKey(java.lang.String key) { return (Updateshipment) super.setKey(key); } @Override public Updateshipment setOauthToken(java.lang.String oauthToken) { return (Updateshipment) super.setOauthToken(oauthToken); } @Override public Updateshipment setPrettyPrint(java.lang.Boolean prettyPrint) { return (Updateshipment) super.setPrettyPrint(prettyPrint); } @Override public Updateshipment setQuotaUser(java.lang.String quotaUser) { return (Updateshipment) super.setQuotaUser(quotaUser); } @Override public Updateshipment setUploadType(java.lang.String uploadType) { return (Updateshipment) super.setUploadType(uploadType); } @Override public Updateshipment setUploadProtocol(java.lang.String uploadProtocol) { return (Updateshipment) super.setUploadProtocol(uploadProtocol); } /** The ID of the account that manages the order. This cannot be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that manages the order. This cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account that manages the order. This cannot be a multi-client account. */ public Updateshipment setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the order. */ @com.google.api.client.util.Key private java.lang.String orderId; /** The ID of the order. */ public java.lang.String getOrderId() { return orderId; } /** The ID of the order. */ public Updateshipment setOrderId(java.lang.String orderId) { this.orderId = orderId; return this; } @Override public Updateshipment set(String parameterName, Object value) { return (Updateshipment) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Ordertrackingsignals collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Ordertrackingsignals.List request = content.ordertrackingsignals().list(parameters ...)} * </pre> * * @return the resource collection */ public Ordertrackingsignals ordertrackingsignals() { return new Ordertrackingsignals(); } /** * The "ordertrackingsignals" collection of methods. */ public class Ordertrackingsignals { /** * Creates new order tracking signal. * * Create a request for the method "ordertrackingsignals.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param merchantId The ID of the merchant for which the order signal is created. * @param content the {@link com.google.api.services.content.model.OrderTrackingSignal} * @return the request */ public Create create(java.lang.Long merchantId, com.google.api.services.content.model.OrderTrackingSignal content) throws java.io.IOException { Create result = new Create(merchantId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.OrderTrackingSignal> { private static final String REST_PATH = "{merchantId}/ordertrackingsignals"; /** * Creates new order tracking signal. * * Create a request for the method "ordertrackingsignals.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the merchant for which the order signal is created. * @param content the {@link com.google.api.services.content.model.OrderTrackingSignal} * @since 1.13 */ protected Create(java.lang.Long merchantId, com.google.api.services.content.model.OrderTrackingSignal content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.OrderTrackingSignal.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** The ID of the merchant for which the order signal is created. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** The ID of the merchant for which the order signal is created. */ public java.lang.Long getMerchantId() { return merchantId; } /** The ID of the merchant for which the order signal is created. */ public Create setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Pos collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Pos.List request = content.pos().list(parameters ...)} * </pre> * * @return the resource collection */ public Pos pos() { return new Pos(); } /** * The "pos" collection of methods. */ public class Pos { /** * Batches multiple POS-related calls in a single request. * * Create a request for the method "pos.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.PosCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.PosCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.PosCustomBatchResponse> { private static final String REST_PATH = "pos/batch"; /** * Batches multiple POS-related calls in a single request. * * Create a request for the method "pos.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.PosCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.PosCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.PosCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Deletes a store for the given merchant. * * Create a request for the method "pos.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param storeCode A store code that is unique per merchant. * @return the request */ public Delete delete(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, java.lang.String storeCode) throws java.io.IOException { Delete result = new Delete(merchantId, targetMerchantId, storeCode); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/pos/{targetMerchantId}/store/{storeCode}"; /** * Deletes a store for the given merchant. * * Create a request for the method "pos.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param storeCode A store code that is unique per merchant. * @since 1.13 */ protected Delete(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, java.lang.String storeCode) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.targetMerchantId = com.google.api.client.util.Preconditions.checkNotNull(targetMerchantId, "Required parameter targetMerchantId must be specified."); this.storeCode = com.google.api.client.util.Preconditions.checkNotNull(storeCode, "Required parameter storeCode must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** The ID of the POS or inventory data provider. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the POS or inventory data provider. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the POS or inventory data provider. */ public Delete setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the target merchant. */ @com.google.api.client.util.Key private java.math.BigInteger targetMerchantId; /** The ID of the target merchant. */ public java.math.BigInteger getTargetMerchantId() { return targetMerchantId; } /** The ID of the target merchant. */ public Delete setTargetMerchantId(java.math.BigInteger targetMerchantId) { this.targetMerchantId = targetMerchantId; return this; } /** A store code that is unique per merchant. */ @com.google.api.client.util.Key private java.lang.String storeCode; /** A store code that is unique per merchant. */ public java.lang.String getStoreCode() { return storeCode; } /** A store code that is unique per merchant. */ public Delete setStoreCode(java.lang.String storeCode) { this.storeCode = storeCode; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves information about the given store. * * Create a request for the method "pos.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param storeCode A store code that is unique per merchant. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, java.lang.String storeCode) throws java.io.IOException { Get result = new Get(merchantId, targetMerchantId, storeCode); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.PosStore> { private static final String REST_PATH = "{merchantId}/pos/{targetMerchantId}/store/{storeCode}"; /** * Retrieves information about the given store. * * Create a request for the method "pos.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param storeCode A store code that is unique per merchant. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, java.lang.String storeCode) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.PosStore.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.targetMerchantId = com.google.api.client.util.Preconditions.checkNotNull(targetMerchantId, "Required parameter targetMerchantId must be specified."); this.storeCode = com.google.api.client.util.Preconditions.checkNotNull(storeCode, "Required parameter storeCode must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The ID of the POS or inventory data provider. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the POS or inventory data provider. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the POS or inventory data provider. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the target merchant. */ @com.google.api.client.util.Key private java.math.BigInteger targetMerchantId; /** The ID of the target merchant. */ public java.math.BigInteger getTargetMerchantId() { return targetMerchantId; } /** The ID of the target merchant. */ public Get setTargetMerchantId(java.math.BigInteger targetMerchantId) { this.targetMerchantId = targetMerchantId; return this; } /** A store code that is unique per merchant. */ @com.google.api.client.util.Key private java.lang.String storeCode; /** A store code that is unique per merchant. */ public java.lang.String getStoreCode() { return storeCode; } /** A store code that is unique per merchant. */ public Get setStoreCode(java.lang.String storeCode) { this.storeCode = storeCode; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Creates a store for the given merchant. * * Create a request for the method "pos.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param content the {@link com.google.api.services.content.model.PosStore} * @return the request */ public Insert insert(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, com.google.api.services.content.model.PosStore content) throws java.io.IOException { Insert result = new Insert(merchantId, targetMerchantId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.PosStore> { private static final String REST_PATH = "{merchantId}/pos/{targetMerchantId}/store"; /** * Creates a store for the given merchant. * * Create a request for the method "pos.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param content the {@link com.google.api.services.content.model.PosStore} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, com.google.api.services.content.model.PosStore content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.PosStore.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.targetMerchantId = com.google.api.client.util.Preconditions.checkNotNull(targetMerchantId, "Required parameter targetMerchantId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** The ID of the POS or inventory data provider. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the POS or inventory data provider. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the POS or inventory data provider. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the target merchant. */ @com.google.api.client.util.Key private java.math.BigInteger targetMerchantId; /** The ID of the target merchant. */ public java.math.BigInteger getTargetMerchantId() { return targetMerchantId; } /** The ID of the target merchant. */ public Insert setTargetMerchantId(java.math.BigInteger targetMerchantId) { this.targetMerchantId = targetMerchantId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Submit inventory for the given merchant. * * Create a request for the method "pos.inventory". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Inventory#execute()} method to invoke the remote operation. * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param content the {@link com.google.api.services.content.model.PosInventoryRequest} * @return the request */ public Inventory inventory(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, com.google.api.services.content.model.PosInventoryRequest content) throws java.io.IOException { Inventory result = new Inventory(merchantId, targetMerchantId, content); initialize(result); return result; } public class Inventory extends ShoppingContentRequest<com.google.api.services.content.model.PosInventoryResponse> { private static final String REST_PATH = "{merchantId}/pos/{targetMerchantId}/inventory"; /** * Submit inventory for the given merchant. * * Create a request for the method "pos.inventory". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Inventory#execute()} method to invoke the remote operation. <p> * {@link * Inventory#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param content the {@link com.google.api.services.content.model.PosInventoryRequest} * @since 1.13 */ protected Inventory(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, com.google.api.services.content.model.PosInventoryRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.PosInventoryResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.targetMerchantId = com.google.api.client.util.Preconditions.checkNotNull(targetMerchantId, "Required parameter targetMerchantId must be specified."); } @Override public Inventory set$Xgafv(java.lang.String $Xgafv) { return (Inventory) super.set$Xgafv($Xgafv); } @Override public Inventory setAccessToken(java.lang.String accessToken) { return (Inventory) super.setAccessToken(accessToken); } @Override public Inventory setAlt(java.lang.String alt) { return (Inventory) super.setAlt(alt); } @Override public Inventory setCallback(java.lang.String callback) { return (Inventory) super.setCallback(callback); } @Override public Inventory setFields(java.lang.String fields) { return (Inventory) super.setFields(fields); } @Override public Inventory setKey(java.lang.String key) { return (Inventory) super.setKey(key); } @Override public Inventory setOauthToken(java.lang.String oauthToken) { return (Inventory) super.setOauthToken(oauthToken); } @Override public Inventory setPrettyPrint(java.lang.Boolean prettyPrint) { return (Inventory) super.setPrettyPrint(prettyPrint); } @Override public Inventory setQuotaUser(java.lang.String quotaUser) { return (Inventory) super.setQuotaUser(quotaUser); } @Override public Inventory setUploadType(java.lang.String uploadType) { return (Inventory) super.setUploadType(uploadType); } @Override public Inventory setUploadProtocol(java.lang.String uploadProtocol) { return (Inventory) super.setUploadProtocol(uploadProtocol); } /** The ID of the POS or inventory data provider. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the POS or inventory data provider. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the POS or inventory data provider. */ public Inventory setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the target merchant. */ @com.google.api.client.util.Key private java.math.BigInteger targetMerchantId; /** The ID of the target merchant. */ public java.math.BigInteger getTargetMerchantId() { return targetMerchantId; } /** The ID of the target merchant. */ public Inventory setTargetMerchantId(java.math.BigInteger targetMerchantId) { this.targetMerchantId = targetMerchantId; return this; } @Override public Inventory set(String parameterName, Object value) { return (Inventory) super.set(parameterName, value); } } /** * Lists the stores of the target merchant. * * Create a request for the method "pos.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @return the request */ public List list(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId) throws java.io.IOException { List result = new List(merchantId, targetMerchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.PosListResponse> { private static final String REST_PATH = "{merchantId}/pos/{targetMerchantId}/store"; /** * Lists the stores of the target merchant. * * Create a request for the method "pos.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @since 1.13 */ protected List(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.PosListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.targetMerchantId = com.google.api.client.util.Preconditions.checkNotNull(targetMerchantId, "Required parameter targetMerchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the POS or inventory data provider. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the POS or inventory data provider. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the POS or inventory data provider. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the target merchant. */ @com.google.api.client.util.Key private java.math.BigInteger targetMerchantId; /** The ID of the target merchant. */ public java.math.BigInteger getTargetMerchantId() { return targetMerchantId; } /** The ID of the target merchant. */ public List setTargetMerchantId(java.math.BigInteger targetMerchantId) { this.targetMerchantId = targetMerchantId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Submit a sale event for the given merchant. * * Create a request for the method "pos.sale". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Sale#execute()} method to invoke the remote operation. * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param content the {@link com.google.api.services.content.model.PosSaleRequest} * @return the request */ public Sale sale(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, com.google.api.services.content.model.PosSaleRequest content) throws java.io.IOException { Sale result = new Sale(merchantId, targetMerchantId, content); initialize(result); return result; } public class Sale extends ShoppingContentRequest<com.google.api.services.content.model.PosSaleResponse> { private static final String REST_PATH = "{merchantId}/pos/{targetMerchantId}/sale"; /** * Submit a sale event for the given merchant. * * Create a request for the method "pos.sale". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Sale#execute()} method to invoke the remote operation. <p> {@link * Sale#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the POS or inventory data provider. * @param targetMerchantId The ID of the target merchant. * @param content the {@link com.google.api.services.content.model.PosSaleRequest} * @since 1.13 */ protected Sale(java.math.BigInteger merchantId, java.math.BigInteger targetMerchantId, com.google.api.services.content.model.PosSaleRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.PosSaleResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.targetMerchantId = com.google.api.client.util.Preconditions.checkNotNull(targetMerchantId, "Required parameter targetMerchantId must be specified."); } @Override public Sale set$Xgafv(java.lang.String $Xgafv) { return (Sale) super.set$Xgafv($Xgafv); } @Override public Sale setAccessToken(java.lang.String accessToken) { return (Sale) super.setAccessToken(accessToken); } @Override public Sale setAlt(java.lang.String alt) { return (Sale) super.setAlt(alt); } @Override public Sale setCallback(java.lang.String callback) { return (Sale) super.setCallback(callback); } @Override public Sale setFields(java.lang.String fields) { return (Sale) super.setFields(fields); } @Override public Sale setKey(java.lang.String key) { return (Sale) super.setKey(key); } @Override public Sale setOauthToken(java.lang.String oauthToken) { return (Sale) super.setOauthToken(oauthToken); } @Override public Sale setPrettyPrint(java.lang.Boolean prettyPrint) { return (Sale) super.setPrettyPrint(prettyPrint); } @Override public Sale setQuotaUser(java.lang.String quotaUser) { return (Sale) super.setQuotaUser(quotaUser); } @Override public Sale setUploadType(java.lang.String uploadType) { return (Sale) super.setUploadType(uploadType); } @Override public Sale setUploadProtocol(java.lang.String uploadProtocol) { return (Sale) super.setUploadProtocol(uploadProtocol); } /** The ID of the POS or inventory data provider. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the POS or inventory data provider. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the POS or inventory data provider. */ public Sale setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the target merchant. */ @com.google.api.client.util.Key private java.math.BigInteger targetMerchantId; /** The ID of the target merchant. */ public java.math.BigInteger getTargetMerchantId() { return targetMerchantId; } /** The ID of the target merchant. */ public Sale setTargetMerchantId(java.math.BigInteger targetMerchantId) { this.targetMerchantId = targetMerchantId; return this; } @Override public Sale set(String parameterName, Object value) { return (Sale) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Products collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Products.List request = content.products().list(parameters ...)} * </pre> * * @return the resource collection */ public Products products() { return new Products(); } /** * The "products" collection of methods. */ public class Products { /** * Retrieves, inserts, and deletes multiple products in a single request. * * Create a request for the method "products.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.ProductsCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.ProductsCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.ProductsCustomBatchResponse> { private static final String REST_PATH = "products/batch"; /** * Retrieves, inserts, and deletes multiple products in a single request. * * Create a request for the method "products.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.ProductsCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.ProductsCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ProductsCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Deletes a product from your Merchant Center account. * * Create a request for the method "products.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product. * @return the request */ public Delete delete(java.math.BigInteger merchantId, java.lang.String productId) throws java.io.IOException { Delete result = new Delete(merchantId, productId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/products/{productId}"; /** * Deletes a product from your Merchant Center account. * * Create a request for the method "products.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product. * @since 1.13 */ protected Delete(java.math.BigInteger merchantId, java.lang.String productId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the product. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ public Delete setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The REST ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The REST ID of the product. */ public java.lang.String getProductId() { return productId; } /** The REST ID of the product. */ public Delete setProductId(java.lang.String productId) { this.productId = productId; return this; } /** The Content API Supplemental Feed ID. */ @com.google.api.client.util.Key private java.math.BigInteger feedId; /** The Content API Supplemental Feed ID. */ public java.math.BigInteger getFeedId() { return feedId; } /** The Content API Supplemental Feed ID. */ public Delete setFeedId(java.math.BigInteger feedId) { this.feedId = feedId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves a product from your Merchant Center account. * * Create a request for the method "products.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String productId) throws java.io.IOException { Get result = new Get(merchantId, productId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Product> { private static final String REST_PATH = "{merchantId}/products/{productId}"; /** * Retrieves a product from your Merchant Center account. * * Create a request for the method "products.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String productId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Product.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the product. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The REST ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The REST ID of the product. */ public java.lang.String getProductId() { return productId; } /** The REST ID of the product. */ public Get setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Uploads a product to your Merchant Center account. If an item with the same channel, * contentLanguage, offerId, and targetCountry already exists, this method updates that entry. * * Create a request for the method "products.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.Product} * @return the request */ public Insert insert(java.math.BigInteger merchantId, com.google.api.services.content.model.Product content) throws java.io.IOException { Insert result = new Insert(merchantId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.Product> { private static final String REST_PATH = "{merchantId}/products"; /** * Uploads a product to your Merchant Center account. If an item with the same channel, * contentLanguage, offerId, and targetCountry already exists, this method updates that entry. * * Create a request for the method "products.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param content the {@link com.google.api.services.content.model.Product} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, com.google.api.services.content.model.Product content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.Product.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the product. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The Content API Supplemental Feed ID. */ @com.google.api.client.util.Key private java.math.BigInteger feedId; /** The Content API Supplemental Feed ID. */ public java.math.BigInteger getFeedId() { return feedId; } /** The Content API Supplemental Feed ID. */ public Insert setFeedId(java.math.BigInteger feedId) { this.feedId = feedId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Lists the products in your Merchant Center account. The response might contain fewer items than * specified by maxResults. Rely on nextPageToken to determine if there are more items to be * requested. * * Create a request for the method "products.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the products. This account cannot be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ProductsListResponse> { private static final String REST_PATH = "{merchantId}/products"; /** * Lists the products in your Merchant Center account. The response might contain fewer items than * specified by maxResults. Rely on nextPageToken to determine if there are more items to be * requested. * * Create a request for the method "products.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the products. This account cannot be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ProductsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the products. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the products. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the products. This account cannot be a multi-client * account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The maximum number of products to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of products to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of products to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Productstatuses collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Productstatuses.List request = content.productstatuses().list(parameters ...)} * </pre> * * @return the resource collection */ public Productstatuses productstatuses() { return new Productstatuses(); } /** * The "productstatuses" collection of methods. */ public class Productstatuses { /** * Gets the statuses of multiple products in a single request. * * Create a request for the method "productstatuses.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.ProductstatusesCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.ProductstatusesCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.ProductstatusesCustomBatchResponse> { private static final String REST_PATH = "productstatuses/batch"; /** * Gets the statuses of multiple products in a single request. * * Create a request for the method "productstatuses.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.ProductstatusesCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.ProductstatusesCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ProductstatusesCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Gets the status of a product from your Merchant Center account. * * Create a request for the method "productstatuses.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String productId) throws java.io.IOException { Get result = new Get(merchantId, productId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.ProductStatus> { private static final String REST_PATH = "{merchantId}/productstatuses/{productId}"; /** * Gets the status of a product from your Merchant Center account. * * Create a request for the method "productstatuses.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String productId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ProductStatus.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the product. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The REST ID of the product. */ @com.google.api.client.util.Key private java.lang.String productId; /** The REST ID of the product. */ public java.lang.String getProductId() { return productId; } /** The REST ID of the product. */ public Get setProductId(java.lang.String productId) { this.productId = productId; return this; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinations; /** If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination. */ public java.util.List<java.lang.String> getDestinations() { return destinations; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ public Get setDestinations(java.util.List<java.lang.String> destinations) { this.destinations = destinations; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the statuses of the products in your Merchant Center account. * * Create a request for the method "productstatuses.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the products. This account cannot be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ProductstatusesListResponse> { private static final String REST_PATH = "{merchantId}/productstatuses"; /** * Lists the statuses of the products in your Merchant Center account. * * Create a request for the method "productstatuses.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the products. This account cannot be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ProductstatusesListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the products. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the products. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the products. This account cannot be a multi-client * account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinations; /** If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination. */ public java.util.List<java.lang.String> getDestinations() { return destinations; } /** * If set, only issues for the specified destinations are returned, otherwise only issues for * the Shopping destination. */ public List setDestinations(java.util.List<java.lang.String> destinations) { this.destinations = destinations; return this; } /** The maximum number of product statuses to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of product statuses to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of product statuses to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * An accessor for creating requests from the Repricingreports collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Repricingreports.List request = content.repricingreports().list(parameters ...)} * </pre> * * @return the resource collection */ public Repricingreports repricingreports() { return new Repricingreports(); } /** * The "repricingreports" collection of methods. */ public class Repricingreports { /** * Lists the metrics report for a given Repricing product. * * Create a request for the method "repricingreports.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. Id of the merchant who owns the Repricing rule. * @param productId Required. Id of the Repricing product. Also known as the [REST_ID](https://developers.google.com * /shopping-content/reference/rest/v2.1/products#Product.FIELDS.id) * @return the request */ public List list(java.lang.Long merchantId, java.lang.String productId) throws java.io.IOException { List result = new List(merchantId, productId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListRepricingProductReportsResponse> { private static final String REST_PATH = "{merchantId}/productstatuses/{productId}/repricingreports"; /** * Lists the metrics report for a given Repricing product. * * Create a request for the method "repricingreports.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. Id of the merchant who owns the Repricing rule. * @param productId Required. Id of the Repricing product. Also known as the [REST_ID](https://developers.google.com * /shopping-content/reference/rest/v2.1/products#Product.FIELDS.id) * @since 1.13 */ protected List(java.lang.Long merchantId, java.lang.String productId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListRepricingProductReportsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** Required. Id of the merchant who owns the Repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. Id of the merchant who owns the Repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. Id of the merchant who owns the Repricing rule. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * Required. Id of the Repricing product. Also known as the * [REST_ID](https://developers.google.com/shopping- * content/reference/rest/v2.1/products#Product.FIELDS.id) */ @com.google.api.client.util.Key private java.lang.String productId; /** Required. Id of the Repricing product. Also known as the [REST_ID](https://developers.google.com /shopping-content/reference/rest/v2.1/products#Product.FIELDS.id) */ public java.lang.String getProductId() { return productId; } /** * Required. Id of the Repricing product. Also known as the * [REST_ID](https://developers.google.com/shopping- * content/reference/rest/v2.1/products#Product.FIELDS.id) */ public List setProductId(java.lang.String productId) { this.productId = productId; return this; } /** * Gets Repricing reports on and before this date in the merchant's timezone. You can only * retrieve data up to 7 days ago (default) or earlier. Format is YYYY-MM-DD. */ @com.google.api.client.util.Key private java.lang.String endDate; /** Gets Repricing reports on and before this date in the merchant's timezone. You can only retrieve data up to 7 days ago (default) or earlier. Format is YYYY-MM-DD. */ public java.lang.String getEndDate() { return endDate; } /** * Gets Repricing reports on and before this date in the merchant's timezone. You can only * retrieve data up to 7 days ago (default) or earlier. Format is YYYY-MM-DD. */ public List setEndDate(java.lang.String endDate) { this.endDate = endDate; return this; } /** * Maximum number of days of reports to return. There can be more than one rule report * returned per day. For example, if 3 rule types got applied to the same product within a * 24-hour period, then a page_size of 1 will return 3 rule reports. The page size defaults * to 50 and values above 1000 are coerced to 1000. This service may return fewer days of * reports than this value, for example, if the time between your start and end date is less * than the page size. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Maximum number of days of reports to return. There can be more than one rule report returned per day. For example, if 3 rule types got applied to the same product within a 24-hour period, then a page_size of 1 will return 3 rule reports. The page size defaults to 50 and values above 1000 are coerced to 1000. This service may return fewer days of reports than this value, for example, if the time between your start and end date is less than the page size. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Maximum number of days of reports to return. There can be more than one rule report * returned per day. For example, if 3 rule types got applied to the same product within a * 24-hour period, then a page_size of 1 will return 3 rule reports. The page size defaults * to 50 and values above 1000 are coerced to 1000. This service may return fewer days of * reports than this value, for example, if the time between your start and end date is less * than the page size. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** Token (if provided) to retrieve the subsequent page. All other parameters must match the original call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** Id of the Repricing rule. If specified, only gets this rule's reports. */ @com.google.api.client.util.Key private java.lang.String ruleId; /** Id of the Repricing rule. If specified, only gets this rule's reports. */ public java.lang.String getRuleId() { return ruleId; } /** Id of the Repricing rule. If specified, only gets this rule's reports. */ public List setRuleId(java.lang.String ruleId) { this.ruleId = ruleId; return this; } /** * Gets Repricing reports on and after this date in the merchant's timezone, up to one year * ago. Do not use a start date later than 7 days ago (default). Format is YYYY-MM-DD. */ @com.google.api.client.util.Key private java.lang.String startDate; /** Gets Repricing reports on and after this date in the merchant's timezone, up to one year ago. Do not use a start date later than 7 days ago (default). Format is YYYY-MM-DD. */ public java.lang.String getStartDate() { return startDate; } /** * Gets Repricing reports on and after this date in the merchant's timezone, up to one year * ago. Do not use a start date later than 7 days ago (default). Format is YYYY-MM-DD. */ public List setStartDate(java.lang.String startDate) { this.startDate = startDate; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } } /** * An accessor for creating requests from the Pubsubnotificationsettings collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Pubsubnotificationsettings.List request = content.pubsubnotificationsettings().list(parameters ...)} * </pre> * * @return the resource collection */ public Pubsubnotificationsettings pubsubnotificationsettings() { return new Pubsubnotificationsettings(); } /** * The "pubsubnotificationsettings" collection of methods. */ public class Pubsubnotificationsettings { /** * Retrieves a Merchant Center account's pubsub notification settings. * * Create a request for the method "pubsubnotificationsettings.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account for which to get pubsub notification settings. * @return the request */ public Get get(java.math.BigInteger merchantId) throws java.io.IOException { Get result = new Get(merchantId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.PubsubNotificationSettings> { private static final String REST_PATH = "{merchantId}/pubsubnotificationsettings"; /** * Retrieves a Merchant Center account's pubsub notification settings. * * Create a request for the method "pubsubnotificationsettings.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account for which to get pubsub notification settings. * @since 1.13 */ protected Get(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.PubsubNotificationSettings.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The ID of the account for which to get pubsub notification settings. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account for which to get pubsub notification settings. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account for which to get pubsub notification settings. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Register a Merchant Center account for pubsub notifications. Note that cloud topic name should * not be provided as part of the request. * * Create a request for the method "pubsubnotificationsettings.update". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account. * @param content the {@link com.google.api.services.content.model.PubsubNotificationSettings} * @return the request */ public Update update(java.math.BigInteger merchantId, com.google.api.services.content.model.PubsubNotificationSettings content) throws java.io.IOException { Update result = new Update(merchantId, content); initialize(result); return result; } public class Update extends ShoppingContentRequest<com.google.api.services.content.model.PubsubNotificationSettings> { private static final String REST_PATH = "{merchantId}/pubsubnotificationsettings"; /** * Register a Merchant Center account for pubsub notifications. Note that cloud topic name should * not be provided as part of the request. * * Create a request for the method "pubsubnotificationsettings.update". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account. * @param content the {@link com.google.api.services.content.model.PubsubNotificationSettings} * @since 1.13 */ protected Update(java.math.BigInteger merchantId, com.google.api.services.content.model.PubsubNotificationSettings content) { super(ShoppingContent.this, "PUT", REST_PATH, content, com.google.api.services.content.model.PubsubNotificationSettings.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** The ID of the account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account. */ public Update setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Regionalinventory collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Regionalinventory.List request = content.regionalinventory().list(parameters ...)} * </pre> * * @return the resource collection */ public Regionalinventory regionalinventory() { return new Regionalinventory(); } /** * The "regionalinventory" collection of methods. */ public class Regionalinventory { /** * Updates regional inventory for multiple products or regions in a single request. * * Create a request for the method "regionalinventory.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.RegionalinventoryCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.RegionalinventoryCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.RegionalinventoryCustomBatchResponse> { private static final String REST_PATH = "regionalinventory/batch"; /** * Updates regional inventory for multiple products or regions in a single request. * * Create a request for the method "regionalinventory.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.RegionalinventoryCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.RegionalinventoryCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.RegionalinventoryCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Update the regional inventory of a product in your Merchant Center account. If a regional * inventory with the same region ID already exists, this method updates that entry. * * Create a request for the method "regionalinventory.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product for which to update the regional inventory. * @param content the {@link com.google.api.services.content.model.RegionalInventory} * @return the request */ public Insert insert(java.math.BigInteger merchantId, java.lang.String productId, com.google.api.services.content.model.RegionalInventory content) throws java.io.IOException { Insert result = new Insert(merchantId, productId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.RegionalInventory> { private static final String REST_PATH = "{merchantId}/products/{productId}/regionalinventory"; /** * Update the regional inventory of a product in your Merchant Center account. If a regional * inventory with the same region ID already exists, this method updates that entry. * * Create a request for the method "regionalinventory.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the account that contains the product. This account cannot be a multi-client account. * @param productId The REST ID of the product for which to update the regional inventory. * @param content the {@link com.google.api.services.content.model.RegionalInventory} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, java.lang.String productId, com.google.api.services.content.model.RegionalInventory content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.RegionalInventory.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.productId = com.google.api.client.util.Preconditions.checkNotNull(productId, "Required parameter productId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account that contains the product. This account cannot be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the account that contains the product. This account cannot be a multi-client * account. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The REST ID of the product for which to update the regional inventory. */ @com.google.api.client.util.Key private java.lang.String productId; /** The REST ID of the product for which to update the regional inventory. */ public java.lang.String getProductId() { return productId; } /** The REST ID of the product for which to update the regional inventory. */ public Insert setProductId(java.lang.String productId) { this.productId = productId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Regions collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Regions.List request = content.regions().list(parameters ...)} * </pre> * * @return the resource collection */ public Regions regions() { return new Regions(); } /** * The "regions" collection of methods. */ public class Regions { /** * Creates a region definition in your Merchant Center account. * * Create a request for the method "regions.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to create region definition. * @param content the {@link com.google.api.services.content.model.Region} * @return the request */ public Create create(java.lang.Long merchantId, com.google.api.services.content.model.Region content) throws java.io.IOException { Create result = new Create(merchantId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.Region> { private static final String REST_PATH = "{merchantId}/regions"; /** * Creates a region definition in your Merchant Center account. * * Create a request for the method "regions.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to create region definition. * @param content the {@link com.google.api.services.content.model.Region} * @since 1.13 */ protected Create(java.lang.Long merchantId, com.google.api.services.content.model.Region content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.Region.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant for which to create region definition. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to create region definition. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant for which to create region definition. */ public Create setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the region to create. */ @com.google.api.client.util.Key private java.lang.String regionId; /** Required. The id of the region to create. */ public java.lang.String getRegionId() { return regionId; } /** Required. The id of the region to create. */ public Create setRegionId(java.lang.String regionId) { this.regionId = regionId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a region definition from your Merchant Center account. * * Create a request for the method "regions.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to delete region definition. * @param regionId Required. The id of the region to delete. * @return the request */ public Delete delete(java.lang.Long merchantId, java.lang.String regionId) throws java.io.IOException { Delete result = new Delete(merchantId, regionId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/regions/{regionId}"; /** * Deletes a region definition from your Merchant Center account. * * Create a request for the method "regions.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to delete region definition. * @param regionId Required. The id of the region to delete. * @since 1.13 */ protected Delete(java.lang.Long merchantId, java.lang.String regionId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionId = com.google.api.client.util.Preconditions.checkNotNull(regionId, "Required parameter regionId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant for which to delete region definition. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to delete region definition. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant for which to delete region definition. */ public Delete setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the region to delete. */ @com.google.api.client.util.Key private java.lang.String regionId; /** Required. The id of the region to delete. */ public java.lang.String getRegionId() { return regionId; } /** Required. The id of the region to delete. */ public Delete setRegionId(java.lang.String regionId) { this.regionId = regionId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves a region defined in your Merchant Center account. * * Create a request for the method "regions.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to retrieve region definition. * @param regionId Required. The id of the region to retrieve. * @return the request */ public Get get(java.lang.Long merchantId, java.lang.String regionId) throws java.io.IOException { Get result = new Get(merchantId, regionId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.Region> { private static final String REST_PATH = "{merchantId}/regions/{regionId}"; /** * Retrieves a region defined in your Merchant Center account. * * Create a request for the method "regions.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to retrieve region definition. * @param regionId Required. The id of the region to retrieve. * @since 1.13 */ protected Get(java.lang.Long merchantId, java.lang.String regionId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.Region.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionId = com.google.api.client.util.Preconditions.checkNotNull(regionId, "Required parameter regionId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant for which to retrieve region definition. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to retrieve region definition. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant for which to retrieve region definition. */ public Get setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the region to retrieve. */ @com.google.api.client.util.Key private java.lang.String regionId; /** Required. The id of the region to retrieve. */ public java.lang.String getRegionId() { return regionId; } /** Required. The id of the region to retrieve. */ public Get setRegionId(java.lang.String regionId) { this.regionId = regionId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the regions in your Merchant Center account. * * Create a request for the method "regions.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to list region definitions. * @return the request */ public List list(java.lang.Long merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListRegionsResponse> { private static final String REST_PATH = "{merchantId}/regions"; /** * Lists the regions in your Merchant Center account. * * Create a request for the method "regions.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to list region definitions. * @since 1.13 */ protected List(java.lang.Long merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListRegionsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant for which to list region definitions. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to list region definitions. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant for which to list region definitions. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * The maximum number of regions to return. The service may return fewer than this value. If * unspecified, at most 50 rules will be returned. The maximum value is 1000; values above * 1000 will be coerced to 1000. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The maximum number of regions to return. The service may return fewer than this value. If unspecified, at most 50 rules will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. */ public java.lang.Integer getPageSize() { return pageSize; } /** * The maximum number of regions to return. The service may return fewer than this value. If * unspecified, at most 50 rules will be returned. The maximum value is 1000; values above * 1000 will be coerced to 1000. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A page token, received from a previous `ListRegions` call. Provide this to retrieve the * subsequent page. When paginating, all other parameters provided to `ListRegions` must match * the call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A page token, received from a previous `ListRegions` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListRegions` must match the call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * A page token, received from a previous `ListRegions` call. Provide this to retrieve the * subsequent page. When paginating, all other parameters provided to `ListRegions` must match * the call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a region definition in your Merchant Center account. * * Create a request for the method "regions.patch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to update region definition. * @param regionId Required. The id of the region to update. * @param content the {@link com.google.api.services.content.model.Region} * @return the request */ public Patch patch(java.lang.Long merchantId, java.lang.String regionId, com.google.api.services.content.model.Region content) throws java.io.IOException { Patch result = new Patch(merchantId, regionId, content); initialize(result); return result; } public class Patch extends ShoppingContentRequest<com.google.api.services.content.model.Region> { private static final String REST_PATH = "{merchantId}/regions/{regionId}"; /** * Updates a region definition in your Merchant Center account. * * Create a request for the method "regions.patch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to update region definition. * @param regionId Required. The id of the region to update. * @param content the {@link com.google.api.services.content.model.Region} * @since 1.13 */ protected Patch(java.lang.Long merchantId, java.lang.String regionId, com.google.api.services.content.model.Region content) { super(ShoppingContent.this, "PATCH", REST_PATH, content, com.google.api.services.content.model.Region.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.regionId = com.google.api.client.util.Preconditions.checkNotNull(regionId, "Required parameter regionId must be specified."); } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant for which to update region definition. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to update region definition. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant for which to update region definition. */ public Patch setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the region to update. */ @com.google.api.client.util.Key private java.lang.String regionId; /** Required. The id of the region to update. */ public java.lang.String getRegionId() { return regionId; } /** Required. The id of the region to update. */ public Patch setRegionId(java.lang.String regionId) { this.regionId = regionId; return this; } /** Optional. The field mask indicating the fields to update. */ @com.google.api.client.util.Key private String updateMask; /** Optional. The field mask indicating the fields to update. */ public String getUpdateMask() { return updateMask; } /** Optional. The field mask indicating the fields to update. */ public Patch setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Reports collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Reports.List request = content.reports().list(parameters ...)} * </pre> * * @return the resource collection */ public Reports reports() { return new Reports(); } /** * The "reports" collection of methods. */ public class Reports { /** * Retrieves merchant performance mertrics matching the search query and optionally segmented by * selected dimensions. * * Create a request for the method "reports.search". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Search#execute()} method to invoke the remote operation. * * @param merchantId Required. Id of the merchant making the call. Must be a standalone account or an MCA subaccount. * @param content the {@link com.google.api.services.content.model.SearchRequest} * @return the request */ public Search search(java.lang.Long merchantId, com.google.api.services.content.model.SearchRequest content) throws java.io.IOException { Search result = new Search(merchantId, content); initialize(result); return result; } public class Search extends ShoppingContentRequest<com.google.api.services.content.model.SearchResponse> { private static final String REST_PATH = "{merchantId}/reports/search"; /** * Retrieves merchant performance mertrics matching the search query and optionally segmented by * selected dimensions. * * Create a request for the method "reports.search". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Search#execute()} method to invoke the remote operation. <p> {@link * Search#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. Id of the merchant making the call. Must be a standalone account or an MCA subaccount. * @param content the {@link com.google.api.services.content.model.SearchRequest} * @since 1.13 */ protected Search(java.lang.Long merchantId, com.google.api.services.content.model.SearchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.SearchResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Search set$Xgafv(java.lang.String $Xgafv) { return (Search) super.set$Xgafv($Xgafv); } @Override public Search setAccessToken(java.lang.String accessToken) { return (Search) super.setAccessToken(accessToken); } @Override public Search setAlt(java.lang.String alt) { return (Search) super.setAlt(alt); } @Override public Search setCallback(java.lang.String callback) { return (Search) super.setCallback(callback); } @Override public Search setFields(java.lang.String fields) { return (Search) super.setFields(fields); } @Override public Search setKey(java.lang.String key) { return (Search) super.setKey(key); } @Override public Search setOauthToken(java.lang.String oauthToken) { return (Search) super.setOauthToken(oauthToken); } @Override public Search setPrettyPrint(java.lang.Boolean prettyPrint) { return (Search) super.setPrettyPrint(prettyPrint); } @Override public Search setQuotaUser(java.lang.String quotaUser) { return (Search) super.setQuotaUser(quotaUser); } @Override public Search setUploadType(java.lang.String uploadType) { return (Search) super.setUploadType(uploadType); } @Override public Search setUploadProtocol(java.lang.String uploadProtocol) { return (Search) super.setUploadProtocol(uploadProtocol); } /** * Required. Id of the merchant making the call. Must be a standalone account or an MCA * subaccount. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. Id of the merchant making the call. Must be a standalone account or an MCA subaccount. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. Id of the merchant making the call. Must be a standalone account or an MCA * subaccount. */ public Search setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } @Override public Search set(String parameterName, Object value) { return (Search) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Repricingrules collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Repricingrules.List request = content.repricingrules().list(parameters ...)} * </pre> * * @return the resource collection */ public Repricingrules repricingrules() { return new Repricingrules(); } /** * The "repricingrules" collection of methods. */ public class Repricingrules { /** * Creates a repricing rule for your Merchant Center account. * * Create a request for the method "repricingrules.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param content the {@link com.google.api.services.content.model.RepricingRule} * @return the request */ public Create create(java.lang.Long merchantId, com.google.api.services.content.model.RepricingRule content) throws java.io.IOException { Create result = new Create(merchantId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.RepricingRule> { private static final String REST_PATH = "{merchantId}/repricingrules"; /** * Creates a repricing rule for your Merchant Center account. * * Create a request for the method "repricingrules.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param content the {@link com.google.api.services.content.model.RepricingRule} * @since 1.13 */ protected Create(java.lang.Long merchantId, com.google.api.services.content.model.RepricingRule content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.RepricingRule.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant who owns the repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant who owns the repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant who owns the repricing rule. */ public Create setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the rule to create. */ @com.google.api.client.util.Key private java.lang.String ruleId; /** Required. The id of the rule to create. */ public java.lang.String getRuleId() { return ruleId; } /** Required. The id of the rule to create. */ public Create setRuleId(java.lang.String ruleId) { this.ruleId = ruleId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a repricing rule in your Merchant Center account. * * Create a request for the method "repricingrules.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param ruleId Required. The id of the rule to Delete. * @return the request */ public Delete delete(java.lang.Long merchantId, java.lang.String ruleId) throws java.io.IOException { Delete result = new Delete(merchantId, ruleId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/repricingrules/{ruleId}"; /** * Deletes a repricing rule in your Merchant Center account. * * Create a request for the method "repricingrules.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param ruleId Required. The id of the rule to Delete. * @since 1.13 */ protected Delete(java.lang.Long merchantId, java.lang.String ruleId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.ruleId = com.google.api.client.util.Preconditions.checkNotNull(ruleId, "Required parameter ruleId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant who owns the repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant who owns the repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant who owns the repricing rule. */ public Delete setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the rule to Delete. */ @com.google.api.client.util.Key private java.lang.String ruleId; /** Required. The id of the rule to Delete. */ public java.lang.String getRuleId() { return ruleId; } /** Required. The id of the rule to Delete. */ public Delete setRuleId(java.lang.String ruleId) { this.ruleId = ruleId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Retrieves a repricing rule from your Merchant Center account. * * Create a request for the method "repricingrules.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param ruleId Required. The id of the rule to retrieve. * @return the request */ public Get get(java.lang.Long merchantId, java.lang.String ruleId) throws java.io.IOException { Get result = new Get(merchantId, ruleId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.RepricingRule> { private static final String REST_PATH = "{merchantId}/repricingrules/{ruleId}"; /** * Retrieves a repricing rule from your Merchant Center account. * * Create a request for the method "repricingrules.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param ruleId Required. The id of the rule to retrieve. * @since 1.13 */ protected Get(java.lang.Long merchantId, java.lang.String ruleId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.RepricingRule.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.ruleId = com.google.api.client.util.Preconditions.checkNotNull(ruleId, "Required parameter ruleId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant who owns the repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant who owns the repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant who owns the repricing rule. */ public Get setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the rule to retrieve. */ @com.google.api.client.util.Key private java.lang.String ruleId; /** Required. The id of the rule to retrieve. */ public java.lang.String getRuleId() { return ruleId; } /** Required. The id of the rule to retrieve. */ public Get setRuleId(java.lang.String ruleId) { this.ruleId = ruleId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists the repricing rules in your Merchant Center account. * * Create a request for the method "repricingrules.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @return the request */ public List list(java.lang.Long merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListRepricingRulesResponse> { private static final String REST_PATH = "{merchantId}/repricingrules"; /** * Lists the repricing rules in your Merchant Center account. * * Create a request for the method "repricingrules.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @since 1.13 */ protected List(java.lang.Long merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListRepricingRulesResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant who owns the repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant who owns the repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant who owns the repricing rule. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** * [CLDR country code](http://www.unicode.org/repos/cldr/tags/latest/common/main/en.xml) (e.g. * "US"), used as a filter on repricing rules. */ @com.google.api.client.util.Key private java.lang.String countryCode; /**[ CLDR country code](http://www.unicode.org/repos/cldr/tags/latest/common/main/en.xml) (e.g. "US"), [ used as a filter on repricing rules. [ */ public java.lang.String getCountryCode() { return countryCode; } /** * [CLDR country code](http://www.unicode.org/repos/cldr/tags/latest/common/main/en.xml) (e.g. * "US"), used as a filter on repricing rules. */ public List setCountryCode(java.lang.String countryCode) { this.countryCode = countryCode; return this; } /** * The two-letter ISO 639-1 language code associated with the repricing rule, used as a * filter. */ @com.google.api.client.util.Key private java.lang.String languageCode; /** The two-letter ISO 639-1 language code associated with the repricing rule, used as a filter. */ public java.lang.String getLanguageCode() { return languageCode; } /** * The two-letter ISO 639-1 language code associated with the repricing rule, used as a * filter. */ public List setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } /** * The maximum number of repricing rules to return. The service may return fewer than this * value. If unspecified, at most 50 rules will be returned. The maximum value is 1000; values * above 1000 will be coerced to 1000. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The maximum number of repricing rules to return. The service may return fewer than this value. If unspecified, at most 50 rules will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. */ public java.lang.Integer getPageSize() { return pageSize; } /** * The maximum number of repricing rules to return. The service may return fewer than this * value. If unspecified, at most 50 rules will be returned. The maximum value is 1000; values * above 1000 will be coerced to 1000. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A page token, received from a previous `ListRepricingRules` call. Provide this to retrieve * the subsequent page. When paginating, all other parameters provided to `ListRepricingRules` * must match the call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A page token, received from a previous `ListRepricingRules` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListRepricingRules` must match the call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * A page token, received from a previous `ListRepricingRules` call. Provide this to retrieve * the subsequent page. When paginating, all other parameters provided to `ListRepricingRules` * must match the call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a repricing rule in your Merchant Center account. All mutable fields will be overwritten * in each update request. In each update, you must provide all required mutable fields, or an error * will be thrown. If you do not provide an optional field in the update request, if that field * currently exists, it will be deleted from the rule. * * Create a request for the method "repricingrules.patch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param ruleId Required. The id of the rule to update. * @param content the {@link com.google.api.services.content.model.RepricingRule} * @return the request */ public Patch patch(java.lang.Long merchantId, java.lang.String ruleId, com.google.api.services.content.model.RepricingRule content) throws java.io.IOException { Patch result = new Patch(merchantId, ruleId, content); initialize(result); return result; } public class Patch extends ShoppingContentRequest<com.google.api.services.content.model.RepricingRule> { private static final String REST_PATH = "{merchantId}/repricingrules/{ruleId}"; /** * Updates a repricing rule in your Merchant Center account. All mutable fields will be * overwritten in each update request. In each update, you must provide all required mutable * fields, or an error will be thrown. If you do not provide an optional field in the update * request, if that field currently exists, it will be deleted from the rule. * * Create a request for the method "repricingrules.patch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant who owns the repricing rule. * @param ruleId Required. The id of the rule to update. * @param content the {@link com.google.api.services.content.model.RepricingRule} * @since 1.13 */ protected Patch(java.lang.Long merchantId, java.lang.String ruleId, com.google.api.services.content.model.RepricingRule content) { super(ShoppingContent.this, "PATCH", REST_PATH, content, com.google.api.services.content.model.RepricingRule.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.ruleId = com.google.api.client.util.Preconditions.checkNotNull(ruleId, "Required parameter ruleId must be specified."); } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** Required. The id of the merchant who owns the repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant who owns the repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. The id of the merchant who owns the repricing rule. */ public Patch setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the rule to update. */ @com.google.api.client.util.Key private java.lang.String ruleId; /** Required. The id of the rule to update. */ public java.lang.String getRuleId() { return ruleId; } /** Required. The id of the rule to update. */ public Patch setRuleId(java.lang.String ruleId) { this.ruleId = ruleId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * An accessor for creating requests from the Repricingreports collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Repricingreports.List request = content.repricingreports().list(parameters ...)} * </pre> * * @return the resource collection */ public Repricingreports repricingreports() { return new Repricingreports(); } /** * The "repricingreports" collection of methods. */ public class Repricingreports { /** * Lists the metrics report for a given Repricing rule. * * Create a request for the method "repricingreports.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. Id of the merchant who owns the Repricing rule. * @param ruleId Required. Id of the Repricing rule. * @return the request */ public List list(java.lang.Long merchantId, java.lang.String ruleId) throws java.io.IOException { List result = new List(merchantId, ruleId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListRepricingRuleReportsResponse> { private static final String REST_PATH = "{merchantId}/repricingrules/{ruleId}/repricingreports"; /** * Lists the metrics report for a given Repricing rule. * * Create a request for the method "repricingreports.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. Id of the merchant who owns the Repricing rule. * @param ruleId Required. Id of the Repricing rule. * @since 1.13 */ protected List(java.lang.Long merchantId, java.lang.String ruleId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListRepricingRuleReportsResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.ruleId = com.google.api.client.util.Preconditions.checkNotNull(ruleId, "Required parameter ruleId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** Required. Id of the merchant who owns the Repricing rule. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. Id of the merchant who owns the Repricing rule. */ public java.lang.Long getMerchantId() { return merchantId; } /** Required. Id of the merchant who owns the Repricing rule. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. Id of the Repricing rule. */ @com.google.api.client.util.Key private java.lang.String ruleId; /** Required. Id of the Repricing rule. */ public java.lang.String getRuleId() { return ruleId; } /** Required. Id of the Repricing rule. */ public List setRuleId(java.lang.String ruleId) { this.ruleId = ruleId; return this; } /** * Gets Repricing reports on and before this date in the merchant's timezone. You can only * retrieve data up to 7 days ago (default) or earlier. Format: YYYY-MM-DD. */ @com.google.api.client.util.Key private java.lang.String endDate; /** Gets Repricing reports on and before this date in the merchant's timezone. You can only retrieve data up to 7 days ago (default) or earlier. Format: YYYY-MM-DD. */ public java.lang.String getEndDate() { return endDate; } /** * Gets Repricing reports on and before this date in the merchant's timezone. You can only * retrieve data up to 7 days ago (default) or earlier. Format: YYYY-MM-DD. */ public List setEndDate(java.lang.String endDate) { this.endDate = endDate; return this; } /** * Maximum number of daily reports to return. Each report includes data from a single * 24-hour period. The page size defaults to 50 and values above 1000 are coerced to 1000. * This service may return fewer days than this value, for example, if the time between your * start and end date is less than page size. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Maximum number of daily reports to return. Each report includes data from a single 24-hour period. The page size defaults to 50 and values above 1000 are coerced to 1000. This service may return fewer days than this value, for example, if the time between your start and end date is less than page size. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Maximum number of daily reports to return. Each report includes data from a single * 24-hour period. The page size defaults to 50 and values above 1000 are coerced to 1000. * This service may return fewer days than this value, for example, if the time between your * start and end date is less than page size. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** Token (if provided) to retrieve the subsequent page. All other parameters must match the original call that provided the page token. */ public java.lang.String getPageToken() { return pageToken; } /** * Token (if provided) to retrieve the subsequent page. All other parameters must match the * original call that provided the page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * Gets Repricing reports on and after this date in the merchant's timezone, up to one year * ago. Do not use a start date later than 7 days ago (default). Format: YYYY-MM-DD. */ @com.google.api.client.util.Key private java.lang.String startDate; /** Gets Repricing reports on and after this date in the merchant's timezone, up to one year ago. Do not use a start date later than 7 days ago (default). Format: YYYY-MM-DD. */ public java.lang.String getStartDate() { return startDate; } /** * Gets Repricing reports on and after this date in the merchant's timezone, up to one year * ago. Do not use a start date later than 7 days ago (default). Format: YYYY-MM-DD. */ public List setStartDate(java.lang.String startDate) { this.startDate = startDate; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } } /** * An accessor for creating requests from the Returnaddress collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Returnaddress.List request = content.returnaddress().list(parameters ...)} * </pre> * * @return the resource collection */ public Returnaddress returnaddress() { return new Returnaddress(); } /** * The "returnaddress" collection of methods. */ public class Returnaddress { /** * Batches multiple return address related calls in a single request. * * Create a request for the method "returnaddress.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.ReturnaddressCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.ReturnaddressCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.ReturnaddressCustomBatchResponse> { private static final String REST_PATH = "returnaddress/batch"; /** * Batches multiple return address related calls in a single request. * * Create a request for the method "returnaddress.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.ReturnaddressCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.ReturnaddressCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ReturnaddressCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Deletes a return address for the given Merchant Center account. * * Create a request for the method "returnaddress.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account from which to delete the given return address. * @param returnAddressId Return address ID generated by Google. * @return the request */ public Delete delete(java.math.BigInteger merchantId, java.lang.String returnAddressId) throws java.io.IOException { Delete result = new Delete(merchantId, returnAddressId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/returnaddress/{returnAddressId}"; /** * Deletes a return address for the given Merchant Center account. * * Create a request for the method "returnaddress.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account from which to delete the given return address. * @param returnAddressId Return address ID generated by Google. * @since 1.13 */ protected Delete(java.math.BigInteger merchantId, java.lang.String returnAddressId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnAddressId = com.google.api.client.util.Preconditions.checkNotNull(returnAddressId, "Required parameter returnAddressId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account from which to delete the given return address. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account from which to delete the given return address. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account from which to delete the given return address. */ public Delete setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** Return address ID generated by Google. */ @com.google.api.client.util.Key private java.lang.String returnAddressId; /** Return address ID generated by Google. */ public java.lang.String getReturnAddressId() { return returnAddressId; } /** Return address ID generated by Google. */ public Delete setReturnAddressId(java.lang.String returnAddressId) { this.returnAddressId = returnAddressId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a return address of the Merchant Center account. * * Create a request for the method "returnaddress.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to get a return address for. * @param returnAddressId Return address ID generated by Google. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String returnAddressId) throws java.io.IOException { Get result = new Get(merchantId, returnAddressId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.ReturnAddress> { private static final String REST_PATH = "{merchantId}/returnaddress/{returnAddressId}"; /** * Gets a return address of the Merchant Center account. * * Create a request for the method "returnaddress.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to get a return address for. * @param returnAddressId Return address ID generated by Google. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String returnAddressId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ReturnAddress.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnAddressId = com.google.api.client.util.Preconditions.checkNotNull(returnAddressId, "Required parameter returnAddressId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to get a return address for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to get a return address for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to get a return address for. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** Return address ID generated by Google. */ @com.google.api.client.util.Key private java.lang.String returnAddressId; /** Return address ID generated by Google. */ public java.lang.String getReturnAddressId() { return returnAddressId; } /** Return address ID generated by Google. */ public Get setReturnAddressId(java.lang.String returnAddressId) { this.returnAddressId = returnAddressId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Inserts a return address for the Merchant Center account. * * Create a request for the method "returnaddress.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to insert a return address for. * @param content the {@link com.google.api.services.content.model.ReturnAddress} * @return the request */ public Insert insert(java.math.BigInteger merchantId, com.google.api.services.content.model.ReturnAddress content) throws java.io.IOException { Insert result = new Insert(merchantId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.ReturnAddress> { private static final String REST_PATH = "{merchantId}/returnaddress"; /** * Inserts a return address for the Merchant Center account. * * Create a request for the method "returnaddress.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to insert a return address for. * @param content the {@link com.google.api.services.content.model.ReturnAddress} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, com.google.api.services.content.model.ReturnAddress content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ReturnAddress.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to insert a return address for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to insert a return address for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to insert a return address for. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Lists the return addresses of the Merchant Center account. * * Create a request for the method "returnaddress.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to list return addresses for. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ReturnaddressListResponse> { private static final String REST_PATH = "{merchantId}/returnaddress"; /** * Lists the return addresses of the Merchant Center account. * * Create a request for the method "returnaddress.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to list return addresses for. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ReturnaddressListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to list return addresses for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to list return addresses for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to list return addresses for. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** * List only return addresses applicable to the given country of sale. When omitted, all * return addresses are listed. */ @com.google.api.client.util.Key private java.lang.String country; /** List only return addresses applicable to the given country of sale. When omitted, all return addresses are listed. */ public java.lang.String getCountry() { return country; } /** * List only return addresses applicable to the given country of sale. When omitted, all * return addresses are listed. */ public List setCountry(java.lang.String country) { this.country = country; return this; } /** The maximum number of addresses in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of addresses in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of addresses in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Returnpolicy collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Returnpolicy.List request = content.returnpolicy().list(parameters ...)} * </pre> * * @return the resource collection */ public Returnpolicy returnpolicy() { return new Returnpolicy(); } /** * The "returnpolicy" collection of methods. */ public class Returnpolicy { /** * Batches multiple return policy related calls in a single request. * * Create a request for the method "returnpolicy.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.ReturnpolicyCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.ReturnpolicyCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.ReturnpolicyCustomBatchResponse> { private static final String REST_PATH = "returnpolicy/batch"; /** * Batches multiple return policy related calls in a single request. * * Create a request for the method "returnpolicy.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.ReturnpolicyCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.ReturnpolicyCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ReturnpolicyCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Deletes a return policy for the given Merchant Center account. * * Create a request for the method "returnpolicy.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account from which to delete the given return policy. * @param returnPolicyId Return policy ID generated by Google. * @return the request */ public Delete delete(java.math.BigInteger merchantId, java.lang.String returnPolicyId) throws java.io.IOException { Delete result = new Delete(merchantId, returnPolicyId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/returnpolicy/{returnPolicyId}"; /** * Deletes a return policy for the given Merchant Center account. * * Create a request for the method "returnpolicy.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account from which to delete the given return policy. * @param returnPolicyId Return policy ID generated by Google. * @since 1.13 */ protected Delete(java.math.BigInteger merchantId, java.lang.String returnPolicyId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnPolicyId = com.google.api.client.util.Preconditions.checkNotNull(returnPolicyId, "Required parameter returnPolicyId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account from which to delete the given return policy. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account from which to delete the given return policy. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account from which to delete the given return policy. */ public Delete setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** Return policy ID generated by Google. */ @com.google.api.client.util.Key private java.lang.String returnPolicyId; /** Return policy ID generated by Google. */ public java.lang.String getReturnPolicyId() { return returnPolicyId; } /** Return policy ID generated by Google. */ public Delete setReturnPolicyId(java.lang.String returnPolicyId) { this.returnPolicyId = returnPolicyId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a return policy of the Merchant Center account. * * Create a request for the method "returnpolicy.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to get a return policy for. * @param returnPolicyId Return policy ID generated by Google. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String returnPolicyId) throws java.io.IOException { Get result = new Get(merchantId, returnPolicyId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.ReturnPolicy> { private static final String REST_PATH = "{merchantId}/returnpolicy/{returnPolicyId}"; /** * Gets a return policy of the Merchant Center account. * * Create a request for the method "returnpolicy.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to get a return policy for. * @param returnPolicyId Return policy ID generated by Google. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String returnPolicyId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ReturnPolicy.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnPolicyId = com.google.api.client.util.Preconditions.checkNotNull(returnPolicyId, "Required parameter returnPolicyId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to get a return policy for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to get a return policy for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to get a return policy for. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** Return policy ID generated by Google. */ @com.google.api.client.util.Key private java.lang.String returnPolicyId; /** Return policy ID generated by Google. */ public java.lang.String getReturnPolicyId() { return returnPolicyId; } /** Return policy ID generated by Google. */ public Get setReturnPolicyId(java.lang.String returnPolicyId) { this.returnPolicyId = returnPolicyId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Inserts a return policy for the Merchant Center account. * * Create a request for the method "returnpolicy.insert". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to insert a return policy for. * @param content the {@link com.google.api.services.content.model.ReturnPolicy} * @return the request */ public Insert insert(java.math.BigInteger merchantId, com.google.api.services.content.model.ReturnPolicy content) throws java.io.IOException { Insert result = new Insert(merchantId, content); initialize(result); return result; } public class Insert extends ShoppingContentRequest<com.google.api.services.content.model.ReturnPolicy> { private static final String REST_PATH = "{merchantId}/returnpolicy"; /** * Inserts a return policy for the Merchant Center account. * * Create a request for the method "returnpolicy.insert". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Insert#execute()} method to invoke the remote operation. <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to insert a return policy for. * @param content the {@link com.google.api.services.content.model.ReturnPolicy} * @since 1.13 */ protected Insert(java.math.BigInteger merchantId, com.google.api.services.content.model.ReturnPolicy content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ReturnPolicy.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to insert a return policy for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to insert a return policy for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to insert a return policy for. */ public Insert setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Lists the return policies of the Merchant Center account. * * Create a request for the method "returnpolicy.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to list return policies for. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ReturnpolicyListResponse> { private static final String REST_PATH = "{merchantId}/returnpolicy"; /** * Lists the return policies of the Merchant Center account. * * Create a request for the method "returnpolicy.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to list return policies for. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ReturnpolicyListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to list return policies for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to list return policies for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to list return policies for. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Returnpolicyonline collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Returnpolicyonline.List request = content.returnpolicyonline().list(parameters ...)} * </pre> * * @return the resource collection */ public Returnpolicyonline returnpolicyonline() { return new Returnpolicyonline(); } /** * The "returnpolicyonline" collection of methods. */ public class Returnpolicyonline { /** * Creates a new return policy. * * Create a request for the method "returnpolicyonline.create". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param content the {@link com.google.api.services.content.model.ReturnPolicyOnline} * @return the request */ public Create create(java.lang.Long merchantId, com.google.api.services.content.model.ReturnPolicyOnline content) throws java.io.IOException { Create result = new Create(merchantId, content); initialize(result); return result; } public class Create extends ShoppingContentRequest<com.google.api.services.content.model.ReturnPolicyOnline> { private static final String REST_PATH = "{merchantId}/returnpolicyonline"; /** * Creates a new return policy. * * Create a request for the method "returnpolicyonline.create". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param content the {@link com.google.api.services.content.model.ReturnPolicyOnline} * @since 1.13 */ protected Create(java.lang.Long merchantId, com.google.api.services.content.model.ReturnPolicyOnline content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ReturnPolicyOnline.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to retrieve the return policy online object. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ public Create setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes an existing return policy. * * Create a request for the method "returnpolicyonline.delete". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param returnPolicyId Required. The id of the return policy to delete. * @return the request */ public Delete delete(java.lang.Long merchantId, java.lang.String returnPolicyId) throws java.io.IOException { Delete result = new Delete(merchantId, returnPolicyId); initialize(result); return result; } public class Delete extends ShoppingContentRequest<Void> { private static final String REST_PATH = "{merchantId}/returnpolicyonline/{returnPolicyId}"; /** * Deletes an existing return policy. * * Create a request for the method "returnpolicyonline.delete". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Delete#execute()} method to invoke the remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param returnPolicyId Required. The id of the return policy to delete. * @since 1.13 */ protected Delete(java.lang.Long merchantId, java.lang.String returnPolicyId) { super(ShoppingContent.this, "DELETE", REST_PATH, null, Void.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnPolicyId = com.google.api.client.util.Preconditions.checkNotNull(returnPolicyId, "Required parameter returnPolicyId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to retrieve the return policy online object. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ public Delete setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the return policy to delete. */ @com.google.api.client.util.Key private java.lang.String returnPolicyId; /** Required. The id of the return policy to delete. */ public java.lang.String getReturnPolicyId() { return returnPolicyId; } /** Required. The id of the return policy to delete. */ public Delete setReturnPolicyId(java.lang.String returnPolicyId) { this.returnPolicyId = returnPolicyId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets an existing return policy. * * Create a request for the method "returnpolicyonline.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param returnPolicyId Required. The id of the return policy to retrieve. * @return the request */ public Get get(java.lang.Long merchantId, java.lang.String returnPolicyId) throws java.io.IOException { Get result = new Get(merchantId, returnPolicyId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.ReturnPolicyOnline> { private static final String REST_PATH = "{merchantId}/returnpolicyonline/{returnPolicyId}"; /** * Gets an existing return policy. * * Create a request for the method "returnpolicyonline.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param returnPolicyId Required. The id of the return policy to retrieve. * @since 1.13 */ protected Get(java.lang.Long merchantId, java.lang.String returnPolicyId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ReturnPolicyOnline.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnPolicyId = com.google.api.client.util.Preconditions.checkNotNull(returnPolicyId, "Required parameter returnPolicyId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to retrieve the return policy online object. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ public Get setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the return policy to retrieve. */ @com.google.api.client.util.Key private java.lang.String returnPolicyId; /** Required. The id of the return policy to retrieve. */ public java.lang.String getReturnPolicyId() { return returnPolicyId; } /** Required. The id of the return policy to retrieve. */ public Get setReturnPolicyId(java.lang.String returnPolicyId) { this.returnPolicyId = returnPolicyId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists all existing return policies. * * Create a request for the method "returnpolicyonline.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @return the request */ public List list(java.lang.Long merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ListReturnPolicyOnlineResponse> { private static final String REST_PATH = "{merchantId}/returnpolicyonline"; /** * Lists all existing return policies. * * Create a request for the method "returnpolicyonline.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @since 1.13 */ protected List(java.lang.Long merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ListReturnPolicyOnlineResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to retrieve the return policy online object. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ public List setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates an existing return policy. * * Create a request for the method "returnpolicyonline.patch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param returnPolicyId Required. The id of the return policy to update. * @param content the {@link com.google.api.services.content.model.ReturnPolicyOnline} * @return the request */ public Patch patch(java.lang.Long merchantId, java.lang.String returnPolicyId, com.google.api.services.content.model.ReturnPolicyOnline content) throws java.io.IOException { Patch result = new Patch(merchantId, returnPolicyId, content); initialize(result); return result; } public class Patch extends ShoppingContentRequest<com.google.api.services.content.model.ReturnPolicyOnline> { private static final String REST_PATH = "{merchantId}/returnpolicyonline/{returnPolicyId}"; /** * Updates an existing return policy. * * Create a request for the method "returnpolicyonline.patch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Patch#execute()} method to invoke the remote operation. <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId Required. The id of the merchant for which to retrieve the return policy online object. * @param returnPolicyId Required. The id of the return policy to update. * @param content the {@link com.google.api.services.content.model.ReturnPolicyOnline} * @since 1.13 */ protected Patch(java.lang.Long merchantId, java.lang.String returnPolicyId, com.google.api.services.content.model.ReturnPolicyOnline content) { super(ShoppingContent.this, "PATCH", REST_PATH, content, com.google.api.services.content.model.ReturnPolicyOnline.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.returnPolicyId = com.google.api.client.util.Preconditions.checkNotNull(returnPolicyId, "Required parameter returnPolicyId must be specified."); } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ @com.google.api.client.util.Key private java.lang.Long merchantId; /** Required. The id of the merchant for which to retrieve the return policy online object. */ public java.lang.Long getMerchantId() { return merchantId; } /** * Required. The id of the merchant for which to retrieve the return policy online object. */ public Patch setMerchantId(java.lang.Long merchantId) { this.merchantId = merchantId; return this; } /** Required. The id of the return policy to update. */ @com.google.api.client.util.Key private java.lang.String returnPolicyId; /** Required. The id of the return policy to update. */ public java.lang.String getReturnPolicyId() { return returnPolicyId; } /** Required. The id of the return policy to update. */ public Patch setReturnPolicyId(java.lang.String returnPolicyId) { this.returnPolicyId = returnPolicyId; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Settlementreports collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Settlementreports.List request = content.settlementreports().list(parameters ...)} * </pre> * * @return the resource collection */ public Settlementreports settlementreports() { return new Settlementreports(); } /** * The "settlementreports" collection of methods. */ public class Settlementreports { /** * Retrieves a settlement report from your Merchant Center account. * * Create a request for the method "settlementreports.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account of the settlement report. * @param settlementId The Google-provided ID of the settlement. * @return the request */ public Get get(java.math.BigInteger merchantId, java.lang.String settlementId) throws java.io.IOException { Get result = new Get(merchantId, settlementId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.SettlementReport> { private static final String REST_PATH = "{merchantId}/settlementreports/{settlementId}"; /** * Retrieves a settlement report from your Merchant Center account. * * Create a request for the method "settlementreports.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account of the settlement report. * @param settlementId The Google-provided ID of the settlement. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.lang.String settlementId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.SettlementReport.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.settlementId = com.google.api.client.util.Preconditions.checkNotNull(settlementId, "Required parameter settlementId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account of the settlement report. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account of the settlement report. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account of the settlement report. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The Google-provided ID of the settlement. */ @com.google.api.client.util.Key private java.lang.String settlementId; /** The Google-provided ID of the settlement. */ public java.lang.String getSettlementId() { return settlementId; } /** The Google-provided ID of the settlement. */ public Get setSettlementId(java.lang.String settlementId) { this.settlementId = settlementId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves a list of settlement reports from your Merchant Center account. * * Create a request for the method "settlementreports.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to list settlements for. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.SettlementreportsListResponse> { private static final String REST_PATH = "{merchantId}/settlementreports"; /** * Retrieves a list of settlement reports from your Merchant Center account. * * Create a request for the method "settlementreports.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to list settlements for. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.SettlementreportsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to list settlements for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to list settlements for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to list settlements for. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** * The maximum number of settlements to return in the response, used for paging. The default * value is 200 returns per page, and the maximum allowed value is 5000 returns per page. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of settlements to return in the response, used for paging. The default value is 200 returns per page, and the maximum allowed value is 5000 returns per page. */ public java.lang.Long getMaxResults() { return maxResults; } /** * The maximum number of settlements to return in the response, used for paging. The default * value is 200 returns per page, and the maximum allowed value is 5000 returns per page. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * Obtains settlements which have transactions before this date (inclusively), in ISO 8601 * format. */ @com.google.api.client.util.Key private java.lang.String transferEndDate; /** Obtains settlements which have transactions before this date (inclusively), in ISO 8601 format. */ public java.lang.String getTransferEndDate() { return transferEndDate; } /** * Obtains settlements which have transactions before this date (inclusively), in ISO 8601 * format. */ public List setTransferEndDate(java.lang.String transferEndDate) { this.transferEndDate = transferEndDate; return this; } /** * Obtains settlements which have transactions after this date (inclusively), in ISO 8601 * format. */ @com.google.api.client.util.Key private java.lang.String transferStartDate; /** Obtains settlements which have transactions after this date (inclusively), in ISO 8601 format. */ public java.lang.String getTransferStartDate() { return transferStartDate; } /** * Obtains settlements which have transactions after this date (inclusively), in ISO 8601 * format. */ public List setTransferStartDate(java.lang.String transferStartDate) { this.transferStartDate = transferStartDate; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Settlementtransactions collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Settlementtransactions.List request = content.settlementtransactions().list(parameters ...)} * </pre> * * @return the resource collection */ public Settlementtransactions settlementtransactions() { return new Settlementtransactions(); } /** * The "settlementtransactions" collection of methods. */ public class Settlementtransactions { /** * Retrieves a list of transactions for the settlement. * * Create a request for the method "settlementtransactions.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The Merchant Center account to list transactions for. * @param settlementId The Google-provided ID of the settlement. * @return the request */ public List list(java.math.BigInteger merchantId, java.lang.String settlementId) throws java.io.IOException { List result = new List(merchantId, settlementId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.SettlementtransactionsListResponse> { private static final String REST_PATH = "{merchantId}/settlementreports/{settlementId}/transactions"; /** * Retrieves a list of transactions for the settlement. * * Create a request for the method "settlementtransactions.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The Merchant Center account to list transactions for. * @param settlementId The Google-provided ID of the settlement. * @since 1.13 */ protected List(java.math.BigInteger merchantId, java.lang.String settlementId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.SettlementtransactionsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.settlementId = com.google.api.client.util.Preconditions.checkNotNull(settlementId, "Required parameter settlementId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The Merchant Center account to list transactions for. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The Merchant Center account to list transactions for. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The Merchant Center account to list transactions for. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The Google-provided ID of the settlement. */ @com.google.api.client.util.Key private java.lang.String settlementId; /** The Google-provided ID of the settlement. */ public java.lang.String getSettlementId() { return settlementId; } /** The Google-provided ID of the settlement. */ public List setSettlementId(java.lang.String settlementId) { this.settlementId = settlementId; return this; } /** * The maximum number of transactions to return in the response, used for paging. The default * value is 200 transactions per page, and the maximum allowed value is 5000 transactions per * page. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of transactions to return in the response, used for paging. The default value is 200 transactions per page, and the maximum allowed value is 5000 transactions per page. */ public java.lang.Long getMaxResults() { return maxResults; } /** * The maximum number of transactions to return in the response, used for paging. The default * value is 200 transactions per page, and the maximum allowed value is 5000 transactions per * page. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** The list of transactions to return. If not set, all transactions will be returned. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> transactionIds; /** The list of transactions to return. If not set, all transactions will be returned. */ public java.util.List<java.lang.String> getTransactionIds() { return transactionIds; } /** The list of transactions to return. If not set, all transactions will be returned. */ public List setTransactionIds(java.util.List<java.lang.String> transactionIds) { this.transactionIds = transactionIds; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Shippingsettings collection. * * <p>The typical use is:</p> * <pre> * {@code ShoppingContent content = new ShoppingContent(...);} * {@code ShoppingContent.Shippingsettings.List request = content.shippingsettings().list(parameters ...)} * </pre> * * @return the resource collection */ public Shippingsettings shippingsettings() { return new Shippingsettings(); } /** * The "shippingsettings" collection of methods. */ public class Shippingsettings { /** * Retrieves and updates the shipping settings of multiple accounts in a single request. * * Create a request for the method "shippingsettings.custombatch". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.content.model.ShippingsettingsCustomBatchRequest} * @return the request */ public Custombatch custombatch(com.google.api.services.content.model.ShippingsettingsCustomBatchRequest content) throws java.io.IOException { Custombatch result = new Custombatch(content); initialize(result); return result; } public class Custombatch extends ShoppingContentRequest<com.google.api.services.content.model.ShippingsettingsCustomBatchResponse> { private static final String REST_PATH = "shippingsettings/batch"; /** * Retrieves and updates the shipping settings of multiple accounts in a single request. * * Create a request for the method "shippingsettings.custombatch". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Custombatch#execute()} method to invoke the remote operation. <p> * {@link * Custombatch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.content.model.ShippingsettingsCustomBatchRequest} * @since 1.13 */ protected Custombatch(com.google.api.services.content.model.ShippingsettingsCustomBatchRequest content) { super(ShoppingContent.this, "POST", REST_PATH, content, com.google.api.services.content.model.ShippingsettingsCustomBatchResponse.class); } @Override public Custombatch set$Xgafv(java.lang.String $Xgafv) { return (Custombatch) super.set$Xgafv($Xgafv); } @Override public Custombatch setAccessToken(java.lang.String accessToken) { return (Custombatch) super.setAccessToken(accessToken); } @Override public Custombatch setAlt(java.lang.String alt) { return (Custombatch) super.setAlt(alt); } @Override public Custombatch setCallback(java.lang.String callback) { return (Custombatch) super.setCallback(callback); } @Override public Custombatch setFields(java.lang.String fields) { return (Custombatch) super.setFields(fields); } @Override public Custombatch setKey(java.lang.String key) { return (Custombatch) super.setKey(key); } @Override public Custombatch setOauthToken(java.lang.String oauthToken) { return (Custombatch) super.setOauthToken(oauthToken); } @Override public Custombatch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Custombatch) super.setPrettyPrint(prettyPrint); } @Override public Custombatch setQuotaUser(java.lang.String quotaUser) { return (Custombatch) super.setQuotaUser(quotaUser); } @Override public Custombatch setUploadType(java.lang.String uploadType) { return (Custombatch) super.setUploadType(uploadType); } @Override public Custombatch setUploadProtocol(java.lang.String uploadProtocol) { return (Custombatch) super.setUploadProtocol(uploadProtocol); } @Override public Custombatch set(String parameterName, Object value) { return (Custombatch) super.set(parameterName, value); } } /** * Retrieves the shipping settings of the account. * * Create a request for the method "shippingsettings.get". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update shipping settings. * @return the request */ public Get get(java.math.BigInteger merchantId, java.math.BigInteger accountId) throws java.io.IOException { Get result = new Get(merchantId, accountId); initialize(result); return result; } public class Get extends ShoppingContentRequest<com.google.api.services.content.model.ShippingSettings> { private static final String REST_PATH = "{merchantId}/shippingsettings/{accountId}"; /** * Retrieves the shipping settings of the account. * * Create a request for the method "shippingsettings.get". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update shipping settings. * @since 1.13 */ protected Get(java.math.BigInteger merchantId, java.math.BigInteger accountId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ShippingSettings.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Get setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to get/update shipping settings. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to get/update shipping settings. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to get/update shipping settings. */ public Get setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Retrieves supported carriers and carrier services for an account. * * Create a request for the method "shippingsettings.getsupportedcarriers". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Getsupportedcarriers#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account for which to retrieve the supported carriers. * @return the request */ public Getsupportedcarriers getsupportedcarriers(java.math.BigInteger merchantId) throws java.io.IOException { Getsupportedcarriers result = new Getsupportedcarriers(merchantId); initialize(result); return result; } public class Getsupportedcarriers extends ShoppingContentRequest<com.google.api.services.content.model.ShippingsettingsGetSupportedCarriersResponse> { private static final String REST_PATH = "{merchantId}/supportedCarriers"; /** * Retrieves supported carriers and carrier services for an account. * * Create a request for the method "shippingsettings.getsupportedcarriers". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Getsupportedcarriers#execute()} method to invoke the remote * operation. <p> {@link Getsupportedcarriers#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account for which to retrieve the supported carriers. * @since 1.13 */ protected Getsupportedcarriers(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ShippingsettingsGetSupportedCarriersResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Getsupportedcarriers set$Xgafv(java.lang.String $Xgafv) { return (Getsupportedcarriers) super.set$Xgafv($Xgafv); } @Override public Getsupportedcarriers setAccessToken(java.lang.String accessToken) { return (Getsupportedcarriers) super.setAccessToken(accessToken); } @Override public Getsupportedcarriers setAlt(java.lang.String alt) { return (Getsupportedcarriers) super.setAlt(alt); } @Override public Getsupportedcarriers setCallback(java.lang.String callback) { return (Getsupportedcarriers) super.setCallback(callback); } @Override public Getsupportedcarriers setFields(java.lang.String fields) { return (Getsupportedcarriers) super.setFields(fields); } @Override public Getsupportedcarriers setKey(java.lang.String key) { return (Getsupportedcarriers) super.setKey(key); } @Override public Getsupportedcarriers setOauthToken(java.lang.String oauthToken) { return (Getsupportedcarriers) super.setOauthToken(oauthToken); } @Override public Getsupportedcarriers setPrettyPrint(java.lang.Boolean prettyPrint) { return (Getsupportedcarriers) super.setPrettyPrint(prettyPrint); } @Override public Getsupportedcarriers setQuotaUser(java.lang.String quotaUser) { return (Getsupportedcarriers) super.setQuotaUser(quotaUser); } @Override public Getsupportedcarriers setUploadType(java.lang.String uploadType) { return (Getsupportedcarriers) super.setUploadType(uploadType); } @Override public Getsupportedcarriers setUploadProtocol(java.lang.String uploadProtocol) { return (Getsupportedcarriers) super.setUploadProtocol(uploadProtocol); } /** The ID of the account for which to retrieve the supported carriers. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account for which to retrieve the supported carriers. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account for which to retrieve the supported carriers. */ public Getsupportedcarriers setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Getsupportedcarriers set(String parameterName, Object value) { return (Getsupportedcarriers) super.set(parameterName, value); } } /** * Retrieves supported holidays for an account. * * Create a request for the method "shippingsettings.getsupportedholidays". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Getsupportedholidays#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account for which to retrieve the supported holidays. * @return the request */ public Getsupportedholidays getsupportedholidays(java.math.BigInteger merchantId) throws java.io.IOException { Getsupportedholidays result = new Getsupportedholidays(merchantId); initialize(result); return result; } public class Getsupportedholidays extends ShoppingContentRequest<com.google.api.services.content.model.ShippingsettingsGetSupportedHolidaysResponse> { private static final String REST_PATH = "{merchantId}/supportedHolidays"; /** * Retrieves supported holidays for an account. * * Create a request for the method "shippingsettings.getsupportedholidays". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Getsupportedholidays#execute()} method to invoke the remote * operation. <p> {@link Getsupportedholidays#initialize(com.google.api.client.googleapis.services * .AbstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param merchantId The ID of the account for which to retrieve the supported holidays. * @since 1.13 */ protected Getsupportedholidays(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ShippingsettingsGetSupportedHolidaysResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Getsupportedholidays set$Xgafv(java.lang.String $Xgafv) { return (Getsupportedholidays) super.set$Xgafv($Xgafv); } @Override public Getsupportedholidays setAccessToken(java.lang.String accessToken) { return (Getsupportedholidays) super.setAccessToken(accessToken); } @Override public Getsupportedholidays setAlt(java.lang.String alt) { return (Getsupportedholidays) super.setAlt(alt); } @Override public Getsupportedholidays setCallback(java.lang.String callback) { return (Getsupportedholidays) super.setCallback(callback); } @Override public Getsupportedholidays setFields(java.lang.String fields) { return (Getsupportedholidays) super.setFields(fields); } @Override public Getsupportedholidays setKey(java.lang.String key) { return (Getsupportedholidays) super.setKey(key); } @Override public Getsupportedholidays setOauthToken(java.lang.String oauthToken) { return (Getsupportedholidays) super.setOauthToken(oauthToken); } @Override public Getsupportedholidays setPrettyPrint(java.lang.Boolean prettyPrint) { return (Getsupportedholidays) super.setPrettyPrint(prettyPrint); } @Override public Getsupportedholidays setQuotaUser(java.lang.String quotaUser) { return (Getsupportedholidays) super.setQuotaUser(quotaUser); } @Override public Getsupportedholidays setUploadType(java.lang.String uploadType) { return (Getsupportedholidays) super.setUploadType(uploadType); } @Override public Getsupportedholidays setUploadProtocol(java.lang.String uploadProtocol) { return (Getsupportedholidays) super.setUploadProtocol(uploadProtocol); } /** The ID of the account for which to retrieve the supported holidays. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account for which to retrieve the supported holidays. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account for which to retrieve the supported holidays. */ public Getsupportedholidays setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Getsupportedholidays set(String parameterName, Object value) { return (Getsupportedholidays) super.set(parameterName, value); } } /** * Retrieves supported pickup services for an account. * * Create a request for the method "shippingsettings.getsupportedpickupservices". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Getsupportedpickupservices#execute()} method to invoke the remote * operation. * * @param merchantId The ID of the account for which to retrieve the supported pickup services. * @return the request */ public Getsupportedpickupservices getsupportedpickupservices(java.math.BigInteger merchantId) throws java.io.IOException { Getsupportedpickupservices result = new Getsupportedpickupservices(merchantId); initialize(result); return result; } public class Getsupportedpickupservices extends ShoppingContentRequest<com.google.api.services.content.model.ShippingsettingsGetSupportedPickupServicesResponse> { private static final String REST_PATH = "{merchantId}/supportedPickupServices"; /** * Retrieves supported pickup services for an account. * * Create a request for the method "shippingsettings.getsupportedpickupservices". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Getsupportedpickupservices#execute()} method to invoke the remote * operation. <p> {@link Getsupportedpickupservices#initialize(com.google.api.client.googleapis.se * rvices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately * after invoking the constructor. </p> * * @param merchantId The ID of the account for which to retrieve the supported pickup services. * @since 1.13 */ protected Getsupportedpickupservices(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ShippingsettingsGetSupportedPickupServicesResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Getsupportedpickupservices set$Xgafv(java.lang.String $Xgafv) { return (Getsupportedpickupservices) super.set$Xgafv($Xgafv); } @Override public Getsupportedpickupservices setAccessToken(java.lang.String accessToken) { return (Getsupportedpickupservices) super.setAccessToken(accessToken); } @Override public Getsupportedpickupservices setAlt(java.lang.String alt) { return (Getsupportedpickupservices) super.setAlt(alt); } @Override public Getsupportedpickupservices setCallback(java.lang.String callback) { return (Getsupportedpickupservices) super.setCallback(callback); } @Override public Getsupportedpickupservices setFields(java.lang.String fields) { return (Getsupportedpickupservices) super.setFields(fields); } @Override public Getsupportedpickupservices setKey(java.lang.String key) { return (Getsupportedpickupservices) super.setKey(key); } @Override public Getsupportedpickupservices setOauthToken(java.lang.String oauthToken) { return (Getsupportedpickupservices) super.setOauthToken(oauthToken); } @Override public Getsupportedpickupservices setPrettyPrint(java.lang.Boolean prettyPrint) { return (Getsupportedpickupservices) super.setPrettyPrint(prettyPrint); } @Override public Getsupportedpickupservices setQuotaUser(java.lang.String quotaUser) { return (Getsupportedpickupservices) super.setQuotaUser(quotaUser); } @Override public Getsupportedpickupservices setUploadType(java.lang.String uploadType) { return (Getsupportedpickupservices) super.setUploadType(uploadType); } @Override public Getsupportedpickupservices setUploadProtocol(java.lang.String uploadProtocol) { return (Getsupportedpickupservices) super.setUploadProtocol(uploadProtocol); } /** The ID of the account for which to retrieve the supported pickup services. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the account for which to retrieve the supported pickup services. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the account for which to retrieve the supported pickup services. */ public Getsupportedpickupservices setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } @Override public Getsupportedpickupservices set(String parameterName, Object value) { return (Getsupportedpickupservices) super.set(parameterName, value); } } /** * Lists the shipping settings of the sub-accounts in your Merchant Center account. * * Create a request for the method "shippingsettings.list". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. This must be a multi-client account. * @return the request */ public List list(java.math.BigInteger merchantId) throws java.io.IOException { List result = new List(merchantId); initialize(result); return result; } public class List extends ShoppingContentRequest<com.google.api.services.content.model.ShippingsettingsListResponse> { private static final String REST_PATH = "{merchantId}/shippingsettings"; /** * Lists the shipping settings of the sub-accounts in your Merchant Center account. * * Create a request for the method "shippingsettings.list". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. This must be a multi-client account. * @since 1.13 */ protected List(java.math.BigInteger merchantId) { super(ShoppingContent.this, "GET", REST_PATH, null, com.google.api.services.content.model.ShippingsettingsListResponse.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The ID of the managing account. This must be a multi-client account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. This must be a multi-client account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** The ID of the managing account. This must be a multi-client account. */ public List setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The maximum number of shipping settings to return in the response, used for paging. */ @com.google.api.client.util.Key private java.lang.Long maxResults; /** The maximum number of shipping settings to return in the response, used for paging. */ public java.lang.Long getMaxResults() { return maxResults; } /** The maximum number of shipping settings to return in the response, used for paging. */ public List setMaxResults(java.lang.Long maxResults) { this.maxResults = maxResults; return this; } /** The token returned by the previous request. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The token returned by the previous request. */ public java.lang.String getPageToken() { return pageToken; } /** The token returned by the previous request. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates the shipping settings of the account. Any fields that are not provided are deleted from * the resource. * * Create a request for the method "shippingsettings.update". * * This request holds the parameters needed by the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update shipping settings. * @param content the {@link com.google.api.services.content.model.ShippingSettings} * @return the request */ public Update update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.ShippingSettings content) throws java.io.IOException { Update result = new Update(merchantId, accountId, content); initialize(result); return result; } public class Update extends ShoppingContentRequest<com.google.api.services.content.model.ShippingSettings> { private static final String REST_PATH = "{merchantId}/shippingsettings/{accountId}"; /** * Updates the shipping settings of the account. Any fields that are not provided are deleted from * the resource. * * Create a request for the method "shippingsettings.update". * * This request holds the parameters needed by the the content server. After setting any optional * parameters, call the {@link Update#execute()} method to invoke the remote operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param merchantId The ID of the managing account. If this parameter is not the same as accountId, then this account * must be a multi-client account and `accountId` must be the ID of a sub-account of this * account. * @param accountId The ID of the account for which to get/update shipping settings. * @param content the {@link com.google.api.services.content.model.ShippingSettings} * @since 1.13 */ protected Update(java.math.BigInteger merchantId, java.math.BigInteger accountId, com.google.api.services.content.model.ShippingSettings content) { super(ShoppingContent.this, "PUT", REST_PATH, content, com.google.api.services.content.model.ShippingSettings.class); this.merchantId = com.google.api.client.util.Preconditions.checkNotNull(merchantId, "Required parameter merchantId must be specified."); this.accountId = com.google.api.client.util.Preconditions.checkNotNull(accountId, "Required parameter accountId must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ @com.google.api.client.util.Key private java.math.BigInteger merchantId; /** The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and `accountId` must be the ID of a sub-account of this account. */ public java.math.BigInteger getMerchantId() { return merchantId; } /** * The ID of the managing account. If this parameter is not the same as accountId, then this * account must be a multi-client account and `accountId` must be the ID of a sub-account of * this account. */ public Update setMerchantId(java.math.BigInteger merchantId) { this.merchantId = merchantId; return this; } /** The ID of the account for which to get/update shipping settings. */ @com.google.api.client.util.Key private java.math.BigInteger accountId; /** The ID of the account for which to get/update shipping settings. */ public java.math.BigInteger getAccountId() { return accountId; } /** The ID of the account for which to get/update shipping settings. */ public Update setAccountId(java.math.BigInteger accountId) { this.accountId = accountId; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * Builder for {@link ShoppingContent}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) { // If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint. // If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS. // Use the regular endpoint for all other cases. String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT"); useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint; if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) { return DEFAULT_MTLS_ROOT_URL; } return DEFAULT_ROOT_URL; } /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, Builder.chooseEndpoint(transport), DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link ShoppingContent}. */ @Override public ShoppingContent build() { return new ShoppingContent(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link ShoppingContentRequestInitializer}. * * @since 1.12 */ public Builder setShoppingContentRequestInitializer( ShoppingContentRequestInitializer shoppingcontentRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(shoppingcontentRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
[ "\"GOOGLE_API_USE_MTLS_ENDPOINT\"" ]
[]
[ "GOOGLE_API_USE_MTLS_ENDPOINT" ]
[]
["GOOGLE_API_USE_MTLS_ENDPOINT"]
java
1
0
third_party/legacy_roslaunch/main.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ # pylint: disable=bare-except,broad-except # pylint: disable=line-too-long import os import logging import socket import sys import traceback from optparse import OptionParser import rosgraph.roslogging import rospkg from rosmaster import DEFAULT_MASTER_PORT from rosmaster.master_api import NUM_WORKERS from third_party.legacy_roslaunch import arg_dump from third_party.legacy_roslaunch import child from third_party.legacy_roslaunch import core from third_party.legacy_roslaunch import node_args from third_party.legacy_roslaunch import param_dump from third_party.legacy_roslaunch import parent from third_party.legacy_roslaunch import rlutil from third_party.legacy_roslaunch.core import RLException from third_party.legacy_roslaunch.nodeprocess import DEFAULT_TIMEOUT_SIGINT, DEFAULT_TIMEOUT_SIGTERM NAME = 'roslaunch' def configure_logging(uuid): """ scripts using roslaunch MUST call configure_logging """ try: logfile_basename = os.path.join( uuid, '%s-%s-%s.log' % (NAME, socket.gethostname(), os.getpid())) # additional: names of python packages we depend on that may also be logging logfile_name = rosgraph.roslogging.configure_logging( NAME, filename=logfile_basename) if logfile_name: print("... logging to %s" % logfile_name) # add logger to internal roslaunch logging infrastructure logger = logging.getLogger('roslaunch') core.add_printlog_handler(logger.info) core.add_printerrlog_handler(logger.error) except: print( "WARNING: unable to configure logging. No log files will be generated", file=sys.stderr) def write_pid_file(options_pid_fn, options_core, port): if options_pid_fn or options_core: # #2987 ros_home = rospkg.get_ros_home() if options_pid_fn: pid_fn = os.path.expanduser(options_pid_fn) if os.path.dirname( pid_fn) == ros_home and not os.path.exists(ros_home): os.makedirs(ros_home) else: # NOTE: this assumption is not 100% valid until work on #3097 is complete if port is None: port = DEFAULT_MASTER_PORT pid_fn = os.path.join(ros_home, 'roscore-%s.pid' % (port)) # #3828 if not os.path.exists(ros_home): os.makedirs(ros_home) with open(pid_fn, "w") as f: f.write(str(os.getpid())) def _get_optparse(): usage = "usage: %prog [options] [package] <filename> [arg_name:=value...]\n" usage += " %prog [options] <filename> [<filename>...] [arg_name:=value...]\n\n" usage += "If <filename> is a single dash ('-'), launch XML is read from standard input." parser = OptionParser(usage=usage, prog=NAME) parser.add_option( "--files", dest="file_list", default=False, action="store_true", help= "Print list files loaded by launch file, including launch file itself") parser.add_option("--args", dest="node_args", default=None, help="Print command-line arguments for node", metavar="NODE_NAME") parser.add_option("--nodes", dest="node_list", default=False, action="store_true", help="Print list of node names in launch file") parser.add_option("--find-node", dest="find_node", default=None, help="Find launch file that node is defined in", metavar="NODE_NAME") parser.add_option("-c", "--child", dest="child_name", default=None, help="Run as child service 'NAME'. Required with -u", metavar="NAME") parser.add_option("--local", dest="local_only", default=False, action="store_true", help="Do not launch remote nodes") # #2370 parser.add_option("--screen", dest="force_screen", default=False, action="store_true", help="Force output of all local nodes to screen") parser.add_option("--required", dest="force_required", default=False, action="store_true", help="Force all nodes to be required") parser.add_option("--log", dest="force_log", default=False, action="store_true", help="Force output of all local nodes to log") parser.add_option("-u", "--server_uri", dest="server_uri", default=None, help="URI of server. Required with -c", metavar="URI") parser.add_option("--run_id", dest="run_id", default=None, help="run_id of session. Required with -c", metavar="RUN_ID") # #1254: wait until master comes online before starting parser.add_option("--wait", action="store_true", dest="wait_for_master", default=False, help="wait for master to start before launching") parser.add_option("-p", "--port", dest="port", default=None, help="master port. Only valid if master is launched", metavar="PORT") parser.add_option("--core", action="store_true", dest="core", default=False, help="Launch core services only") parser.add_option("--pid", dest="pid_fn", default="", help="write the roslaunch pid to filename") parser.add_option("-v", action="store_true", dest="verbose", default=False, help="verbose printing") parser.add_option("--no-summary", action="store_true", dest="no_summary", default=False, help="hide summary printing") # 2685 - Dump parameters of launch files parser.add_option("--dump-params", default=False, action="store_true", dest="dump_params", help="Dump parameters of all roslaunch files to stdout") parser.add_option("--skip-log-check", default=False, action="store_true", dest="skip_log_check", help="skip check size of log folder") parser.add_option( "--ros-args", default=False, action="store_true", dest="ros_args", help="Display command-line arguments for this launch file") parser.add_option("--disable-title", default=False, action="store_true", dest="disable_title", help="Disable setting of terminal title") parser.add_option( "-w", "--numworkers", dest="num_workers", default=NUM_WORKERS, type=int, help="override number of worker threads. Only valid for core services.", metavar="NUM_WORKERS") parser.add_option( "-t", "--timeout", dest="timeout", help= "override the socket connection timeout (in seconds). Only valid for core services.", metavar="TIMEOUT") parser.add_option( "--master-logger-level", dest="master_logger_level", default=False, type=str, help= "set rosmaster.master logger level ('debug', 'info', 'warn', 'error', 'fatal')" ) parser.add_option( "--sigint-timeout", dest="sigint_timeout", default=DEFAULT_TIMEOUT_SIGINT, type=float, help="the SIGINT timeout used when killing nodes (in seconds).", metavar="SIGINT_TIMEOUT") parser.add_option( "--sigterm-timeout", dest="sigterm_timeout", default=DEFAULT_TIMEOUT_SIGTERM, type=float, help= "the SIGTERM timeout used when killing nodes if SIGINT does not stop the node (in seconds).", metavar="SIGTERM_TIMEOUT") return parser def _validate_args(parser, options, args): # validate args first so we don't spin up any resources if options.child_name: if not options.server_uri: parser.error( "--child option requires --server_uri to be set as well") if not options.run_id: parser.error("--child option requires --run_id to be set as well") if options.port: parser.error("port option cannot be used with roslaunch child mode") if args: parser.error("Input files are not allowed when run in child mode") elif options.core: if options.run_id: parser.error( "--run_id should only be set for child roslaunches (-c)") # we don't actually do anything special for core as the roscore.xml file # is an implicit include for any roslaunch elif len(args) == 0: parser.error("you must specify at least one input file") else: missing_files = [f for f in args if not (f == '-' or os.path.exists(f))] if missing_files: parser.error("The following input files do not exist: %s" % ', '.join(missing_files)) if args.count('-') > 1: parser.error( "Only a single instance of the dash ('-') may be specified.") if len([ x for x in [ options.node_list, options.find_node, options.node_args, options.ros_args ] if x ]) > 1: parser.error( "only one of [--nodes, --find-node, --args --ros-args] may be specified" ) def handle_exception(roslaunch_core, logger, msg, e): roslaunch_core.printerrlog(msg + str(e)) roslaunch_core.printerrlog( 'The traceback for the exception was written to the log file') if logger: logger.error(traceback.format_exc()) sys.exit(1) def main(argv): options = None logger = None try: parser = _get_optparse() (options, args) = parser.parse_args(argv[1:]) args = rlutil.resolve_launch_arguments(args) _validate_args(parser, options, args) # node args doesn't require any roslaunch infrastructure, so process it first if any([ options.node_args, options.node_list, options.find_node, options.dump_params, options.file_list, options.ros_args ]): if options.node_args and not args: parser.error("please specify a launch file") if options.node_args: node_args.print_node_args(options.node_args, args) elif options.find_node: node_args.print_node_filename(options.find_node, args) # Dump parameters, #2685 elif options.dump_params: param_dump.dump_params(args) elif options.file_list: rlutil.print_file_list(args) elif options.ros_args: arg_dump.dump_args(args) else: node_args.print_node_list(args) return # we have to wait for the master here because we don't have the run_id yet if options.wait_for_master: if options.core: parser.error("--wait cannot be used with roscore") rlutil.wait_for_master() # write the pid to a file write_pid_file(options.pid_fn, options.core, options.port) # spin up the logging infrastructure. have to wait until we can read options.run_id uuid = rlutil.get_or_generate_uuid(options.run_id, options.wait_for_master) configure_logging(uuid) # #3088: don't check disk usage on remote machines if not options.child_name and not options.skip_log_check: # #2761 rlutil.check_log_disk_usage() logger = logging.getLogger('roslaunch') logger.info("roslaunch starting with args %s", str(argv)) logger.info("roslaunch env is %s", os.environ) if options.child_name: logger.info('starting in child mode') # This is a roslaunch child, spin up client server. # client spins up an XML-RPC server that waits for # commands and configuration from the server. c = child.ROSLaunchChild(uuid, options.child_name, options.server_uri, sigint_timeout=options.sigint_timeout, sigterm_timeout=options.sigterm_timeout) c.run() else: logger.info('starting in server mode') # #1491 change terminal name if not options.disable_title: rlutil.change_terminal_name(args, options.core) # Read roslaunch string from stdin when - is passed as launch filename. roslaunch_strs = [] if '-' in args: core.printlog( "Passed '-' as file argument, attempting to read roslaunch XML from stdin." ) roslaunch_strs.append(sys.stdin.read()) core.printlog("... %d bytes read successfully.\n" % len(roslaunch_strs[-1])) args.remove('-') # This is a roslaunch parent, spin up parent server and launch processes. # args are the roslaunch files to load # force a port binding spec if we are running a core if options.core: options.port = options.port or DEFAULT_MASTER_PORT p = parent.ROSLaunchParent( uuid, args, roslaunch_strs=roslaunch_strs, is_core=options.core, port=options.port, local_only=options.local_only, verbose=options.verbose, force_screen=options.force_screen, force_log=options.force_log, num_workers=options.num_workers, timeout=options.timeout, master_logger_level=options.master_logger_level, show_summary=not options.no_summary, force_required=options.force_required, sigint_timeout=options.sigint_timeout, sigterm_timeout=options.sigterm_timeout) p.start() p.spin() except RLException as e: handle_exception(core, logger, "RLException: ", e) except ValueError as e: # TODO: need to trap better than this high-level trap handle_exception(core, logger, "Value error: ", e) except rospkg.ResourceNotFound as e: handle_exception(core, logger, "Resource not found: ", e) except Exception as e: traceback.print_exc() sys.exit(1) finally: # remove the pid file if options is not None and options.pid_fn: try: os.unlink(options.pid_fn) except os.error: pass if __name__ == '__main__': main(sys.argv)
[]
[]
[]
[]
[]
python
0
0
tests/src/integration/triggerrule/triggerrule_test.go
// +build integration /* * 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. */ package tests import ( "github.com/apache/incubator-openwhisk-wskdeploy/tests/src/integration/common" "github.com/stretchr/testify/assert" "os" "testing" ) var wskprops = common.GetWskprops() // TODO: write the integration against openwhisk func TestTriggerRule(t *testing.T) { wskdeploy := common.NewWskdeploy() _, err := wskdeploy.Deploy(manifestPath, deploymentPath) assert.Equal(t, nil, err, "Failed to deploy based on the manifest and deployment files.") _, err = wskdeploy.Undeploy(manifestPath, deploymentPath) assert.Equal(t, nil, err, "Failed to undeploy based on the manifest and deployment files.") } var ( manifestPath = os.Getenv("GOPATH") + "/src/github.com/apache/incubator-openwhisk-wskdeploy/tests/src/integration/triggerrule/manifest.yml" deploymentPath = os.Getenv("GOPATH") + "/src/github.com/apache/incubator-openwhisk-wskdeploy/tests/src/integration/triggerrule/deployment.yml" )
[ "\"GOPATH\"", "\"GOPATH\"" ]
[]
[ "GOPATH" ]
[]
["GOPATH"]
go
1
0
infrastructure-provisioning/src/general/scripts/os/common_clean_instance.py
#!/usr/bin/python3 # ***************************************************************************** # # 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 argparse import os import sys from datalab.notebook_lib import * from fabric import * parser = argparse.ArgumentParser() parser.add_argument('--hostname', type=str, default='') parser.add_argument('--keyfile', type=str, default='') parser.add_argument('--os_user', type=str, default='') parser.add_argument('--application', type=str, default='') args = parser.parse_args() def general_clean(): try: conn.sudo('systemctl stop ungit') conn.sudo('systemctl stop inactive.timer') conn.sudo('rm -f /etc/systemd/system/inactive.service') conn.sudo('rm -f /etc/systemd/system/inactive.timer') conn.sudo('rm -rf /opt/inactivity') conn.sudo('npm -g uninstall ungit') conn.sudo('rm -f /etc/systemd/system/ungit.service') conn.sudo('systemctl daemon-reload') remove_os_pkg(['nodejs', 'npm']) conn.sudo('sed -i "/spark.*.memory/d" /opt/spark/conf/spark-defaults.conf') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_jupyter(): try: conn.sudo('systemctl stop jupyter-notebook') conn.sudo('pip3 uninstall -y notebook jupyter') conn.sudo('rm -rf /usr/local/share/jupyter/') conn.sudo('rm -rf /home/{}/.jupyter/'.format(args.os_user)) conn.sudo('rm -rf /home/{}/.ipython/'.format(args.os_user)) conn.sudo('rm -rf /home/{}/.ipynb_checkpoints/'.format(args.os_user)) conn.sudo('rm -rf /home/{}/.local/share/jupyter/'.format(args.os_user)) conn.sudo('rm -f /etc/systemd/system/jupyter-notebook.service') conn.sudo('systemctl daemon-reload') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_jupyterlab(): try: conn.sudo('systemctl stop jupyterlab-notebook') conn.sudo('pip3 uninstall -y jupyterlab') #conn.sudo('rm -rf /usr/local/share/jupyter/') conn.sudo('rm -rf /home/{}/.jupyter/'.format(args.os_user)) conn.sudo('rm -rf /home/{}/.ipython/'.format(args.os_user)) conn.sudo('rm -rf /home/{}/.ipynb_checkpoints/'.format(args.os_user)) conn.sudo('rm -rf /home/{}/.local/share/jupyter/'.format(args.os_user)) conn.sudo('rm -f /etc/systemd/system/jupyterlab-notebook.service') conn.sudo('systemctl daemon-reload') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_zeppelin(): try: conn.sudo('systemctl stop zeppelin-notebook') conn.sudo('rm -rf /opt/zeppelin* /var/log/zeppelin /var/run/zeppelin') if os.environ['notebook_multiple_clusters'] == 'true': conn.sudo('systemctl stop livy-server') conn.sudo('rm -rf /opt/livy* /var/run/livy') conn.sudo('rm -f /etc/systemd/system/livy-server.service') conn.sudo('rm -f /etc/systemd/system/zeppelin-notebook.service') conn.sudo('systemctl daemon-reload') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_rstudio(): try: remove_os_pkg(['rstudio-server']) conn.sudo('rm -f /home/{}/.Rprofile'.format(args.os_user)) conn.sudo('rm -f /home/{}/.Renviron'.format(args.os_user)) except Exception as err: print('Error:', str(err)) sys.exit(1) def clean_tensor(): try: clean_jupyter() conn.sudo('systemctl stop tensorboard') conn.sudo('systemctl disable tensorboard') conn.sudo('systemctl daemon-reload') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_tensor_rstudio(): try: clean_rstudio() conn.sudo('systemctl stop tensorboard') conn.sudo('systemctl disable tensorboard') conn.sudo('systemctl daemon-reload') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_tensor_jupyterlab(): try: clean_jupyterlab() conn.sudo('systemctl stop tensorboard') conn.sudo('systemctl disable tensorboard') conn.sudo('systemctl daemon-reload') except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) def clean_deeplearning(): try: conn.sudo('systemctl stop ungit') conn.sudo('systemctl stop inactive.timer') conn.sudo('rm -f /etc/systemd/system/inactive.service') conn.sudo('rm -f /etc/systemd/system/inactive.timer') conn.sudo('rm -rf /opt/inactivity') conn.sudo('npm -g uninstall ungit') conn.sudo('rm -f /etc/systemd/system/ungit.service') conn.sudo('systemctl daemon-reload') remove_os_pkg(['nodejs', 'npm']) conn.sudo('sed -i "/spark.*.memory/d" /opt/spark/conf/spark-defaults.conf') # conn.sudo('systemctl stop tensorboard') # conn.sudo('systemctl disable tensorboard') # conn.sudo('systemctl daemon-reload') clean_jupyter() except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) if __name__ == "__main__": print('Configure connections') global conn conn = datalab.fab.init_datalab_connection(args.hostname, args.os_user, args.keyfile) if os.environ['conf_cloud_provider'] == 'azure': from datalab.actions_lib import ensure_right_mount_paths ensure_right_mount_paths() de_master_name = '{}-{}-{}-de-{}-m'.format( os.environ['conf_service_base_name'], os.environ['project_name'], os.environ['endpoint_name'], os.environ['computational_name']) de_ami_id = AzureMeta().get_instance_image(os.environ['azure_resource_group_name'], de_master_name) default_ami_id = 'default' else: de_master_name = '{}-{}-{}-de-{}-m'.format( os.environ['conf_service_base_name'], os.environ['project_name'], os.environ['endpoint_name'], os.environ['computational_name']) de_ami_id = get_ami_id_by_instance_name(de_master_name) default_ami_id = get_ami_id( os.environ['aws_{}_image_name'.format(os.environ['conf_os_family'])]) if de_ami_id != default_ami_id: if args.application in os.environ['dataengine_image_notebooks'].split(','): if args.application == 'deeplearning': clean_deeplearning() else: general_clean() if args.application == 'jupyter': clean_jupyter() elif args.application == 'zeppelin': clean_zeppelin() elif args.application == 'rstudio': clean_rstudio() elif args.application == 'tensor': clean_tensor() elif args.application == 'tensor-rstudio': clean_tensor_rstudio() elif args.application == 'tensor-jupyterlab': clean_tensor_jupyterlab() else: print('Found default ami, do not make clean') #conn.close() sys.exit(0)
[]
[]
[ "computational_name", "dataengine_image_notebooks", "conf_cloud_provider", "aws_{}_image_name'.format(os.environ['conf_os_family", "notebook_multiple_clusters", "endpoint_name", "project_name", "azure_resource_group_name", "conf_service_base_name" ]
[]
["computational_name", "dataengine_image_notebooks", "conf_cloud_provider", "aws_{}_image_name'.format(os.environ['conf_os_family", "notebook_multiple_clusters", "endpoint_name", "project_name", "azure_resource_group_name", "conf_service_base_name"]
python
9
0
Institute_Management_System/Institute_Management_System/asgi.py
""" ASGI config for Institute_Management_System project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Institute_Management_System.settings') application = get_asgi_application()
[]
[]
[]
[]
[]
python
0
0
methods_transfers_test.go
package coinbase import ( "fmt" "os" "testing" ) func createTransfersClient(t *testing.T) (c *Client) { c = &Client{ APIKey: os.Getenv("COINBASE_API_KEY"), } if c.APIKey == "" { t.Skip("Coinbase api key is missing (should be in the COINBASE_API_KEY environment variable)") } return c } func TestTransfers(t *testing.T) { c := createTransfersClient(t) transfers, err := c.GetTransfers(1, 0) if err != nil { t.Fatal(err) } fmt.Printf("%+v\n", transfers) }
[ "\"COINBASE_API_KEY\"" ]
[]
[ "COINBASE_API_KEY" ]
[]
["COINBASE_API_KEY"]
go
1
0
vendor/src/github.com/sendgrid/sendgrid-go/examples/clients/clients.go
package main import ( "fmt" "github.com/sendgrid/sendgrid-go" "log" "os" ) /////////////////////////////////////////////////// // Retrieve email statistics by client type. // GET /clients/stats func Retrieveemailstatisticsbyclienttype() { apiKey := os.Getenv("YOUR_SENDGRID_APIKEY") host := "https://api.sendgrid.com" request := sendgrid.GetRequest(apiKey, "/v3/clients/stats", host) request.Method = "GET" queryParams := make(map[string]string) queryParams["aggregated_by"] = "day" queryParams["start_date"] = "2016-01-01" queryParams["end_date"] = "2016-04-01" request.QueryParams = queryParams response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } /////////////////////////////////////////////////// // Retrieve stats by a specific client type. // GET /clients/{client_type}/stats func Retrievestatsbyaspecificclienttype() { apiKey := os.Getenv("YOUR_SENDGRID_APIKEY") host := "https://api.sendgrid.com" request := sendgrid.GetRequest(apiKey, "/v3/clients/{client_type}/stats", host) request.Method = "GET" queryParams := make(map[string]string) queryParams["aggregated_by"] = "day" queryParams["start_date"] = "2016-01-01" queryParams["end_date"] = "2016-04-01" request.QueryParams = queryParams response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } func main() { // add your function calls here }
[ "\"YOUR_SENDGRID_APIKEY\"", "\"YOUR_SENDGRID_APIKEY\"" ]
[]
[ "YOUR_SENDGRID_APIKEY" ]
[]
["YOUR_SENDGRID_APIKEY"]
go
1
0
pkg/runner/run_context.go
package runner import ( "context" "encoding/json" "errors" "fmt" "os" "path/filepath" "regexp" "runtime" "strings" "github.com/google/shlex" "github.com/spf13/pflag" "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" selinux "github.com/opencontainers/selinux/go-selinux" "github.com/nektos/act/pkg/common" "github.com/nektos/act/pkg/container" "github.com/nektos/act/pkg/model" ) const ActPath string = "/var/run/act" // RunContext contains info about current job type RunContext struct { Name string Config *Config Matrix map[string]interface{} Run *model.Run EventJSON string Env map[string]string ExtraPath []string CurrentStep string StepResults map[string]*stepResult ExprEval ExpressionEvaluator JobContainer container.Container OutputMappings map[MappableOutput]MappableOutput JobName string } type MappableOutput struct { StepID string OutputName string } func (rc *RunContext) String() string { return fmt.Sprintf("%s/%s", rc.Run.Workflow.Name, rc.Name) } type stepStatus int const ( stepStatusSuccess stepStatus = iota stepStatusFailure ) var stepStatusStrings = [...]string{ "success", "failure", } func (s stepStatus) MarshalText() ([]byte, error) { return []byte(s.String()), nil } func (s *stepStatus) UnmarshalText(b []byte) error { str := string(b) for i, name := range stepStatusStrings { if name == str { *s = stepStatus(i) return nil } } return fmt.Errorf("invalid step status %q", str) } func (s stepStatus) String() string { if int(s) >= len(stepStatusStrings) { return "" } return stepStatusStrings[s] } type stepResult struct { Outputs map[string]string `json:"outputs"` Conclusion stepStatus `json:"conclusion"` Outcome stepStatus `json:"outcome"` } // GetEnv returns the env for the context func (rc *RunContext) GetEnv() map[string]string { if rc.Env == nil { rc.Env = mergeMaps(rc.Config.Env, rc.Run.Workflow.Env, rc.Run.Job().Environment()) } rc.Env["ACT"] = "true" return rc.Env } func (rc *RunContext) jobContainerName() string { return createContainerName("act", rc.String()) } // Returns the binds and mounts for the container, resolving paths as appopriate func (rc *RunContext) GetBindsAndMounts() ([]string, map[string]string) { name := rc.jobContainerName() if rc.Config.ContainerDaemonSocket == "" { rc.Config.ContainerDaemonSocket = "/var/run/docker.sock" } binds := []string{ fmt.Sprintf("%s:%s", rc.Config.ContainerDaemonSocket, "/var/run/docker.sock"), } mounts := map[string]string{ "act-toolcache": "/toolcache", name + "-env": ActPath, } if rc.Config.BindWorkdir { bindModifiers := "" if runtime.GOOS == "darwin" { bindModifiers = ":delegated" } if selinux.GetEnabled() { bindModifiers = ":z" } binds = append(binds, fmt.Sprintf("%s:%s%s", rc.Config.Workdir, rc.Config.ContainerWorkdir(), bindModifiers)) } else { mounts[name] = rc.Config.ContainerWorkdir() } return binds, mounts } func (rc *RunContext) startJobContainer() common.Executor { image := rc.platformImage() hostname := rc.hostname() return func(ctx context.Context) error { rawLogger := common.Logger(ctx).WithField("raw_output", true) logWriter := common.NewLineWriter(rc.commandHandler(ctx), func(s string) bool { if rc.Config.LogOutput { rawLogger.Infof("%s", s) } else { rawLogger.Debugf("%s", s) } return true }) username, password, err := rc.handleCredentials() if err != nil { return fmt.Errorf("failed to handle credentials: %s", err) } common.Logger(ctx).Infof("\U0001f680 Start image=%s", image) name := rc.jobContainerName() envList := make([]string, 0) envList = append(envList, fmt.Sprintf("%s=%s", "RUNNER_TOOL_CACHE", "/opt/hostedtoolcache")) envList = append(envList, fmt.Sprintf("%s=%s", "RUNNER_OS", "Linux")) envList = append(envList, fmt.Sprintf("%s=%s", "RUNNER_TEMP", "/tmp")) binds, mounts := rc.GetBindsAndMounts() rc.JobContainer = container.NewContainer(&container.NewContainerInput{ Cmd: nil, Entrypoint: []string{"/usr/bin/tail", "-f", "/dev/null"}, WorkingDir: rc.Config.ContainerWorkdir(), Image: image, Username: username, Password: password, Name: name, Env: envList, Mounts: mounts, NetworkMode: "host", Binds: binds, Stdout: logWriter, Stderr: logWriter, Privileged: rc.Config.Privileged, UsernsMode: rc.Config.UsernsMode, Platform: rc.Config.ContainerArchitecture, Hostname: hostname, }) var copyWorkspace bool var copyToPath string if !rc.Config.BindWorkdir { copyToPath, copyWorkspace = rc.localCheckoutPath() copyToPath = filepath.Join(rc.Config.ContainerWorkdir(), copyToPath) } return common.NewPipelineExecutor( rc.JobContainer.Pull(rc.Config.ForcePull), rc.stopJobContainer(), rc.JobContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop), rc.JobContainer.Start(false), rc.JobContainer.UpdateFromImageEnv(&rc.Env), rc.JobContainer.UpdateFromEnv("/etc/environment", &rc.Env), rc.JobContainer.Exec([]string{"mkdir", "-m", "0777", "-p", ActPath}, rc.Env, "root", ""), rc.JobContainer.CopyDir(copyToPath, rc.Config.Workdir+string(filepath.Separator)+".", rc.Config.UseGitIgnore).IfBool(copyWorkspace), rc.JobContainer.Copy(ActPath+"/", &container.FileEntry{ Name: "workflow/event.json", Mode: 0644, Body: rc.EventJSON, }, &container.FileEntry{ Name: "workflow/envs.txt", Mode: 0666, Body: "", }, &container.FileEntry{ Name: "workflow/paths.txt", Mode: 0666, Body: "", }), )(ctx) } } func (rc *RunContext) execJobContainer(cmd []string, env map[string]string, user, workdir string) common.Executor { return func(ctx context.Context) error { return rc.JobContainer.Exec(cmd, env, user, workdir)(ctx) } } // stopJobContainer removes the job container (if it exists) and its volume (if it exists) if !rc.Config.ReuseContainers func (rc *RunContext) stopJobContainer() common.Executor { return func(ctx context.Context) error { if rc.JobContainer != nil && !rc.Config.ReuseContainers { return rc.JobContainer.Remove(). Then(container.NewDockerVolumeRemoveExecutor(rc.jobContainerName(), false))(ctx) } return nil } } // Prepare the mounts and binds for the worker // ActionCacheDir is for rc func (rc *RunContext) ActionCacheDir() string { var xdgCache string var ok bool if xdgCache, ok = os.LookupEnv("XDG_CACHE_HOME"); !ok || xdgCache == "" { if home, err := homedir.Dir(); err == nil { xdgCache = filepath.Join(home, ".cache") } else if xdgCache, err = filepath.Abs("."); err != nil { log.Fatal(err) } } return filepath.Join(xdgCache, "act") } // Interpolate outputs after a job is done func (rc *RunContext) interpolateOutputs() common.Executor { return func(ctx context.Context) error { ee := rc.NewExpressionEvaluator() for k, v := range rc.Run.Job().Outputs { interpolated := ee.Interpolate(v) if v != interpolated { rc.Run.Job().Outputs[k] = interpolated } } return nil } } // Executor returns a pipeline executor for all the steps in the job func (rc *RunContext) Executor() common.Executor { steps := make([]common.Executor, 0) steps = append(steps, func(ctx context.Context) error { if len(rc.Matrix) > 0 { common.Logger(ctx).Infof("\U0001F9EA Matrix: %v", rc.Matrix) } return nil }) steps = append(steps, rc.startJobContainer()) for i, step := range rc.Run.Job().Steps { if step.ID == "" { step.ID = fmt.Sprintf("%d", i) } steps = append(steps, rc.newStepExecutor(step)) } steps = append(steps, rc.stopJobContainer()) return common.NewPipelineExecutor(steps...).Finally(rc.interpolateOutputs()).Finally(func(ctx context.Context) error { if rc.JobContainer != nil { return rc.JobContainer.Close()(ctx) } return nil }).If(rc.isEnabled) } func (rc *RunContext) newStepExecutor(step *model.Step) common.Executor { sc := &StepContext{ RunContext: rc, Step: step, } return func(ctx context.Context) error { rc.CurrentStep = sc.Step.ID rc.StepResults[rc.CurrentStep] = &stepResult{ Outcome: stepStatusSuccess, Conclusion: stepStatusSuccess, Outputs: make(map[string]string), } runStep, err := rc.EvalBool(sc.Step.If.Value) if err != nil { common.Logger(ctx).Errorf(" \u274C Error in if: expression - %s", sc.Step) exprEval, err := sc.setupEnv(ctx) if err != nil { return err } rc.ExprEval = exprEval rc.StepResults[rc.CurrentStep].Conclusion = stepStatusFailure rc.StepResults[rc.CurrentStep].Outcome = stepStatusFailure return err } if !runStep { log.Debugf("Skipping step '%s' due to '%s'", sc.Step.String(), sc.Step.If.Value) return nil } exprEval, err := sc.setupEnv(ctx) if err != nil { return err } rc.ExprEval = exprEval common.Logger(ctx).Infof("\u2B50 Run %s", sc.Step) err = sc.Executor()(ctx) if err == nil { common.Logger(ctx).Infof(" \u2705 Success - %s", sc.Step) } else { common.Logger(ctx).Errorf(" \u274C Failure - %s", sc.Step) rc.StepResults[rc.CurrentStep].Outcome = stepStatusFailure if sc.Step.ContinueOnError { common.Logger(ctx).Infof("Failed but continue next step") err = nil rc.StepResults[rc.CurrentStep].Conclusion = stepStatusSuccess } else { rc.StepResults[rc.CurrentStep].Conclusion = stepStatusFailure } } return err } } func (rc *RunContext) platformImage() string { job := rc.Run.Job() c := job.Container() if c != nil { return rc.ExprEval.Interpolate(c.Image) } if job.RunsOn() == nil { log.Errorf("'runs-on' key not defined in %s", rc.String()) } for _, runnerLabel := range job.RunsOn() { platformName := rc.ExprEval.Interpolate(runnerLabel) image := rc.Config.Platforms[strings.ToLower(platformName)] if image != "" { return image } } return "" } func (rc *RunContext) hostname() string { job := rc.Run.Job() c := job.Container() if c == nil { return "" } optionsFlags := pflag.NewFlagSet("container_options", pflag.ContinueOnError) hostname := optionsFlags.StringP("hostname", "h", "", "") optionsArgs, err := shlex.Split(c.Options) if err != nil { log.Warnf("Cannot parse container options: %s", c.Options) return "" } err = optionsFlags.Parse(optionsArgs) if err != nil { log.Warnf("Cannot parse container options: %s", c.Options) return "" } return *hostname } func (rc *RunContext) isEnabled(ctx context.Context) bool { job := rc.Run.Job() l := common.Logger(ctx) runJob, err := rc.EvalBool(job.If.Value) if err != nil { common.Logger(ctx).Errorf(" \u274C Error in if: expression - %s", job.Name) return false } if !runJob { l.Debugf("Skipping job '%s' due to '%s'", job.Name, job.If.Value) return false } img := rc.platformImage() if img == "" { if job.RunsOn() == nil { log.Errorf("'runs-on' key not defined in %s", rc.String()) } for _, runnerLabel := range job.RunsOn() { platformName := rc.ExprEval.Interpolate(runnerLabel) l.Infof("\U0001F6A7 Skipping unsupported platform -- Try running with `-P %+v=...`", platformName) } return false } return true } var splitPattern *regexp.Regexp // EvalBool evaluates an expression against current run context func (rc *RunContext) EvalBool(expr string) (bool, error) { if splitPattern == nil { splitPattern = regexp.MustCompile(fmt.Sprintf(`%s|%s|\S+`, expressionPattern.String(), operatorPattern.String())) } if strings.HasPrefix(strings.TrimSpace(expr), "!") { return false, errors.New("expressions starting with ! must be wrapped in ${{ }}") } if expr != "" { parts := splitPattern.FindAllString(expr, -1) var evaluatedParts []string for i, part := range parts { if operatorPattern.MatchString(part) { evaluatedParts = append(evaluatedParts, part) continue } interpolatedPart, isString := rc.ExprEval.InterpolateWithStringCheck(part) // This peculiar transformation has to be done because the GitHub parser // treats false returned from contexts as a string, not a boolean. // Hence env.SOMETHING will be evaluated to true in an if: expression // regardless if SOMETHING is set to false, true or any other string. // It also handles some other weirdness that I found by trial and error. if (expressionPattern.MatchString(part) && // it is an expression !strings.Contains(part, "!")) && // but it's not negated interpolatedPart == "false" && // and the interpolated string is false (isString || previousOrNextPartIsAnOperator(i, parts)) { // and it's of type string or has an logical operator before or after interpolatedPart = fmt.Sprintf("'%s'", interpolatedPart) // then we have to quote the false expression } evaluatedParts = append(evaluatedParts, interpolatedPart) } joined := strings.Join(evaluatedParts, " ") v, _, err := rc.ExprEval.Evaluate(fmt.Sprintf("Boolean(%s)", joined)) if err != nil { return false, err } log.Debugf("expression '%s' evaluated to '%s'", expr, v) return v == "true", nil } return true, nil } func previousOrNextPartIsAnOperator(i int, parts []string) bool { operator := false if i > 0 { operator = operatorPattern.MatchString(parts[i-1]) } if i+1 < len(parts) { operator = operator || operatorPattern.MatchString(parts[i+1]) } return operator } func mergeMaps(maps ...map[string]string) map[string]string { rtnMap := make(map[string]string) for _, m := range maps { for k, v := range m { rtnMap[k] = v } } return rtnMap } func createContainerName(parts ...string) string { name := make([]string, 0) pattern := regexp.MustCompile("[^a-zA-Z0-9]") partLen := (30 / len(parts)) - 1 for i, part := range parts { if i == len(parts)-1 { name = append(name, pattern.ReplaceAllString(part, "-")) } else { // If any part has a '-<number>' on the end it is likely part of a matrix job. // Let's preserve the number to prevent clashes in container names. re := regexp.MustCompile("-[0-9]+$") num := re.FindStringSubmatch(part) if len(num) > 0 { name = append(name, trimToLen(pattern.ReplaceAllString(part, "-"), partLen-len(num[0]))) name = append(name, num[0]) } else { name = append(name, trimToLen(pattern.ReplaceAllString(part, "-"), partLen)) } } } return strings.ReplaceAll(strings.Trim(strings.Join(name, "-"), "-"), "--", "-") } func trimToLen(s string, l int) string { if l < 0 { l = 0 } if len(s) > l { return s[:l] } return s } type jobContext struct { Status string `json:"status"` Container struct { ID string `json:"id"` Network string `json:"network"` } `json:"container"` Services map[string]struct { ID string `json:"id"` } `json:"services"` } func (rc *RunContext) getJobContext() *jobContext { jobStatus := "success" for _, stepStatus := range rc.StepResults { if stepStatus.Conclusion == stepStatusFailure { jobStatus = "failure" break } } return &jobContext{ Status: jobStatus, } } func (rc *RunContext) getStepsContext() map[string]*stepResult { return rc.StepResults } type githubContext struct { Event map[string]interface{} `json:"event"` EventPath string `json:"event_path"` Workflow string `json:"workflow"` RunID string `json:"run_id"` RunNumber string `json:"run_number"` Actor string `json:"actor"` Repository string `json:"repository"` EventName string `json:"event_name"` Sha string `json:"sha"` Ref string `json:"ref"` HeadRef string `json:"head_ref"` BaseRef string `json:"base_ref"` Token string `json:"token"` Workspace string `json:"workspace"` Action string `json:"action"` ActionPath string `json:"action_path"` ActionRef string `json:"action_ref"` ActionRepository string `json:"action_repository"` Job string `json:"job"` JobName string `json:"job_name"` RepositoryOwner string `json:"repository_owner"` RetentionDays string `json:"retention_days"` RunnerPerflog string `json:"runner_perflog"` RunnerTrackingID string `json:"runner_tracking_id"` } func (rc *RunContext) getGithubContext() *githubContext { ghc := &githubContext{ Event: make(map[string]interface{}), EventPath: ActPath + "/workflow/event.json", Workflow: rc.Run.Workflow.Name, RunID: rc.Config.Env["GITHUB_RUN_ID"], RunNumber: rc.Config.Env["GITHUB_RUN_NUMBER"], Actor: rc.Config.Actor, EventName: rc.Config.EventName, Workspace: rc.Config.ContainerWorkdir(), Action: rc.CurrentStep, Token: rc.Config.Secrets["GITHUB_TOKEN"], ActionPath: rc.Config.Env["GITHUB_ACTION_PATH"], ActionRef: rc.Config.Env["RUNNER_ACTION_REF"], ActionRepository: rc.Config.Env["RUNNER_ACTION_REPOSITORY"], RepositoryOwner: rc.Config.Env["GITHUB_REPOSITORY_OWNER"], RetentionDays: rc.Config.Env["GITHUB_RETENTION_DAYS"], RunnerPerflog: rc.Config.Env["RUNNER_PERFLOG"], RunnerTrackingID: rc.Config.Env["RUNNER_TRACKING_ID"], } if ghc.RunID == "" { ghc.RunID = "1" } if ghc.RunNumber == "" { ghc.RunNumber = "1" } if ghc.RetentionDays == "" { ghc.RetentionDays = "0" } if ghc.RunnerPerflog == "" { ghc.RunnerPerflog = "/dev/null" } // Backwards compatibility for configs that require // a default rather than being run as a cmd if ghc.Actor == "" { ghc.Actor = "nektos/act" } repoPath := rc.Config.Workdir repo, err := common.FindGithubRepo(repoPath, rc.Config.GitHubInstance) if err != nil { log.Warningf("unable to get git repo: %v", err) } else { ghc.Repository = repo if ghc.RepositoryOwner == "" { ghc.RepositoryOwner = strings.Split(repo, "/")[0] } } _, sha, err := common.FindGitRevision(repoPath) if err != nil { log.Warningf("unable to get git revision: %v", err) } else { ghc.Sha = sha } if rc.EventJSON != "" { err = json.Unmarshal([]byte(rc.EventJSON), &ghc.Event) if err != nil { log.Errorf("Unable to Unmarshal event '%s': %v", rc.EventJSON, err) } } maybeRef := nestedMapLookup(ghc.Event, ghc.EventName, "ref") if maybeRef != nil { log.Debugf("using github ref from event: %s", maybeRef) ghc.Ref = maybeRef.(string) } else { ref, err := common.FindGitRef(repoPath) if err != nil { log.Warningf("unable to get git ref: %v", err) } else { log.Debugf("using github ref: %s", ref) ghc.Ref = ref } // set the branch in the event data if rc.Config.DefaultBranch != "" { ghc.Event = withDefaultBranch(rc.Config.DefaultBranch, ghc.Event) } else { ghc.Event = withDefaultBranch("master", ghc.Event) } } if ghc.EventName == "pull_request" { ghc.BaseRef = asString(nestedMapLookup(ghc.Event, "pull_request", "base", "ref")) ghc.HeadRef = asString(nestedMapLookup(ghc.Event, "pull_request", "head", "ref")) } return ghc } func (ghc *githubContext) isLocalCheckout(step *model.Step) bool { if step.Type() == model.StepTypeInvalid { // This will be errored out by the executor later, we need this here to avoid a null panic though return false } if step.Type() != model.StepTypeUsesActionRemote { return false } remoteAction := newRemoteAction(step.Uses) if remoteAction == nil { // IsCheckout() will nil panic if we dont bail out early return false } if !remoteAction.IsCheckout() { return false } if repository, ok := step.With["repository"]; ok && repository != ghc.Repository { return false } if repository, ok := step.With["ref"]; ok && repository != ghc.Ref { return false } return true } func asString(v interface{}) string { if v == nil { return "" } else if s, ok := v.(string); ok { return s } return "" } func nestedMapLookup(m map[string]interface{}, ks ...string) (rval interface{}) { var ok bool if len(ks) == 0 { // degenerate input return nil } if rval, ok = m[ks[0]]; !ok { return nil } else if len(ks) == 1 { // we've reached the final key return rval } else if m, ok = rval.(map[string]interface{}); !ok { return nil } else { // 1+ more keys return nestedMapLookup(m, ks[1:]...) } } func withDefaultBranch(b string, event map[string]interface{}) map[string]interface{} { repoI, ok := event["repository"] if !ok { repoI = make(map[string]interface{}) } repo, ok := repoI.(map[string]interface{}) if !ok { log.Warnf("unable to set default branch to %v", b) return event } // if the branch is already there return with no changes if _, ok = repo["default_branch"]; ok { return event } repo["default_branch"] = b event["repository"] = repo return event } func (rc *RunContext) withGithubEnv(env map[string]string) map[string]string { github := rc.getGithubContext() env["CI"] = "true" env["GITHUB_ENV"] = ActPath + "/workflow/envs.txt" env["GITHUB_PATH"] = ActPath + "/workflow/paths.txt" env["GITHUB_WORKFLOW"] = github.Workflow env["GITHUB_RUN_ID"] = github.RunID env["GITHUB_RUN_NUMBER"] = github.RunNumber env["GITHUB_ACTION"] = github.Action if github.ActionPath != "" { env["GITHUB_ACTION_PATH"] = github.ActionPath } env["GITHUB_ACTIONS"] = "true" env["GITHUB_ACTOR"] = github.Actor env["GITHUB_REPOSITORY"] = github.Repository env["GITHUB_EVENT_NAME"] = github.EventName env["GITHUB_EVENT_PATH"] = github.EventPath env["GITHUB_WORKSPACE"] = github.Workspace env["GITHUB_SHA"] = github.Sha env["GITHUB_REF"] = github.Ref env["GITHUB_TOKEN"] = github.Token env["GITHUB_SERVER_URL"] = "https://github.com" env["GITHUB_API_URL"] = "https://api.github.com" env["GITHUB_GRAPHQL_URL"] = "https://api.github.com/graphql" env["GITHUB_ACTION_REF"] = github.ActionRef env["GITHUB_ACTION_REPOSITORY"] = github.ActionRepository env["GITHUB_BASE_REF"] = github.BaseRef env["GITHUB_HEAD_REF"] = github.HeadRef env["GITHUB_JOB"] = rc.JobName env["GITHUB_REPOSITORY_OWNER"] = github.RepositoryOwner env["GITHUB_RETENTION_DAYS"] = github.RetentionDays env["RUNNER_PERFLOG"] = github.RunnerPerflog env["RUNNER_TRACKING_ID"] = github.RunnerTrackingID if rc.Config.GitHubInstance != "github.com" { env["GITHUB_SERVER_URL"] = fmt.Sprintf("https://%s", rc.Config.GitHubInstance) env["GITHUB_API_URL"] = fmt.Sprintf("https://%s/api/v3", rc.Config.GitHubInstance) env["GITHUB_GRAPHQL_URL"] = fmt.Sprintf("https://%s/api/graphql", rc.Config.GitHubInstance) } if rc.Config.ArtifactServerPath != "" { setActionRuntimeVars(rc, env) } job := rc.Run.Job() if job.RunsOn() != nil { for _, runnerLabel := range job.RunsOn() { platformName := rc.ExprEval.Interpolate(runnerLabel) if platformName != "" { if platformName == "ubuntu-latest" { // hardcode current ubuntu-latest since we have no way to check that 'on the fly' env["ImageOS"] = "ubuntu20" } else { platformName = strings.SplitN(strings.Replace(platformName, `-`, ``, 1), `.`, 2)[0] env["ImageOS"] = platformName } } } } return env } func setActionRuntimeVars(rc *RunContext, env map[string]string) { actionsRuntimeURL := os.Getenv("ACTIONS_RUNTIME_URL") if actionsRuntimeURL == "" { actionsRuntimeURL = fmt.Sprintf("http://%s:%s/", common.GetOutboundIP().String(), rc.Config.ArtifactServerPort) } env["ACTIONS_RUNTIME_URL"] = actionsRuntimeURL actionsRuntimeToken := os.Getenv("ACTIONS_RUNTIME_TOKEN") if actionsRuntimeToken == "" { actionsRuntimeToken = "token" } env["ACTIONS_RUNTIME_TOKEN"] = actionsRuntimeToken } func (rc *RunContext) localCheckoutPath() (string, bool) { ghContext := rc.getGithubContext() for _, step := range rc.Run.Job().Steps { if ghContext.isLocalCheckout(step) { return step.With["path"], true } } return "", false } func (rc *RunContext) handleCredentials() (username, password string, err error) { // TODO: remove below 2 lines when we can release act with breaking changes username = rc.Config.Secrets["DOCKER_USERNAME"] password = rc.Config.Secrets["DOCKER_PASSWORD"] container := rc.Run.Job().Container() if container == nil || container.Credentials == nil { return } if container.Credentials != nil && len(container.Credentials) != 2 { err = fmt.Errorf("invalid property count for key 'credentials:'") return } ee := rc.NewExpressionEvaluator() var ok bool if username, ok = ee.InterpolateWithStringCheck(container.Credentials["username"]); !ok { err = fmt.Errorf("failed to interpolate container.credentials.username") return } if password, ok = ee.InterpolateWithStringCheck(container.Credentials["password"]); !ok { err = fmt.Errorf("failed to interpolate container.credentials.password") return } if container.Credentials["username"] == "" || container.Credentials["password"] == "" { err = fmt.Errorf("container.credentials cannot be empty") return } return username, password, err }
[ "\"ACTIONS_RUNTIME_URL\"", "\"ACTIONS_RUNTIME_TOKEN\"" ]
[]
[ "ACTIONS_RUNTIME_URL", "ACTIONS_RUNTIME_TOKEN" ]
[]
["ACTIONS_RUNTIME_URL", "ACTIONS_RUNTIME_TOKEN"]
go
2
0
vendor/code.cloudfoundry.org/cli/cf/cmd/cmd_test.go
package cmd_test import ( "bufio" "net/http" "os" "os/exec" "path/filepath" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/gomega/gexec" ) var buildPath string var _ = SynchronizedBeforeSuite(func() []byte { path, buildErr := Build("code.cloudfoundry.org/cli") Expect(buildErr).NotTo(HaveOccurred()) return []byte(path) }, func(data []byte) { buildPath = string(data) }) // gexec.Build leaves a compiled binary behind in /tmp. var _ = SynchronizedAfterSuite(func() {}, func() { CleanupBuildArtifacts() }) var _ = Describe("main", func() { var ( old_PLUGINS_HOME string ) BeforeEach(func() { old_PLUGINS_HOME = os.Getenv("CF_PLUGIN_HOME") dir, err := os.Getwd() Expect(err).NotTo(HaveOccurred()) fullDir := filepath.Join(dir, "..", "..", "fixtures", "config", "main-plugin-test-config") err = os.Setenv("CF_PLUGIN_HOME", fullDir) Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { err := os.Setenv("CF_PLUGIN_HOME", old_PLUGINS_HOME) Expect(err).NotTo(HaveOccurred()) }) Describe("Help menu with -h/--help", func() { It("prints the help output with our custom template when run with 'cf -h'", func() { output := Cf("-h", "-a") Eventually(output.Out.Contents).Should(ContainSubstring("A command line tool to interact with Cloud Foundry")) Eventually(output.Out.Contents).Should(ContainSubstring("CF_TRACE=true")) }) It("prints the help output with our custom template when run with 'cf --help'", func() { output := Cf("--help", "-a") Eventually(output.Out.Contents).Should(ContainSubstring("A command line tool to interact with Cloud Foundry")) Eventually(output.Out.Contents).Should(ContainSubstring("CF_TRACE=true")) }) It("accepts -h and --h flags for all commands", func() { result := Cf("push", "-h") Consistently(result.Out).ShouldNot(Say("Incorrect Usage")) Eventually(result.Out.Contents).Should(ContainSubstring("USAGE")) result = Cf("push", "--no-route", "-h") Consistently(result.Out).ShouldNot(Say("Incorrect Usage")) Eventually(result.Out.Contents).Should(ContainSubstring("USAGE")) result = Cf("target", "--h") Consistently(result.Out).ShouldNot(Say("Incorrect Usage")) Eventually(result.Out.Contents).Should(ContainSubstring("USAGE")) }) It("accepts -h before the command name", func() { result := Cf("-h", "push", "--no-route") Consistently(result.Out).ShouldNot(Say("Incorrect Usage")) Consistently(result.Out).ShouldNot(Say("Start an app")) Eventually(result.Out.Contents).Should(ContainSubstring("USAGE")) Eventually(result.Out.Contents).Should(ContainSubstring("push")) }) It("accepts -h before the command alias", func() { result := Cf("-h", "p", "--no-route") Consistently(result.Out).ShouldNot(Say("Incorrect Usage")) Consistently(result.Out).ShouldNot(Say("Start an app")) Eventually(result.Out.Contents).Should(ContainSubstring("USAGE")) Eventually(result.Out.Contents).Should(ContainSubstring("push")) }) }) Describe("Shows version with -v or --version", func() { It("prints the cf version if '-v' flag is provided", func() { output := Cf("-v") Eventually(output.Out.Contents).Should(ContainSubstring("cf version")) Eventually(output).Should(Exit(0)) }) It("prints the cf version if '--version' flag is provided", func() { output := Cf("--version") Eventually(output.Out.Contents).Should(ContainSubstring("cf version")) Eventually(output).Should(Exit(0)) }) }) Describe("Enables verbose output with -v", func() { BeforeEach(func() { client := http.Client{Timeout: 3 * time.Second} _, err := client.Get("http://api.bosh-lite.com/v2/info") if err != nil { Skip("unable to communicate with bosh-lite, skipping") } setApiOutput := Cf("api", "http://api.bosh-lite.com", "--skip-ssl-validation") Eventually(setApiOutput.Out.Contents).Should(ContainSubstring("OK")) }) // Normally cf curl only shows the output of the response // When using trace, it also shows the request/response information It("enables verbose output when -v is provided before a command", func() { output := Cf("-v", "curl", "/v2/info") Consistently(output.Out.Contents).ShouldNot(ContainSubstring("Invalid flag: -v")) Eventually(output.Out.Contents).Should(ContainSubstring("GET /v2/info HTTP/1.1")) }) It("enables verbose output when -v is provided after a command", func() { output := Cf("curl", "/v2/info", "-v") Consistently(output.Out.Contents).ShouldNot(ContainSubstring("Invalid flag: -v")) Eventually(output.Out.Contents).Should(ContainSubstring("GET /v2/info HTTP/1.1")) }) }) Describe("Commands with new command structure", func() { It("prints usage help for all commands by providing `help` flag", func() { output := Cf("api", "-h") Eventually(output.Out.Contents).Should(ContainSubstring("USAGE")) Eventually(output.Out.Contents).Should(ContainSubstring("OPTIONS")) }) It("accepts -h and --h flags for commands", func() { result := Cf("api", "-h") Consistently(result.Out).ShouldNot(Say("Invalid flag: -h")) Eventually(result.Out.Contents).Should(ContainSubstring("api - Set or view target api url")) result = Cf("api", "--h") Consistently(result.Out).ShouldNot(Say("Invalid flag: --h")) Eventually(result.Out.Contents).Should(ContainSubstring("api - Set or view target api url")) }) }) Describe("exit codes", func() { It("exits non-zero when an unknown command is invoked", func() { result := Cf("some-command-that-should-never-actually-be-a-real-thing-i-can-use") Eventually(result, 3*time.Second).Should(Say("not a registered command")) Eventually(result).Should(Exit(1)) }) It("exits non-zero when known command is invoked with invalid option", func() { result := Cf("push", "--crazy") Eventually(result).Should(Exit(1)) }) }) It("can print help menu by executing only the command `cf`", func() { output := Cf() Eventually(output.Out.Contents).Should(ContainSubstring("Cloud Foundry command line tool")) }) It("show user suggested commands for typos", func() { output := Cf("hlp") Eventually(output.Out, 3*time.Second).Should(Say("'hlp' is not a registered command. See 'cf help'")) Eventually(output.Out, 3*time.Second).Should(Say("Did you mean?")) }) It("does not display requirement errors twice", func() { output := Cf("space") Eventually(output).Should(Exit(1)) Expect(output.Err).To(Say("the required argument `SPACE` was not provided")) Expect(output.Err).NotTo(Say("the required argument `SPACE` was not provided")) Expect(output.Out).NotTo(Say("the required argument `SPACE` was not provided")) }) Describe("Plugins", func() { It("Can call a plugin command from the Plugins configuration if it does not exist as a cf command", func() { output := Cf("test_1_cmd1") Eventually(output.Out).Should(Say("You called cmd1 in test_1")) }) It("Can call a plugin command via alias if it does not exist as a cf command", func() { output := Cf("test_1_cmd1_alias") Eventually(output.Out).Should(Say("You called cmd1 in test_1")) }) It("Can call another plugin command when more than one plugin is installed", func() { output := Cf("test_2_cmd1") Eventually(output.Out).Should(Say("You called cmd1 in test_2")) }) It("hide suggetsions for commands that aren't close to anything", func() { output := Cf("this-does-not-match-any-command") Eventually(output.Out, 3*time.Second).Should(Say("'this-does-not-match-any-command' is not a registered command. See 'cf help'")) Consistently(output.Out, 3*time.Second).ShouldNot(Say("Did you mean?\n help")) }) It("informs user for any invalid commands", func() { output := Cf("foo-bar") Eventually(output.Out, 3*time.Second).Should(Say("'foo-bar' is not a registered command")) }) It("Calls help if the plugin shares the same name", func() { output := Cf("help") Consistently(output.Out, 1).ShouldNot(Say("You called help in test_with_help")) }) It("shows help with a '-h' or '--help' flag in plugin command", func() { output := Cf("test_1_cmd1", "-h") Consistently(output.Out).ShouldNot(Say("You called cmd1 in test_1")) Eventually(output.Out.Contents).Should(ContainSubstring("USAGE:")) Eventually(output.Out.Contents).Should(ContainSubstring("OPTIONS:")) }) It("Calls the core push command if the plugin shares the same name", func() { output := Cf("push") Consistently(output.Out, 1).ShouldNot(Say("You called push in test_with_push")) }) It("Calls the core short name if a plugin shares the same name", func() { output := Cf("p") Consistently(output.Out, 1).ShouldNot(Say("You called p within the plugin")) }) It("Passes all arguments to a plugin", func() { output := Cf("my-say", "foo") Eventually(output.Out).Should(Say("foo")) }) It("Passes all arguments and flags to a plugin", func() { output := Cf("my-say", "foo", "--loud") Eventually(output.Out).Should(Say("FOO")) }) It("Calls a plugin that calls core commands", func() { output := Cf("awesomeness") Eventually(output.Out).Should(Say("my-say")) //look for another plugin }) It("Sends stdoutput to the plugin to echo", func() { output := Cf("core-command", "plugins") Eventually(output.Out.Contents).Should(MatchRegexp("Command output from the plugin(.*\\W)*awesomeness(.*\\W)*FIN")) }) It("Can call a core commmand from a plugin without terminal output", func() { output := Cf("core-command-quiet", "plugins") Eventually(output.Out.Contents).Should(MatchRegexp("^\n---------- Command output from the plugin")) }) It("Can call a plugin that requires stdin (interactive)", func() { session := CfWithIo("input", "silly\n") Eventually(session.Out).Should(Say("silly")) }) It("exits 1 when a plugin panics", func() { session := Cf("panic") Eventually(session).Should(Exit(1)) }) It("exits 1 when a plugin exits 1", func() { session := Cf("exit1") Eventually(session).Should(Exit(1)) }) It("show user suggested plugin commands for typos", func() { output := Cf("test_1_cmd") Eventually(output.Out, 3*time.Second).Should(Say("'test_1_cmd' is not a registered command. See 'cf help'")) Eventually(output.Out, 3*time.Second).Should(Say("Did you mean?")) }) }) }) func Cf(args ...string) *Session { session, err := Start(exec.Command(buildPath, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) return session } func CfWithIo(command string, args string) *Session { cmd := exec.Command(buildPath, command) stdin, err := cmd.StdinPipe() Expect(err).ToNot(HaveOccurred()) buffer := bufio.NewWriter(stdin) buffer.WriteString(args) buffer.Flush() session, err := Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) return session } func CfWith_CF_HOME(cfHome string, args ...string) *Session { cmd := exec.Command(buildPath, args...) cmd.Env = append(cmd.Env, "CF_HOME="+cfHome) session, err := Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) return session }
[ "\"CF_PLUGIN_HOME\"" ]
[]
[ "CF_PLUGIN_HOME" ]
[]
["CF_PLUGIN_HOME"]
go
1
0
test/python/test_parallel.py
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """Tests for qiskit/_util.py""" import os import time from qiskit.tools.parallel import parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from .common import QiskitTestCase def _parfunc(x): """Function for testing parallel_map """ time.sleep(1) return x def _build_simple(_): qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) return qc class TestParallel(QiskitTestCase): """A class for testing parallel_map functionality. """ def test_parallel_env_flag(self): """Verify parallel env flag is set """ self.assertEqual(os.getenv('QISKIT_IN_PARALLEL', None), 'FALSE') def test_parallel(self): """Test parallel_map """ ans = parallel_map(_parfunc, list(range(10))) self.assertEqual(ans, list(range(10))) def test_parallel_circuit_names(self): """Verify unique circuit names in parallel""" out_circs = parallel_map(_build_simple, list(range(10))) names = [circ.name for circ in out_circs] self.assertEqual(len(names), len(set(names)))
[]
[]
[ "QISKIT_IN_PARALLEL" ]
[]
["QISKIT_IN_PARALLEL"]
python
1
0
appserver/addons/IMAPmailbox-TA/bin/get_imap_email.py
__doc__ = """ # Copyright 2007 Erik Swan and Splunk, Inc. - [email protected] # This file contains a simple imap -> splunk processor # It is used by splunk to download mail into the splunk server # # Change History # -------------- # Date Author Changes # ----- ------ --------- # 07/10/2008 Jimmy J Changes to do the caching by reading the latest UID from splunk messages itself # Code modified to write a UID key/value pair for every message # Removed all commented code # Fixed the function 'usage' # Removed the hard-coded path separator '/', instead used # os.path.join so it will work even if run on a non *nix platform # Imported traceback module for improved error reporting # Got rid of the splunk CLI interface to determine the last UID # and used the splunk REST API instead # Got rid of imports that were not being used # Made the splunkHost, splunkuser, splunkpassword and splunkxpassword configurable # # 02/11/2014 PJ Balsley Updated script. # Fixed reading some imap.conf settings that only worked with False/True, and not with 0/1. # Minor typeo fixes. # Minor debug issues fixed. # # NOTE: If encrypted passwords are being used, the user needs to run the provided genpass.sh script twice, once for the mailbox password # and once for the splunk server password. Cut/copy/paste the generated encrypted password and place it into the imap.conf config file # """ import getopt, sys, imaplib, os, string, email, logging, time import subprocess, ConfigParser, traceback, datetime, cStringIO, base64 # Generic error class class ConfigError(Exception): pass class LoginError(Exception): pass splunk_home = os.getenv('SPLUNK_HOME') if not splunk_home: raise ConfigError('Environment variable SPLUNK_HOME must be set. Run: source ~/bin/setSplunkEnv') # # This is the list of configuration options that can be set either on the # command line or via the imap.conf file. Note that these names must # correspond exactly to field names in the IMAPProcessor class and the names # specified in the optlist near the bottom of this file. # # The imap.conf configuration file provides more detailed documentation about # the effects of each of the options. # configOptions = [ "server", # imap server name/ip "user", # imap user account "password", # imap plaintext password "xpassword", # or imap encrypted password "port", # imap server port "folders", # list of imap folders to index "imapSearch", # imap search string "fullHeaders", # whether all headers should be indexed "includeBody", # whether the body of messages should be indexed "mimeTypes", # list of mime types to index if multipart "splunkuser", # splunk server userid "splunkpassword", # splunk server password "splunkxpassword", # or splunk server encrypted password "splunkHostPath", # splunk server host path "timeout", # seconds to wait for connected to mailserver. "noCache", # if true, the 'already indexed' markers are ignored "debug", # if true, extra debug info is output "useSSL", # true if use ssl "deleteWhenDone" # delete messages after indexing ] # path to the configuration imap.conf file scriptDir = sys.path[0] # find it relative to get_imap_email.py file configDefaultFileName = os.path.join(scriptDir,'..','default','imap.conf') configLocalFileName = os.path.join(scriptDir,'..','local','imap.conf') # name of the only stanza in the config file configSectionName = "IMAP Configuration" #-------------------------------------------------------------- # IMAPprocessor will download mail from an imap server and write to sdtout. # This is how to get mail into splunk. #-------------------------------------------------------------- class IMAPProcessor(object): # ------------------- # default values. # ------------------- def __init__(self): # initialize all of the configuration fields with default values that # will be used on the off chance that they don't appear in imap.conf self.server = "" # this is required self.user = "" # this is required self.password = "" # and either this... self.xpassword = "" # ...or this is also required self.port = 993 self.folders = 'all' self.imapSearch = 'UNDELETED' self.fullHeaders = False self.includeBody = True self.mimeTypes = 'text/plain' self._mimeTypesList = [] # split list of mime types self.splunkuser = 'admin' self.splunkpassword = 'changeme' # default splunk admin password self.splunkxpassword = '' self.splunkHostPath = 'https://localhost:8089' self.timeout = 10 self.noCache = False self.debug = False self.useSSL = True self.deleteWhenDone = False self.END_IMAP_BREAKER = 'EndIMAPMessage' self.bodySourceType = 'imapbody' self.body_separator = '____________________ Message Body ____________________' self.headerSourceType = 'imap' self.useBodySourceType = False self.version = "2.0" # ----------------------------------- # read in all options and settings. # ----------------------------------- def initFromOptlist(self, optlist): # First read settings in imap.conf, if it exists... self.readConfig() # ...now, for debugging and backward compat, allow command line # settings to override... self.readOptlist(optlist) if self.debug: logging.basicConfig(level=logging.DEBUG) keys = self.__dict__.keys(); keys.sort(); for k in keys: if k.startswith("_"): continue logging.debug(k + "=" + str(self.__dict__[k])) else: logging.basicConfig(level=logging.ERROR) # check min required args if self.server == "" or self.user == "" or ( self.password == "" and self.xpassword =="" ): self.usage() #sys.exit() raise ConfigError # pre-parse the mime types list if self.mimeTypes.find(",") > -1: self._mimeTypesList = self.mimeTypes.split(",") else: self._mimeTypesList.append(self.mimeTypes) # deleteWhenDone overrides any caching. Our assumption is that all messages in the box are new each time if self.deleteWhenDone: self.noCache = True # ----------------------------------- # - Read settings from imap.conf(s) # ----------------------------------- def readConfig(self): path = '' if os.path.exists(configLocalFileName): path = configLocalFileName elif os.path.exists(configDefaultFileName): path = configDefaultFileName else: return # future fyi, v3 will rename ConfigParser to configparser config = ConfigParser.RawConfigParser() config.read(path) for o in configOptions: if config.has_option(configSectionName, o): val = getattr(self, o) # check to see if the current/default value is a boolean; if so, # makes user user supplied value is a bool, will convert string to bool. # ie. makes 0 = False and 1 = True if val.__class__ == bool: val = (config.get(configSectionName, o).strip().lower() == "true") if config.get(configSectionName, o) == "1": val = True if config.get(configSectionName, o) == "0": val = False else: val = config.get(configSectionName, o) setattr(self, o, val) # ---------------------------------------------------------------- # Read settings from the command line. We support command # line args mainly for backwards compat and for quick debugging; # users should be encouraged to use the imap.conf file instead # ---------------------------------------------------------------- def readOptlist(self, optlist): for o, a in optlist: o = o[2:] # strip the leading -- if o in configOptions: val = getattr(self, o) # check to see if the current/default value is a boolean. If so, # then the value is true if specified as a flag; otherwise, convert # the option value to a bool. if val.__class__ == bool: if (a == None or len(a) == 0) : val = True else: val = (a.strip().lower() == "true") else: val = a setattr(self, o, val) # --------------------- # usage text for help # --------------------- def usage(self): logging.debug("The required fields are: server, user and (password or xpassword)") logging.debug("eg:") logging.debug("python get_imap_email.py --server=<mail server name> --user=<user name> --password=<unencrypted password> OR") logging.debug("python get_imap_email.py --server=<mail server name> --user=<user name> --xpassword=<encrypted password>") logging.debug("Other parameters that can also be supplied. Refer the default/imap.conf file for details") # --------------------------------------------------------- # Helper function for mapping folder to UID # Returns the cached id for the given mailbox, or zero if # we've never looked in it before # --------------------------------------------------------- def getCacheIDForMailbox(self, box): if not self.noCache: #If we are here it means we have to extract the last used UID from splunk... import splunk.auth as au import splunk.search as se import splunk import httplib2 import time import string if self.splunkxpassword: try: p = subprocess.Popen('openssl bf -d -a -pass file:%s' % (os.path.join(os.environ['SPLUNK_HOME'],'etc','auth', 'splunk.secret')), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.splunkpassword = p.communicate(self.splunkxpassword + '\n')[0] except Exception, e: if self.debug: logging.error(e) print traceback.print_exc(file=sys.stderr) raise ConfigError('Could not decrypt splunkxpassword') logging.debug("decrypted splunk password") splunk.mergeHostPath(self.splunkHostPath, True) try: key = au.getSessionKey(self.splunkuser, self.splunkpassword) except httplib2.ServerNotFoundError, e: raise LoginError("Unable to find the server at %s" % self.splunkHostPath) except Exception, e: raise LoginError("userid/password combination for splunk user is invalid...") if not key: raise LoginError("userid/password combination for splunk user is invalid...") if box[0] == "'" or box[0] == '"': ss = 'search index=mail mailbox=' + box + ' | head 1 | stats max(Date)' else: ss = 'search index=mail mailbox="' + box + '" | head 1 | stats max(Date)' job = se.dispatch(ss, sessionKey=key) start = datetime.datetime.now() logging.debug("dispatched search = " + ss) logging.debug("dispatched job to splunk through the REST API. Waiting for response...") while not job.isDone: time.sleep(1) logging.debug("*** waiting ") now = datetime.datetime.now() #if (now - start).seconds > self.timeout: if int((now - start).seconds) > int(self.timeout): logging.debug("REST response took more than %s seconds, timing out...using default UID of 0 i.e. same as noCache" % str(self.timeout)) break #if we have caching on, and we run this for the first time, the result will not have any key like UID #Hence it will throw a KeyError or IndexError. Just ignore that error and return 0 try: retVal = str(job.results[0]['max(Date)']) logging.debug(" got back " + str(retVal)) except Exception, e: logging.debug(str(e)) logging.debug(" mailbox was empty ") retVal = "" job.cancel() return retVal else: return "" # -------------------------------------------------- # Method will login and iterate through each folder # -------------------------------------------------- def getMail(self): logging.debug("VERSION = " + str(self.version)) # If the user supplied encrypted password then we need to unencrypt. if self.xpassword: try: p = subprocess.Popen('openssl bf -d -a -pass file:%s' % (os.path.join(os.environ['SPLUNK_HOME'],'etc','auth', 'splunk.secret')), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.password = p.communicate(self.xpassword + '\n')[0] except Exception, e: if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) raise ConfigError('Could not decrypt xpassword') # Try and login try: if self.port: if self.useSSL: M = imaplib.IMAP4_SSL(self.server,int(self.port)) else: M = imaplib.IMAP4(self.server,int(self.port)) else: if self.useSSL: M = imaplib.IMAP4_SSL(self.server) else: M = imaplib.IMAP4(self.server) M.login(self.user, self.password) except Exception, e: if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) raise LoginError('Could not log into server: %s with password provided' % self.server) try: folder_list = [] # See if we need to interate all folders put them into a list if self.folders.lower() == "all": result,list = M.list(); for f in list[:]: x = f.split() mailbox = string.join(x[2:]) folder_list.append(mailbox) # If the user supplied a list of mailboxes, split them up and put in list elif not self.folders == "": if self.folders.find(",") > -1: folder_list = self.folders.split(",") else: folder_list.append(self.folders) else: folder_list = ["*"] # Run though each of the mailboxes for i in folder_list: self.getMailbox(M, i) except LoginError, e: if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) raise e except ConfigError, e: if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) M.logout() raise e except Exception, e: if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) logging.error("ERROR - trying to login to server and get folders") # --------------------------------------------------- # Method will login and iterate through each folder. # --------------------------------------------------- def getMailbox(self, M, box): box = box.replace('"/" ', '') box = box.strip() logging.debug("about to dump mailbox %s" % (box)) # new method # search for the last internal time # get messages since that day of the latest internal time # get internal time for each message # skip ahead until the internal time is matching # dedupe # for all new messages index. try: # get message id we read up to last time (0 first time) latestTime = self.getCacheIDForMailbox(box) logging.debug("using last time of " + latestTime) # Select the mail box at hand, or * for defult if box == "*": resCode, resText = M.select() else: resCode, resText = M.select(box) endid = int(resText[0]) if endid < 1: return # each mailbox is its own source. i # We use the ***SPLUNK*** header processor trick to change sources for each event # each of the below must be on its own line, thus the breaker text after. print "***SPLUNK*** source="+box + " sourcetype=imap host=" + self.server print self.END_IMAP_BREAKER if latestTime == "": self.getAllMail(M, box, endid) else: self.getLatestMail(latestTime, M, box, endid) # if delete when done, clean it up if self.deleteWhenDone: M.expunge() if resCode == 'NO': raise ConfigError("Folder name %s does not exist..." % box) except Exception, e: if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) logging.error("ERROR - trying to select mailbox") try: M.close() except: pass # ------------------------------- # Download all email # ------------------------------ def getAllMail(self, M, box, endid): chunksize = 200 counter = 1 logging.debug("about to get all mail up to counter :" + str(endid)) try: while counter <= endid: searchStr = "(" + self.imapSearch + " " + str(counter) + ":" + str(counter+chunksize) + ")" logging.debug("about so imap search with : " + searchStr) counter = counter + chunksize typ, data = M.search(None, searchStr) ids = data[0].split() if len(ids) < 1: continue; logging.debug("returned from search with " + str(len(ids)) + "ids") logging.debug("id return from search : " + str(ids)) # for each message id.... for num in ids: try: self.fetchMessage(M, box, num, "") except Exception, e: logging.debug("ERROR trying to fetrucn message id: " + num) if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) except: if self.debug: print traceback.print_exc(file=sys.stderr) logging.error("ERROR - trying to search mailbox") # --------------------------------------------------- def getInternalDate(self, M, box, num): dstr = '' try: typ, data = M.fetch(num, '(INTERNALDATE)') dates = data[0] begin = dates.find('"') end = dates.rfind('"') dstr = dates[begin+1:end] except: dstr = '' logging.debug("ERROR - could not get date for message - this is a problem") return dstr # ------------------------------------------------------------------ # get the messages for the day of last time. # unfortunately it looks like the granularity of search is per day. # so we read starting the day and then skip ahead, kinda lame. # ------------------------------------------------------------------ def getLatestMail( self, latestTimeStr, M, box, endid): logging.debug("About to get lastest mail sinze " + latestTimeStr ) # convert to a datetime so we can compare lastDateTime = datetime.datetime.strptime(latestTimeStr[:-6],"%d-%b-%Y %H:%M:%S") logging.debug("datetime for latest is " + str(lastDateTime)) # strip off the time, since imap only does day granularity justDate = latestTimeStr.split(' ')[0] searchStr = "(" + self.imapSearch + " SINCE " + justDate + ")" logging.debug("About to search IMAP using ; " + searchStr) typ, data = M.search(None, searchStr) logging.debug("Got back the following for the day " + str(data) ); ids = data[0].split() logging.debug("returned from search with " + str(len(ids)) + "ids") logging.debug("id return from search : " + str(ids)) # if empty there is no new data, bail. if len(ids) < 1: logging.debug("Got zero ids, doing nothihng") return; # for each new message id for num in ids: # get message date so that we can compare to see if is newer dstr = self.getInternalDate(M, box, num) if dstr == "": continue # convert message date to datetime so we can compare msgDateTime = datetime.datetime.strptime(dstr[:-6],"%d-%b-%Y %H:%M:%S") logging.debug("datetime for message " + str(msgDateTime)) # see if we are caught up yet... if lastDateTime < msgDateTime: # this is a new message, print it out self.fetchMessage(M, box, num, dstr) # ------------------------------------------------ # print body message to STDOUT for indexing # ------------------------------------------------ def printBody( self, message, body, cstr ): if message.has_key('Content-Transfer-Encoding') and message.get('Content-Transfer-Encoding')=='base64': try: body = base64.b64decode(body) #cstr.write('decoded base64 successfully' + '\n') except: cstr.write('WARNING - could not decode base64' + '\n') cstr.write(body + '\n') # ------------------------------------------------- # Get and print to STDOUT the mail message # ------------------------------------------------- def fetchMessage( self, M, box, num , dstr): cstr = cStringIO.StringIO() try: # get UID typ, data = M.fetch(num, 'UID') uid = int(data[0].split()[0]) lastUID = uid if dstr == "": dstr = self.getInternalDate(M, box, num) # get message body try: typ, data = M.fetch(num, '(BODY.PEEK[])') #typ, data = M.fetch(num, '(RFC822)') body = data[0][1] except: logging.debug("Fetch error" + num ) if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) # get message size typ, data = M.fetch(num, '(RFC822.SIZE)') size = data[0].split() size = size[-1].replace(')', '') # create message object from the body message = email.message_from_string(body) # Try printing out the date first, we will use this to break the events. if dstr == '': dstr = 'no date in message' if message.has_key('date'): dstr = message['date'] elif message.has_key('Date'): dstr = message['Date'] elif message.has_key('DATE'): dstr = message['DATE'] cstr.write('Date = "' + dstr + '"\n') for k, v in message.items(): if k == 'date' or k == 'Date': continue if not self.fullHeaders: lk = string.lower(k) if lk == 'from' or lk == 'to' or lk == 'subject' or lk == 'date' or lk == 'cc': cstr.write(k + ' = "' + string.replace(v,'"','') + '"\n') else: cstr.write(k + ' = "' + string.replace(v,'"','') + '"\n') # include size and name of folder since they are not part of header # interestingly, sometimes these come back quoted - so check. if box[0]=="'" or box[0]=='"': cstr.write('mailbox = ' + box + '\n') else: cstr.write('mailbox = "' + box + '"\n') cstr.write("size = "+size + '\n') # If option includeBody is True then print STOUT the mail body. if self.includeBody: # print the body separator line. cstr.write(self.body_separator + '\n') # This option is old and not needed. We auto set sourcetype in inputs.conf now. if self.useBodySourceType: # hardcoded the changing of sourcetype to mailbody. # customers can change the procssing of mailbody's differently in props.conf cstr.write("EndIMAPHeader" + '\n') cstr.write("sourcetype=" + self.bodySourceType + '\n') # if we are breaking up the event we need to spit out a timestamp. cstr.write("date = " + message['date'] + '\n') # if the message is not multipart - its text so just dump it out. #for key in message.keys(): # cstr.write("***key " + key + " ** value=" + message.get(key)+ '\n') if not message.is_multipart(): body = message.get_payload() self.printBody(message, body, cstr) else: # if it is multipart, then only dump parts whose type is # in the mimeTypes list. for part in message.walk(): if part.get_content_type() in self._mimeTypesList: body = part.get_payload(decode=True) self.printBody( message, body, cstr ) # else, we are not indexing the message body, so do nothing. # just print debug data only. else: if self.debug: for part in message.walk(): cstr.write("ContentType : " + part.get_content_type() + '\n') logging.debug("No message context to print as value includeBody is set to False" + '\n') cstr.write(self.END_IMAP_BREAKER) if self.useBodySourceType: # set us back to mail sourcetype cstr.write("***splunk*** sourcetype=" + self.headerSourceType + '\n') print cstr.getvalue() # if delete when done, then mark the message if self.deleteWhenDone: M.store(num, '+Flags', '(\Deleted)') except Exception, e: logging.debug("1. Failed to get and print message with UID " + num ) if self.debug: logging.debug(e) print traceback.print_exc(file=sys.stderr) logging.debug("2. Failed to get and print message with UID " + num ) # -------------------------------------------------------------- # - parse all program options # -------------------------------------------------------------- def parseArgs(): imapProc = IMAPProcessor() optlist = None try: optlist, args = getopt.getopt(sys.argv[1:], '?',['version', 'server=','user=', 'password=', 'xpassword=', 'port=', 'folders=', 'imapSearch=', 'fullHeaders=', 'includeBody=', 'mimeTypes=', 'splunkuser=', 'splunkpassword=', 'splunkxpassword=', 'splunkHostPath=', 'timeout=', 'noCache', 'debug', 'useSSL=', 'deleteWhenDone=']) if 'version' in args: print sys.argv[0], "version =", str(imapProc.version) return imapProc.initFromOptlist(optlist) except getopt.error, val: logging.error("str(val) # tell them what was wrong") imapProc.usage() raise ConfigError("Incorrect usage...") #- Do the work.... imapProc.getMail() # -------------------------------------------------------------- # - Start script # -------------------------------------------------------------- if __name__ == '__main__': parseArgs()
[]
[]
[ "SPLUNK_HOME" ]
[]
["SPLUNK_HOME"]
python
1
0
lib/galaxy/tool_util/verify/interactor.py
import io import json import os import re import shutil import sys import tarfile import tempfile import time import urllib.parse import zipfile from json import dumps from logging import getLogger import requests from packaging.version import parse as parse_version, Version try: from nose.tools import nottest except ImportError: def nottest(x): return x from galaxy import util from galaxy.tool_util.parser.interface import TestCollectionDef, TestCollectionOutputDef from galaxy.util.bunch import Bunch from . import verify from .asserts import verify_assertions from .wait import wait_on log = getLogger(__name__) # Off by default because it can pound the database pretty heavily # and result in sqlite errors on larger tests or larger numbers of # tests. VERBOSE_ERRORS = util.asbool(os.environ.get("GALAXY_TEST_VERBOSE_ERRORS", False)) UPLOAD_ASYNC = util.asbool(os.environ.get("GALAXY_TEST_UPLOAD_ASYNC", True)) ERROR_MESSAGE_DATASET_SEP = "--------------------------------------" DEFAULT_TOOL_TEST_WAIT = int(os.environ.get("GALAXY_TEST_DEFAULT_WAIT", 86400)) DEFAULT_FTYPE = 'auto' # This following default dbkey was traditionally hg17 before Galaxy 18.05, # restore this behavior by setting GALAXY_TEST_DEFAULT_DBKEY to hg17. DEFAULT_DBKEY = os.environ.get("GALAXY_TEST_DEFAULT_DBKEY", "?") class OutputsDict(dict): """Ordered dict that can also be accessed by index. >>> out = OutputsDict() >>> out['item1'] = 1 >>> out['item2'] = 2 >>> out[1] == 2 == out['item2'] True """ def __getitem__(self, item): if isinstance(item, int): return self[list(self.keys())[item]] else: return super().__getitem__(item) def stage_data_in_history(galaxy_interactor, tool_id, all_test_data, history=None, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_version=None): # Upload any needed files upload_waits = [] assert tool_id if UPLOAD_ASYNC: for test_data in all_test_data: upload_waits.append(galaxy_interactor.stage_data_async(test_data, history, tool_id, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version)) for upload_wait in upload_waits: upload_wait() else: for test_data in all_test_data: upload_wait = galaxy_interactor.stage_data_async(test_data, history, tool_id, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version) upload_wait() class GalaxyInteractorApi: def __init__(self, **kwds): self.api_url = f"{kwds['galaxy_url'].rstrip('/')}/api" self.cookies = None self.master_api_key = kwds["master_api_key"] self.api_key = self.__get_user_key(kwds.get("api_key"), kwds.get("master_api_key"), test_user=kwds.get("test_user")) if kwds.get('user_api_key_is_admin_key', False): self.master_api_key = self.api_key self.keep_outputs_dir = kwds["keep_outputs_dir"] self.download_attempts = kwds.get("download_attempts", 1) self.download_sleep = kwds.get("download_sleep", 1) # Local test data directories. self.test_data_directories = kwds.get("test_data") or [] self._target_galaxy_version = None self.uploads = {} @property def target_galaxy_version(self): if self._target_galaxy_version is None: self._target_galaxy_version = parse_version(self._get('version').json()['version_major']) return self._target_galaxy_version @property def supports_test_data_download(self): return self.target_galaxy_version >= Version("19.01") def __get_user_key(self, user_key, admin_key, test_user=None): if not test_user: test_user = "[email protected]" if user_key: return user_key test_user = self.ensure_user_with_email(test_user) return self._post(f"users/{test_user['id']}/api_key", key=admin_key).json() # def get_tools(self): # response = self._get("tools?in_panel=false") # assert response.status_code == 200, "Non 200 response from tool index API. [%s]" % response.content # return response.json() def get_tests_summary(self): response = self._get("tools/tests_summary") assert response.status_code == 200, f"Non 200 response from tool tests available API. [{response.content}]" return response.json() def get_tool_tests(self, tool_id, tool_version=None): url = f"tools/{tool_id}/test_data" params = {'tool_version': tool_version} if tool_version else None response = self._get(url, data=params) assert response.status_code == 200, f"Non 200 response from tool test API. [{response.content}]" return response.json() def verify_output_collection(self, output_collection_def, output_collection_id, history, tool_id, tool_version=None): data_collection = self._get(f"dataset_collections/{output_collection_id}", data={"instance_type": "history"}).json() def verify_dataset(element, element_attrib, element_outfile): hda = element["object"] try: self.verify_output_dataset( history, hda_id=hda["id"], outfile=element_outfile, attributes=element_attrib, tool_id=tool_id, tool_version=tool_version, ) except AssertionError as e: raise AssertionError(f"Collection element {element.get('element_identifier', '')} of collection {output_collection_def.name}: {e}") verify_collection(output_collection_def, data_collection, verify_dataset) def verify_output(self, history_id, jobs, output_data, output_testdef, tool_id, maxseconds, tool_version=None): outfile = output_testdef.outfile attributes = output_testdef.attributes name = output_testdef.name self.wait_for_jobs(history_id, jobs, maxseconds) hid = self.__output_id(output_data) # TODO: Twill version verifies dataset is 'ok' in here. try: self.verify_output_dataset(history_id=history_id, hda_id=hid, outfile=outfile, attributes=attributes, tool_id=tool_id, tool_version=tool_version) except AssertionError as e: raise AssertionError(f"Output {name}: {str(e)}") primary_datasets = attributes.get('primary_datasets', {}) if primary_datasets: job_id = self._dataset_provenance(history_id, hid)["job_id"] outputs = self._get(f"jobs/{job_id}/outputs").json() for designation, (primary_outfile, primary_attributes) in primary_datasets.items(): primary_output = None for output in outputs: if output["name"] == f'__new_primary_file_{name}|{designation}__': primary_output = output break if not primary_output: raise Exception(f"Failed to find primary dataset with designation [{designation}] for output with name [{name}]") primary_hda_id = primary_output["dataset"]["id"] try: self.verify_output_dataset(history_id, primary_hda_id, primary_outfile, primary_attributes, tool_id=tool_id, tool_version=tool_version) except AssertionError as e: raise AssertionError(f"Primary output {name}: {str(e)}") def wait_for_jobs(self, history_id, jobs, maxseconds): for job in jobs: self.wait_for_job(job['id'], history_id, maxseconds) def verify_output_dataset(self, history_id, hda_id, outfile, attributes, tool_id, tool_version=None): fetcher = self.__dataset_fetcher(history_id) test_data_downloader = self.__test_data_downloader(tool_id, tool_version) verify_hid( outfile, hda_id=hda_id, attributes=attributes, dataset_fetcher=fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=self.keep_outputs_dir ) self._verify_metadata(history_id, hda_id, attributes) def _verify_metadata(self, history_id, hid, attributes): """Check dataset metadata. ftype on output maps to `file_ext` on the hda's API description, `name`, `info`, `dbkey` and `tags` all map to the API description directly. Other metadata attributes are assumed to be datatype-specific and mapped with a prefix of `metadata_`. """ metadata = attributes.get('metadata', {}).copy() for key in metadata.copy().keys(): if key not in ['name', 'info', 'tags', 'created_from_basename']: new_key = f"metadata_{key}" metadata[new_key] = metadata[key] del metadata[key] elif key == "info": metadata["misc_info"] = metadata["info"] del metadata["info"] expected_file_type = attributes.get('ftype', None) if expected_file_type: metadata["file_ext"] = expected_file_type if metadata: def wait_for_content(): response = self._get(f"histories/{history_id}/contents/{hid}") try: response.raise_for_status() return response.json() except requests.exceptions.HTTPError: return None dataset = wait_on(wait_for_content, desc='dataset metadata', timeout=10) for key, value in metadata.items(): try: dataset_value = dataset.get(key, None) def compare(val, expected): if str(val) != str(expected): msg = f"Dataset metadata verification for [{key}] failed, expected [{value}] but found [{dataset_value}]. Dataset API value was [{dataset}]." raise Exception(msg) if isinstance(dataset_value, list): value = str(value).split(",") if len(value) != len(dataset_value): msg = f"Dataset metadata verification for [{key}] failed, expected [{value}] but found [{dataset_value}], lists differ in length. Dataset API value was [{dataset}]." raise Exception(msg) for val, expected in zip(dataset_value, value): compare(val, expected) else: compare(dataset_value, value) except KeyError: msg = f"Failed to verify dataset metadata, metadata key [{key}] was not found." raise Exception(msg) def wait_for_job(self, job_id, history_id=None, maxseconds=DEFAULT_TOOL_TEST_WAIT): self.wait_for(lambda: self.__job_ready(job_id, history_id), maxseconds=maxseconds) def wait_for(self, func, what='tool test run', **kwd): walltime_exceeded = int(kwd.get("maxseconds", DEFAULT_TOOL_TEST_WAIT)) wait_on(func, what, walltime_exceeded) def get_job_stdio(self, job_id): job_stdio = self.__get_job_stdio(job_id).json() return job_stdio def __get_job(self, job_id): return self._get(f'jobs/{job_id}') def __get_job_stdio(self, job_id): return self._get(f'jobs/{job_id}?full=true') def get_history(self, history_name='test_history'): # Return the most recent non-deleted history matching the provided name response = self._get(f"histories?q=name&qv={history_name}&order=update_time") try: return response.json()[-1] except IndexError: return None def new_history(self, history_name='test_history', publish_history=False): create_response = self._post("histories", {"name": history_name}) try: create_response.raise_for_status() except Exception as e: raise Exception(f"Error occured while creating history with name '{history_name}': {e}") history_id = create_response.json()['id'] if publish_history: self.publish_history(history_id) return history_id def publish_history(self, history_id): response = self._put(f'histories/{history_id}', json.dumps({'published': True})) response.raise_for_status() @nottest def test_data_path(self, tool_id, filename, tool_version=None): version_fragment = f'&tool_version={tool_version}' if tool_version else '' response = self._get(f"tools/{tool_id}/test_data_path?filename={filename}{version_fragment}", admin=True) return response.json() @nottest def test_data_download(self, tool_id, filename, mode='file', is_output=True, tool_version=None): result = None local_path = None if self.supports_test_data_download: version_fragment = f'&tool_version={tool_version}' if tool_version else '' response = self._get(f"tools/{tool_id}/test_data_download?filename={filename}{version_fragment}", admin=True) if response.status_code == 200: if mode == 'file': result = response.content elif mode == 'directory': prefix = os.path.basename(filename) path = tempfile.mkdtemp(prefix=prefix) fileobj = io.BytesIO(response.content) if zipfile.is_zipfile(fileobj): with zipfile.ZipFile(fileobj) as contents: contents.extractall(path=path) else: # Galaxy < 21.01 with tarfile.open(fileobj=fileobj) as tar_contents: tar_contents.extractall(path=path) result = path else: # We can only use local data local_path = self.test_data_path(tool_id, filename, tool_version=tool_version) if result is None and (local_path is None or not os.path.exists(local_path)): for test_data_directory in self.test_data_directories: local_path = os.path.join(test_data_directory, filename) if os.path.exists(local_path): break if result is None and local_path is not None and os.path.exists(local_path): if mode == 'file': with open(local_path, mode='rb') as f: result = f.read() elif mode == 'directory': # Make a copy, since we are going to clean up the returned path path = tempfile.mkdtemp() shutil.copytree(local_path, path) result = path if result is None: if is_output: raise AssertionError(f"Test output file ({filename}) is missing. If you are using planemo, try adding --update_test_data to generate it.") else: raise AssertionError(f"Test input file ({filename}) cannot be found.") return result def __output_id(self, output_data): # Allow data structure coming out of tools API - {id: <id>, output_name: <name>, etc...} # or simple id as comes out of workflow API. try: output_id = output_data.get('id') except AttributeError: output_id = output_data return output_id def stage_data_async(self, test_data, history_id, tool_id, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_version=None): fname = test_data['fname'] tool_input = { "file_type": test_data['ftype'], "dbkey": test_data['dbkey'], } metadata = test_data.get("metadata", {}) if not hasattr(metadata, "items"): raise Exception(f"Invalid metadata description found for input [{fname}] - [{metadata}]") for name, value in test_data.get('metadata', {}).items(): tool_input[f"files_metadata|{name}"] = value composite_data = test_data['composite_data'] if composite_data: files = {} for i, file_name in enumerate(composite_data): if force_path_paste: file_path = self.test_data_path(tool_id, file_name, tool_version=tool_version) tool_input.update({ f"files_{i}|url_paste": f"file://{file_path}" }) else: file_content = self.test_data_download(tool_id, file_name, is_output=False, tool_version=tool_version) files[f"files_{i}|file_data"] = file_content tool_input.update({ f"files_{i}|type": "upload_dataset", }) name = test_data['name'] else: name = os.path.basename(fname) tool_input.update({ "files_0|NAME": name, "files_0|type": "upload_dataset", }) files = {} if force_path_paste: file_name = self.test_data_path(tool_id, fname, tool_version=tool_version) tool_input.update({ "files_0|url_paste": f"file://{file_name}" }) else: file_content = self.test_data_download(tool_id, fname, is_output=False, tool_version=tool_version) files = { "files_0|file_data": file_content } submit_response_object = self.__submit_tool(history_id, "upload1", tool_input, extra_data={"type": "upload_dataset"}, files=files) submit_response = ensure_tool_run_response_okay(submit_response_object, f"upload dataset {name}") assert "outputs" in submit_response, f"Invalid response from server [{submit_response}], expecting outputs in response." outputs = submit_response["outputs"] assert len(outputs) > 0, f"Invalid response from server [{submit_response}], expecting an output dataset." dataset = outputs[0] hid = dataset['id'] self.uploads[os.path.basename(fname)] = self.uploads[fname] = self.uploads[name] = {"src": "hda", "id": hid} assert "jobs" in submit_response, f"Invalid response from server [{submit_response}], expecting jobs in response." jobs = submit_response["jobs"] assert len(jobs) > 0, f"Invalid response from server [{submit_response}], expecting a job." return lambda: self.wait_for_job(jobs[0]["id"], history_id, maxseconds=maxseconds) def run_tool(self, testdef, history_id, resource_parameters=None): # We need to handle the case where we've uploaded a valid compressed file since the upload # tool will have uncompressed it on the fly. resource_parameters = resource_parameters or {} inputs_tree = testdef.inputs.copy() for key, value in inputs_tree.items(): values = [value] if not isinstance(value, list) else value new_values = [] for value in values: if isinstance(value, TestCollectionDef): hdca_id = self._create_collection(history_id, value) new_values = [dict(src="hdca", id=hdca_id)] elif value in self.uploads: new_values.append(self.uploads[value]) else: new_values.append(value) inputs_tree[key] = new_values if resource_parameters: inputs_tree["__job_resource|__job_resource__select"] = "yes" for key, value in resource_parameters.items(): inputs_tree[f"__job_resource|{key}"] = value # HACK: Flatten single-value lists. Required when using expand_grouping for key, value in inputs_tree.items(): if isinstance(value, list) and len(value) == 1: inputs_tree[key] = value[0] submit_response = None for _ in range(DEFAULT_TOOL_TEST_WAIT): submit_response = self.__submit_tool(history_id, tool_id=testdef.tool_id, tool_input=inputs_tree, tool_version=testdef.tool_version) if _are_tool_inputs_not_ready(submit_response): print("Tool inputs not ready yet") time.sleep(1) continue else: break submit_response_object = ensure_tool_run_response_okay(submit_response, "execute tool", inputs_tree) try: return Bunch( inputs=inputs_tree, outputs=self.__dictify_outputs(submit_response_object), output_collections=self.__dictify_output_collections(submit_response_object), jobs=submit_response_object['jobs'], ) except KeyError: message = f"Error creating a job for these tool inputs - {submit_response_object['err_msg']}" raise RunToolException(message, inputs_tree) def _create_collection(self, history_id, collection_def): create_payload = dict( name=collection_def.name, element_identifiers=self._element_identifiers(collection_def), collection_type=collection_def.collection_type, history_id=history_id, ) return self._post("dataset_collections", data=create_payload, json=True).json()["id"] def _element_identifiers(self, collection_def): element_identifiers = [] for element_dict in collection_def.elements: element_identifier = element_dict["element_identifier"] element_def = element_dict["element_definition"] if isinstance(element_def, TestCollectionDef): subelement_identifiers = self._element_identifiers(element_def) element = dict( name=element_identifier, src="new_collection", collection_type=element_def.collection_type, element_identifiers=subelement_identifiers ) else: element = self.uploads[element_def["value"]].copy() element["name"] = element_identifier tags = element_def.get("attributes").get("tags") if tags: element["tags"] = tags.split(",") element_identifiers.append(element) return element_identifiers def __dictify_output_collections(self, submit_response): output_collections_dict = {} for output_collection in submit_response['output_collections']: output_collections_dict[output_collection.get("output_name")] = output_collection return output_collections_dict def __dictify_outputs(self, datasets_object): # Convert outputs list to a dictionary that can be accessed by # output_name so can be more flexible about ordering of outputs # but also allows fallback to legacy access as list mode. outputs_dict = OutputsDict() for output in datasets_object['outputs']: outputs_dict[output.get("output_name")] = output return outputs_dict def output_hid(self, output_data): return output_data['id'] def delete_history(self, history): self._delete(f"histories/{history}") def __job_ready(self, job_id, history_id=None): if job_id is None: raise ValueError("__job_ready passed empty job_id") try: return self._state_ready(job_id, error_msg="Job in error state.") except Exception: if VERBOSE_ERRORS and history_id is not None: self._summarize_history(history_id) raise def _summarize_history(self, history_id): if history_id is None: raise ValueError("_summarize_history passed empty history_id") print(f"Problem in history with id {history_id} - summary of history's datasets and jobs below.") try: history_contents = self.__contents(history_id) except Exception: print("*TEST FRAMEWORK FAILED TO FETCH HISTORY DETAILS*") return for history_content in history_contents: dataset = history_content print(ERROR_MESSAGE_DATASET_SEP) dataset_id = dataset.get('id', None) print(f"| {dataset['hid']} - {dataset['name']} (HID - NAME) ") if history_content['history_content_type'] == 'dataset_collection': history_contents_json = self._get(f"histories/{history_id}/contents/dataset_collections/{history_content['id']}").json() print(f"| Dataset Collection: {history_contents_json}") print("|") continue try: dataset_info = self._dataset_info(history_id, dataset_id) print("| Dataset State:") print(self.format_for_summary(dataset_info.get("state"), "Dataset state is unknown.")) print("| Dataset Blurb:") print(self.format_for_summary(dataset_info.get("misc_blurb", ""), "Dataset blurb was empty.")) print("| Dataset Info:") print(self.format_for_summary(dataset_info.get("misc_info", ""), "Dataset info is empty.")) print("| Peek:") print(self.format_for_summary(dataset_info.get("peek", ""), "Peek unavailable.")) except Exception: print("| *TEST FRAMEWORK ERROR FETCHING DATASET DETAILS*") try: provenance_info = self._dataset_provenance(history_id, dataset_id) print("| Dataset Job Standard Output:") print(self.format_for_summary(provenance_info.get("stdout", ""), "Standard output was empty.")) print("| Dataset Job Standard Error:") print(self.format_for_summary(provenance_info.get("stderr", ""), "Standard error was empty.")) except Exception: print("| *TEST FRAMEWORK ERROR FETCHING JOB DETAILS*") print("|") try: jobs_json = self._get(f"jobs?history_id={history_id}").json() for job_json in jobs_json: print(ERROR_MESSAGE_DATASET_SEP) print(f"| Job {job_json['id']}") print("| State: ") print(self.format_for_summary(job_json.get("state", ""), "Job state is unknown.")) print("| Update Time:") print(self.format_for_summary(job_json.get("update_time", ""), "Job update time is unknown.")) print("| Create Time:") print(self.format_for_summary(job_json.get("create_time", ""), "Job create time is unknown.")) print("|") print(ERROR_MESSAGE_DATASET_SEP) except Exception: print(ERROR_MESSAGE_DATASET_SEP) print("*TEST FRAMEWORK FAILED TO FETCH HISTORY JOBS*") print(ERROR_MESSAGE_DATASET_SEP) def format_for_summary(self, blob, empty_message, prefix="| "): contents = "\n".join(f"{prefix}{line.strip()}" for line in io.StringIO(blob).readlines() if line.rstrip("\n\r")) return contents or f"{prefix}*{empty_message}*" def _dataset_provenance(self, history_id, id): provenance = self._get(f"histories/{history_id}/contents/{id}/provenance").json() return provenance def _dataset_info(self, history_id, id): dataset_json = self._get(f"histories/{history_id}/contents/{id}").json() return dataset_json def __contents(self, history_id): history_contents_response = self._get(f"histories/{history_id}/contents") history_contents_response.raise_for_status() return history_contents_response.json() def _state_ready(self, job_id, error_msg): state_str = self.__get_job(job_id).json()['state'] if state_str == 'ok': return True elif state_str == 'error': job_json = self.get_job_stdio(job_id) raise Exception(f"{error_msg}. tool_id: {job_json['tool_id']}, exit_code: {job_json['exit_code']}, stderr: {job_json['stderr']}.") return None def __submit_tool(self, history_id, tool_id, tool_input, extra_data=None, files=None, tool_version=None): extra_data = extra_data or {} data = dict( history_id=history_id, tool_id=tool_id, inputs=dumps(tool_input), tool_version=tool_version, **extra_data ) return self._post("tools", files=files, data=data) def ensure_user_with_email(self, email, password=None): admin_key = self.master_api_key all_users_response = self._get('users', key=admin_key) try: all_users_response.raise_for_status() except requests.exceptions.HTTPError as e: raise Exception(f"Failed to verify user with email [{email}] exists - perhaps you're targetting the wrong Galaxy server or using an incorrect admin API key. HTTP error: {e}") all_users = all_users_response.json() try: test_user = [user for user in all_users if user["email"] == email][0] except IndexError: username = re.sub(r"[^a-z-\d]", '--', email.lower()) password = password or 'testpass' # If remote user middleware is enabled - this endpoint consumes # ``remote_user_email`` otherwise it requires ``email``, ``password`` # and ``username``. data = dict( remote_user_email=email, email=email, password=password, username=username, ) test_user = self._post('users', data, key=admin_key).json() return test_user def __test_data_downloader(self, tool_id, tool_version=None): def test_data_download(filename, mode='file'): return self.test_data_download(tool_id, filename, mode=mode, tool_version=tool_version) return test_data_download def __dataset_fetcher(self, history_id): def fetcher(hda_id, base_name=None): url = f"histories/{history_id}/contents/{hda_id}/display?raw=true" if base_name: url += f"&filename={base_name}" response = None for _ in range(self.download_attempts): response = self._get(url) if response.status_code == 500: print(f"Retrying failed download with status code {response.status_code}") time.sleep(self.download_sleep) continue else: break response.raise_for_status() return response.content return fetcher def api_key_header(self, key, admin, anon, headers): header = headers or {} if not anon: if not key: key = self.api_key if not admin else self.master_api_key header['x-api-key'] = key return header def _post(self, path, data=None, files=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, files=files, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.post(url, **kwd) def _delete(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.delete(url, **kwd) def _patch(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.patch(url, **kwd) def _put(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.put(url, **kwd) def _get(self, path, data=None, key=None, headers=None, admin=False, anon=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwargs = {} if self.cookies: kwargs['cookies'] = self.cookies # no data for GET return requests.get(url, params=data, headers=headers, timeout=util.DEFAULT_SOCKET_TIMEOUT, **kwargs) def get_api_url(self, path: str) -> str: if path.startswith("http"): return path elif path.startswith("/api/"): path = path[len("/api/"):] return urllib.parse.urljoin(f"{self.api_url}/", path) def _prepare_request_params(self, data=None, files=None, as_json: bool = False, params: dict = None, headers: dict = None): """Handle some Galaxy conventions and work around requests issues. This is admittedly kind of hacky, so the interface may change frequently - be careful on reuse. If ``as_json`` is True, use post payload using request's json parameter instead of the data parameter (i.e. assume the contents is a json-ified blob instead of form parameters with individual parameters json-ified if needed). requests doesn't allow files to be specified with the json parameter - so rewrite the parameters to handle that if as_json is True with specified files. """ params = params or {} data = data or {} # handle encoded files if files is None: # if not explicitly passed, check __files... convention used in tool testing # and API testing code files = data.get("__files", None) if files is not None: del data["__files"] # files doesn't really work with json, so dump the parameters # and do a normal POST with request's data parameter. if bool(files) and as_json: as_json = False new_items = {} for key, val in data.items(): if isinstance(val, dict) or isinstance(val, list): new_items[key] = dumps(val) data.update(new_items) kwd = { 'files': files, } if headers: kwd['headers'] = headers if as_json: kwd['json'] = data or None kwd['params'] = params else: data.update(params) kwd['data'] = data if self.cookies: kwd['cookies'] = self.cookies return kwd def ensure_tool_run_response_okay(submit_response_object, request_desc, inputs=None): if submit_response_object.status_code != 200: message = None dynamic_param_error = False try: err_response = submit_response_object.json() if "param_errors" in err_response: param_errors = err_response["param_errors"] if "dbkey" in param_errors: dbkey_err_obj = param_errors["dbkey"] dbkey_val = dbkey_err_obj.get("parameter_value") message = f"Invalid dbkey specified [{dbkey_val}]" for value in param_errors.values(): if isinstance(value, dict) and value.get("is_dynamic"): dynamic_param_error = True if message is None: message = err_response.get("err_msg") or None except Exception: # invalid JSON content. pass if message is None: message = f"Request to {request_desc} failed - invalid JSON content returned from Galaxy server [{submit_response_object.text}]" raise RunToolException(message, inputs, dynamic_param_error=dynamic_param_error) submit_response = submit_response_object.json() return submit_response def _are_tool_inputs_not_ready(submit_response): if submit_response.status_code != 400: return False try: submit_json = submit_response.json() return submit_json.get("err_code") == 400015 except Exception: return False class RunToolException(Exception): def __init__(self, message, inputs=None, dynamic_param_error=False): super().__init__(message) self.inputs = inputs self.dynamic_param_error = dynamic_param_error # Galaxy specific methods - rest of this can be used with arbitrary files and such. def verify_hid(filename, hda_id, attributes, test_data_downloader, hid="", dataset_fetcher=None, keep_outputs_dir=False): assert dataset_fetcher is not None def verify_extra_files(extra_files): _verify_extra_files_content(extra_files, hda_id, dataset_fetcher=dataset_fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=keep_outputs_dir) data = dataset_fetcher(hda_id) item_label = "" verify( item_label, data, attributes=attributes, filename=filename, get_filecontent=test_data_downloader, keep_outputs_dir=keep_outputs_dir, verify_extra_files=verify_extra_files, ) def verify_collection(output_collection_def, data_collection, verify_dataset): name = output_collection_def.name expected_collection_type = output_collection_def.collection_type if expected_collection_type: collection_type = data_collection["collection_type"] if expected_collection_type != collection_type: message = f"Output collection '{name}': expected to be of type [{expected_collection_type}], was of type [{collection_type}]." raise AssertionError(message) expected_element_count = output_collection_def.count if expected_element_count: actual_element_count = len(data_collection["elements"]) if expected_element_count != actual_element_count: message = f"Output collection '{name}': expected to have {expected_element_count} elements, but it had {actual_element_count}." raise AssertionError(message) def get_element(elements, id): for element in elements: if element["element_identifier"] == id: return element return False def verify_elements(element_objects, element_tests): expected_sort_order = {} eo_ids = [_["element_identifier"] for _ in element_objects] for element_identifier, element_test in element_tests.items(): if isinstance(element_test, dict): element_outfile, element_attrib = None, element_test else: element_outfile, element_attrib = element_test if 'expected_sort_order' in element_attrib: expected_sort_order[element_attrib['expected_sort_order']] = element_identifier element = get_element(element_objects, element_identifier) if not element: message = f"Output collection '{name}': failed to find identifier '{element_identifier}' in the tool generated elements {eo_ids}" raise AssertionError(message) element_type = element["element_type"] if element_type != "dataset_collection": verify_dataset(element, element_attrib, element_outfile) else: elements = element["object"]["elements"] verify_elements(elements, element_attrib.get("elements", {})) if len(expected_sort_order) > 0: generated_sort_order = [_["element_identifier"] for _ in element_objects] i = 0 for element_index in sorted(expected_sort_order.keys()): identifier = expected_sort_order[element_index] try: i = generated_sort_order[i:].index(identifier) + 1 except ValueError: message = f"Output collection '{name}': identifier '{element_identifier}' found out of order, expected order of {expected_sort_order} for the tool generated collection elements {eo_ids}" raise AssertionError(message) verify_elements(data_collection["elements"], output_collection_def.element_tests) def _verify_composite_datatype_file_content(file_name, hda_id, base_name=None, attributes=None, dataset_fetcher=None, test_data_downloader=None, keep_outputs_dir=False, mode='file'): assert dataset_fetcher is not None data = dataset_fetcher(hda_id, base_name) item_label = f"History item {hda_id}" try: verify( item_label, data, attributes=attributes, filename=file_name, get_filecontent=test_data_downloader, keep_outputs_dir=keep_outputs_dir, mode=mode, ) except AssertionError as err: errmsg = f'Composite file ({base_name}) of {item_label} different than expected, difference:\n' errmsg += util.unicodify(err) raise AssertionError(errmsg) def _verify_extra_files_content(extra_files, hda_id, dataset_fetcher, test_data_downloader, keep_outputs_dir): files_list = [] cleanup_directories = [] for extra_file_dict in extra_files: extra_file_type = extra_file_dict["type"] extra_file_name = extra_file_dict["name"] extra_file_attributes = extra_file_dict["attributes"] extra_file_value = extra_file_dict["value"] if extra_file_type == 'file': files_list.append((extra_file_name, extra_file_value, extra_file_attributes, extra_file_type)) elif extra_file_type == 'directory': extracted_path = test_data_downloader(extra_file_value, mode='directory') cleanup_directories.append(extracted_path) for root, _directories, files in util.path.safe_walk(extracted_path): for filename in files: filename = os.path.join(root, filename) filename = os.path.relpath(filename, extracted_path) files_list.append((filename, os.path.join(extracted_path, filename), extra_file_attributes, extra_file_type)) else: raise ValueError(f'unknown extra_files type: {extra_file_type}') try: for filename, filepath, attributes, extra_file_type in files_list: _verify_composite_datatype_file_content(filepath, hda_id, base_name=filename, attributes=attributes, dataset_fetcher=dataset_fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=keep_outputs_dir, mode=extra_file_type) finally: for path in cleanup_directories: shutil.rmtree(path) class NullClientTestConfig: def get_test_config(self, job_data): return None class DictClientTestConfig: def __init__(self, tools): self._tools = tools or {} def get_test_config(self, job_data): # TODO: allow short ids, allow versions below outer id instead of key concatenation. tool_id = job_data.get("tool_id") tool_version = job_data.get("tool_version") tool_test_config = None tool_version_test_config = None is_default = False if tool_id in self._tools: tool_test_config = self._tools[tool_id] if tool_test_config is None: tool_id = f"{tool_id}/{tool_version}" if tool_id in self._tools: tool_version_test_config = self._tools[tool_id] else: if tool_version in tool_test_config: tool_version_test_config = tool_test_config[tool_version] elif "default" in tool_test_config: tool_version_test_config = tool_test_config["default"] is_default = True if tool_version_test_config: test_index = job_data.get("test_index") if test_index in tool_version_test_config: return tool_version_test_config[test_index] elif str(test_index) in tool_version_test_config: return tool_version_test_config[str(test_index)] if 'default' in tool_version_test_config: return tool_version_test_config['default'] elif is_default: return tool_version_test_config return None def verify_tool(tool_id, galaxy_interactor, resource_parameters=None, register_job_data=None, test_index=0, tool_version=None, quiet=False, test_history=None, no_history_cleanup=False, publish_history=False, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_test_dicts=None, client_test_config=None, skip_with_reference_data=False, skip_on_dynamic_param_errors=False): if resource_parameters is None: resource_parameters = {} if client_test_config is None: client_test_config = NullClientTestConfig() tool_test_dicts = tool_test_dicts or galaxy_interactor.get_tool_tests(tool_id, tool_version=tool_version) tool_test_dict = tool_test_dicts[test_index] if "test_index" not in tool_test_dict: tool_test_dict["test_index"] = test_index if "tool_id" not in tool_test_dict: tool_test_dict["tool_id"] = tool_id if tool_version is None and "tool_version" in tool_test_dict: tool_version = tool_test_dict.get("tool_version") job_data = { "tool_id": tool_id, "tool_version": tool_version, "test_index": test_index, } client_config = client_test_config.get_test_config(job_data) skip_message = None if client_config is not None: job_data.update(client_config) skip_message = job_data.get("skip") if not skip_message and skip_with_reference_data: required_data_tables = tool_test_dict.get("required_data_tables") required_loc_files = tool_test_dict.get("required_loc_files") # TODO: actually hit the API and see if these tables are available. if required_data_tables: skip_message = f"Skipping test because of required data tables ({required_data_tables})" if required_loc_files: skip_message = f"Skipping test because of required loc files ({required_loc_files})" if skip_message: job_data["status"] = "skip" register_job_data(job_data) return tool_test_dict.setdefault('maxseconds', maxseconds) testdef = ToolTestDescription(tool_test_dict) _handle_def_errors(testdef) created_history = False if test_history is None: created_history = True history_name = f"Tool Test History for {tool_id}/{tool_version}-{test_index}" test_history = galaxy_interactor.new_history(history_name=history_name, publish_history=publish_history) # Upload data to test_history, run the tool and check the outputs - record # API input, job info, tool run exception, as well as exceptions related to # job output checking and register they with the test plugin so it can # record structured information. tool_inputs = None job_stdio = None job_output_exceptions = None tool_execution_exception = None input_staging_exception = None expected_failure_occurred = False begin_time = time.time() try: try: stage_data_in_history( galaxy_interactor, tool_id, testdef.test_data(), history=test_history, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version, ) except Exception as e: input_staging_exception = e raise try: tool_response = galaxy_interactor.run_tool(testdef, test_history, resource_parameters=resource_parameters) data_list, jobs, tool_inputs = tool_response.outputs, tool_response.jobs, tool_response.inputs data_collection_list = tool_response.output_collections except RunToolException as e: tool_inputs = e.inputs tool_execution_exception = e if not testdef.expect_failure: raise e else: expected_failure_occurred = True except Exception as e: tool_execution_exception = e raise e if not expected_failure_occurred: assert data_list or data_collection_list try: job_stdio = _verify_outputs(testdef, test_history, jobs, data_list, data_collection_list, galaxy_interactor, quiet=quiet) except JobOutputsError as e: job_stdio = e.job_stdio job_output_exceptions = e.output_exceptions raise e except Exception as e: job_output_exceptions = [e] raise e finally: if register_job_data is not None: end_time = time.time() job_data["time_seconds"] = end_time - begin_time if tool_inputs is not None: job_data["inputs"] = tool_inputs if job_stdio is not None: job_data["job"] = job_stdio status = "success" if job_output_exceptions: job_data["output_problems"] = [util.unicodify(_) for _ in job_output_exceptions] status = "failure" if tool_execution_exception: job_data["execution_problem"] = util.unicodify(tool_execution_exception) dynamic_param_error = getattr(tool_execution_exception, "dynamic_param_error", False) job_data["dynamic_param_error"] = dynamic_param_error status = "error" if not skip_on_dynamic_param_errors or not dynamic_param_error else "skip" if input_staging_exception: job_data["execution_problem"] = f"Input staging problem: {util.unicodify(input_staging_exception)}" status = "error" job_data["status"] = status register_job_data(job_data) if created_history and not no_history_cleanup: galaxy_interactor.delete_history(test_history) def _handle_def_errors(testdef): # If the test generation had an error, raise if testdef.error: if testdef.exception: if isinstance(testdef.exception, Exception): raise testdef.exception else: raise Exception(testdef.exception) else: raise Exception("Test parse failure") def _verify_outputs(testdef, history, jobs, data_list, data_collection_list, galaxy_interactor, quiet=False): assert len(jobs) == 1, "Test framework logic error, somehow tool test resulted in more than one job." job = jobs[0] maxseconds = testdef.maxseconds if testdef.num_outputs is not None: expected = testdef.num_outputs actual = len(data_list) + len(data_collection_list) if expected != actual: message = f"Incorrect number of outputs - expected {expected}, found {actual}: datasets {data_list} collections {data_collection_list}" raise Exception(message) found_exceptions = [] def register_exception(e): if not found_exceptions and not quiet: # Only print this stuff out once. for stream in ['stdout', 'stderr']: if stream in job_stdio: print(_format_stream(job_stdio[stream], stream=stream, format=True), file=sys.stderr) found_exceptions.append(e) if testdef.expect_failure: if testdef.outputs: raise Exception("Cannot specify outputs in a test expecting failure.") # Wait for the job to complete and register expections if the final # status was not what test was expecting. job_failed = False try: galaxy_interactor.wait_for_job(job['id'], history, maxseconds) except Exception as e: job_failed = True if not testdef.expect_failure: found_exceptions.append(e) job_stdio = galaxy_interactor.get_job_stdio(job['id']) if not job_failed and testdef.expect_failure: error = AssertionError("Expected job to fail but Galaxy indicated the job successfully completed.") register_exception(error) expect_exit_code = testdef.expect_exit_code if expect_exit_code is not None: exit_code = job_stdio["exit_code"] if str(expect_exit_code) != str(exit_code): error = AssertionError(f"Expected job to complete with exit code {expect_exit_code}, found {exit_code}") register_exception(error) for output_index, output_dict in enumerate(testdef.outputs): # Get the correct hid name = output_dict["name"] outfile = output_dict["value"] attributes = output_dict["attributes"] output_testdef = Bunch(name=name, outfile=outfile, attributes=attributes) try: output_data = data_list[name] except (TypeError, KeyError): # Legacy - fall back on ordered data list access if data_list is # just a list (case with twill variant or if output changes its # name). if hasattr(data_list, "values"): output_data = list(data_list.values())[output_index] else: output_data = data_list[len(data_list) - len(testdef.outputs) + output_index] assert output_data is not None try: galaxy_interactor.verify_output(history, jobs, output_data, output_testdef=output_testdef, tool_id=job['tool_id'], maxseconds=maxseconds, tool_version=testdef.tool_version) except Exception as e: register_exception(e) other_checks = { "command_line": "Command produced by the job", "command_version": "Tool version indicated during job execution", "stdout": "Standard output of the job", "stderr": "Standard error of the job", } # TODO: Only hack the stdio like this for older profile, for newer tool profiles # add some syntax for asserting job messages maybe - or just drop this because exit # code and regex on stdio can be tested directly - so this is really testing Galaxy # core handling more than the tool. job_messages = job_stdio.get("job_messages") or [] stdout_prefix = "" stderr_prefix = "" for job_message in job_messages: message_type = job_message.get("type") if message_type == "regex" and job_message.get("stream") == "stderr": stderr_prefix += f"{job_message.get('desc') or ''}\n" elif message_type == "regex" and job_message.get("stream") == "stdout": stdout_prefix += f"{job_message.get('desc') or ''}\n" elif message_type == "exit_code": stderr_prefix += f"{job_message.get('desc') or ''}\n" else: raise Exception(f"Unknown job message type [{message_type}] in [{job_message}]") for what, description in other_checks.items(): if getattr(testdef, what, None) is not None: try: raw_data = job_stdio[what] assertions = getattr(testdef, what) if what == "stdout": data = stdout_prefix + raw_data elif what == "stderr": data = stderr_prefix + raw_data else: data = raw_data verify_assertions(data, assertions) except AssertionError as err: errmsg = f'{description} different than expected\n' errmsg += util.unicodify(err) register_exception(AssertionError(errmsg)) for output_collection_def in testdef.output_collections: try: name = output_collection_def.name # TODO: data_collection_list is clearly a bad name for dictionary. if name not in data_collection_list: message = f"Failed to find output [{name}], tool outputs include [{','.join(data_collection_list.keys())}]" raise AssertionError(message) # Data collection returned from submission, elements may have been populated after # the job completed so re-hit the API for more information. data_collection_id = data_collection_list[name]["id"] galaxy_interactor.verify_output_collection(output_collection_def, data_collection_id, history, job['tool_id']) except Exception as e: register_exception(e) if found_exceptions and not testdef.expect_test_failure: raise JobOutputsError(found_exceptions, job_stdio) else: return job_stdio def _format_stream(output, stream, format): output = output or '' if format: msg = f"---------------------- >> begin tool {stream} << -----------------------\n" msg += f"{output}\n" msg += f"----------------------- >> end tool {stream} << ------------------------\n" else: msg = output return msg class JobOutputsError(AssertionError): def __init__(self, output_exceptions, job_stdio): big_message = "\n".join(map(util.unicodify, output_exceptions)) super().__init__(big_message) self.job_stdio = job_stdio self.output_exceptions = output_exceptions class ToolTestDescription: """ Encapsulates information about a tool test, and allows creation of a dynamic TestCase class (the unittest framework is very class oriented, doing dynamic tests in this way allows better integration) """ def __init__(self, processed_test_dict): assert "test_index" in processed_test_dict, "Invalid processed test description, must have a 'test_index' for naming, etc.." test_index = processed_test_dict["test_index"] name = processed_test_dict.get('name', f'Test-{test_index + 1}') maxseconds = processed_test_dict.get('maxseconds', DEFAULT_TOOL_TEST_WAIT) if maxseconds is not None: maxseconds = int(maxseconds) self.test_index = test_index assert "tool_id" in processed_test_dict, "Invalid processed test description, must have a 'tool_id' for naming, etc.." self.tool_id = processed_test_dict["tool_id"] self.tool_version = processed_test_dict.get("tool_version") self.name = name self.maxseconds = maxseconds self.required_files = processed_test_dict.get("required_files", []) self.required_data_tables = processed_test_dict.get("required_data_tables", []) self.required_loc_files = processed_test_dict.get("required_loc_files", []) inputs = processed_test_dict.get("inputs", {}) loaded_inputs = {} for key, value in inputs.items(): if isinstance(value, dict) and value.get("model_class"): loaded_inputs[key] = TestCollectionDef.from_dict(value) else: loaded_inputs[key] = value self.inputs = loaded_inputs self.outputs = processed_test_dict.get("outputs", []) self.num_outputs = processed_test_dict.get("num_outputs", None) self.error = processed_test_dict.get("error", False) self.exception = processed_test_dict.get("exception", None) self.output_collections = [TestCollectionOutputDef.from_dict(d) for d in processed_test_dict.get("output_collections", [])] self.command_line = processed_test_dict.get("command_line", None) self.command_version = processed_test_dict.get("command_version", None) self.stdout = processed_test_dict.get("stdout", None) self.stderr = processed_test_dict.get("stderr", None) self.expect_exit_code = processed_test_dict.get("expect_exit_code", None) self.expect_failure = processed_test_dict.get("expect_failure", False) self.expect_test_failure = processed_test_dict.get("expect_test_failure", False) def test_data(self): """ Iterator over metadata representing the required files for upload. """ return test_data_iter(self.required_files) def to_dict(self): inputs_dict = {} for key, value in self.inputs.items(): if hasattr(value, "to_dict"): inputs_dict[key] = value.to_dict() else: inputs_dict[key] = value return { "inputs": inputs_dict, "outputs": self.outputs, "output_collections": [_.to_dict() for _ in self.output_collections], "num_outputs": self.num_outputs, "command_line": self.command_line, "command_version": self.command_version, "stdout": self.stdout, "stderr": self.stderr, "expect_exit_code": self.expect_exit_code, "expect_failure": self.expect_failure, "expect_test_failure": self.expect_test_failure, "name": self.name, "test_index": self.test_index, "tool_id": self.tool_id, "tool_version": self.tool_version, "required_files": self.required_files, "required_data_tables": self.required_data_tables, "required_loc_files": self.required_loc_files, "error": self.error, "exception": self.exception, } @nottest def test_data_iter(required_files): for fname, extra in required_files: data_dict = dict( fname=fname, metadata=extra.get('metadata', {}), composite_data=extra.get('composite_data', []), ftype=extra.get('ftype', DEFAULT_FTYPE), dbkey=extra.get('dbkey', DEFAULT_DBKEY), ) edit_attributes = extra.get('edit_attributes', []) # currently only renaming is supported for edit_att in edit_attributes: if edit_att.get('type', None) == 'name': new_name = edit_att.get('value', None) assert new_name, 'You must supply the new dataset name as the value tag of the edit_attributes tag' data_dict['name'] = new_name else: raise Exception(f"edit_attributes type ({edit_att.get('type', None)}) is unimplemented") yield data_dict
[]
[]
[ "GALAXY_TEST_DEFAULT_DBKEY", "GALAXY_TEST_VERBOSE_ERRORS", "GALAXY_TEST_UPLOAD_ASYNC", "GALAXY_TEST_DEFAULT_WAIT" ]
[]
["GALAXY_TEST_DEFAULT_DBKEY", "GALAXY_TEST_VERBOSE_ERRORS", "GALAXY_TEST_UPLOAD_ASYNC", "GALAXY_TEST_DEFAULT_WAIT"]
python
4
0
src/pbox/src/main/java/me/pbox/env/Environment.java
package me.pbox.env; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * @author Mike Mirzayanov ([email protected]) */ public class Environment { private static final String SESSION = String.valueOf(RandomUtils.nextInt(10000, 99999)); private static final String VERSION = "1.0"; private static final Properties PROPERTIES = new Properties(); private static Map<String, String> map = null; private static Map<String, String> lowerCaseMap = null; public static Map<String, String> getMap() { if (map == null) { map = new HashMap<>(System.getenv()); String programFiles = System.getenv("ProgramFiles").replace(" (x86)", ""); if (new File(programFiles).isDirectory()) { map.put("ProgramFiles", programFiles); } String programFilesx86 = programFiles + " (x86)"; if (new File(programFilesx86).isDirectory()) { map.put("ProgramFiles(x86)", programFilesx86); } lowerCaseMap = new HashMap<>(); for (Map.Entry<String, String> entry : map.entrySet()) { lowerCaseMap.put(entry.getKey().toLowerCase(), entry.getValue()); } } return Collections.unmodifiableMap(map); } public static String get(String item) { if (getMap() != null) { return lowerCaseMap.get(item.toLowerCase()); } else { throw new RuntimeException("Can't get environment variables map."); } } public static String getPboxSiteUrl() { return PROPERTIES.getProperty("pbox.site.url"); } public static String getVersion() { return VERSION; } public static File getPboxXml(File parent) { return new File(parent, "pbox.xml"); } public static File getPboxHomeAsFile() { return new File(getPboxHome()); } private static String getPboxHome() { if (StringUtils.isNoneBlank(System.getProperty("pbox.home"))) { return System.getProperty("pbox.home").trim(); } if (StringUtils.isNoneBlank(System.getenv("PBOX_HOME"))) { return System.getenv("PBOX_HOME").trim(); } if (StringUtils.isNoneBlank(System.getenv("ALLUSERSPROFILE"))) { return System.getenv("ALLUSERSPROFILE").trim() + "\\" + "pbox"; } if (StringUtils.isNoneBlank(System.getenv("SystemDrive"))) { return System.getenv("SystemDrive").trim() + "\\" + "pbox"; } return "/pbox"; } public static File getPboxBinAsFile() { return new File(getPboxBin()); } public static String getPboxBin() { return getPboxHome() + "\\bin"; } public static File getPboxRegistryAsFile() { return new File(getPboxRegistry()); } public static String getPboxRegistry() { return getPboxHome() + "\\registry"; } public static File getPboxTempAsFile() { return new File(getPboxTemp()); } public static String getPboxTemp() { String temp = getPboxHome() + "\\temp\\" + SESSION; //noinspection ResultOfMethodCallIgnored new File(temp).mkdirs(); return temp; } public static File getPboxMsiDirectory() { File temp = new File(getPboxHome() + "\\temp\\msis"); //noinspection ResultOfMethodCallIgnored temp.mkdirs(); return temp; } public static String getBin(String tool) { if (tool.toLowerCase().endsWith(".exe")) { throw new IllegalArgumentException("Expected tool name without extension, but got '" + tool + "'."); } return "\"" + getPboxBin() + "\\" + tool + ".exe\""; } public static String getArch() { boolean x64; if (System.getProperty("os.name").contains("Windows")) { x64 = Environment.get("ProgramFiles(x86)") != null; } else { x64 = System.getProperty("os.arch").contains("64"); } return x64 ? "64" : "32"; } static { InputStream resourceInputStream = Environment.class.getResourceAsStream("/bin.lst"); try { String resourceList = IOUtils.toString(resourceInputStream); String[] resources = resourceList.split("[\r\n]+"); for (String resource : resources) { if (StringUtils.isNoneBlank(resource)) { //noinspection ResultOfMethodCallIgnored getPboxBinAsFile().mkdirs(); File targetResourceFile = new File(getPboxBinAsFile(), resource); if (!targetResourceFile.isFile() || targetResourceFile.length() == 0) { try (InputStream inputStream = Environment.class.getResourceAsStream("/bin/" + resource)) { FileOutputStream outputStream = new FileOutputStream(targetResourceFile); IOUtils.copy(inputStream, outputStream); outputStream.close(); } } } } } catch (IOException e) { throw new RuntimeException("Can't process resource /bin.lst.", e); } finally { IOUtils.closeQuietly(resourceInputStream); } } static { InputStream resourceInputStream = Environment.class.getResourceAsStream("/pbox.properties"); try { PROPERTIES.load(new InputStreamReader(resourceInputStream, "UTF-8")); } catch (IOException e) { throw new RuntimeException("Can't process resource /pbox.properties.", e); } finally { IOUtils.closeQuietly(resourceInputStream); } } }
[ "\"ProgramFiles\"", "\"PBOX_HOME\"", "\"PBOX_HOME\"", "\"ALLUSERSPROFILE\"", "\"ALLUSERSPROFILE\"", "\"SystemDrive\"", "\"SystemDrive\"" ]
[]
[ "PBOX_HOME", "ProgramFiles", "ALLUSERSPROFILE", "SystemDrive" ]
[]
["PBOX_HOME", "ProgramFiles", "ALLUSERSPROFILE", "SystemDrive"]
java
4
0
cmd/xenia/commands/test.go
// Copyright (c) 2016-present Xenia, Inc. All Rights Reserved. // See License.txt for license information. package commands import ( "bufio" "fmt" "os" "os/exec" "os/signal" "syscall" "github.com/xzl8028/xenia-server/api4" "github.com/xzl8028/xenia-server/model" "github.com/xzl8028/xenia-server/utils" "github.com/xzl8028/xenia-server/wsapi" "github.com/spf13/cobra" ) var TestCmd = &cobra.Command{ Use: "test", Short: "Testing Commands", Hidden: true, } var RunWebClientTestsCmd = &cobra.Command{ Use: "web_client_tests", Short: "Run the web client tests", RunE: webClientTestsCmdF, } var RunServerForWebClientTestsCmd = &cobra.Command{ Use: "web_client_tests_server", Short: "Run the server configured for running the web client tests against it", RunE: serverForWebClientTestsCmdF, } func init() { TestCmd.AddCommand( RunWebClientTestsCmd, RunServerForWebClientTestsCmd, ) RootCmd.AddCommand(TestCmd) } func webClientTestsCmdF(command *cobra.Command, args []string) error { a, err := InitDBCommandContextCobra(command) if err != nil { return err } defer a.Shutdown() utils.InitTranslations(a.Config().LocalizationSettings) serverErr := a.Srv.Start() if serverErr != nil { return serverErr } api4.Init(a, a.Srv.AppOptions, a.Srv.Router) wsapi.Init(a, a.Srv.WebSocketRouter) a.UpdateConfig(setupClientTests) runWebClientTests() return nil } func serverForWebClientTestsCmdF(command *cobra.Command, args []string) error { a, err := InitDBCommandContextCobra(command) if err != nil { return err } defer a.Shutdown() utils.InitTranslations(a.Config().LocalizationSettings) serverErr := a.Srv.Start() if serverErr != nil { return serverErr } api4.Init(a, a.Srv.AppOptions, a.Srv.Router) wsapi.Init(a, a.Srv.WebSocketRouter) a.UpdateConfig(setupClientTests) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-c return nil } func setupClientTests(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true *cfg.ServiceSettings.EnableCommands = false *cfg.ServiceSettings.EnableCustomEmoji = true *cfg.ServiceSettings.EnableIncomingWebhooks = false *cfg.ServiceSettings.EnableOutgoingWebhooks = false } func executeTestCommand(command *exec.Cmd) { cmdOutPipe, err := command.StdoutPipe() if err != nil { CommandPrintErrorln("Failed to run tests") os.Exit(1) return } cmdErrOutPipe, err := command.StderrPipe() if err != nil { CommandPrintErrorln("Failed to run tests") os.Exit(1) return } cmdOutReader := bufio.NewScanner(cmdOutPipe) cmdErrOutReader := bufio.NewScanner(cmdErrOutPipe) go func() { for cmdOutReader.Scan() { fmt.Println(cmdOutReader.Text()) } }() go func() { for cmdErrOutReader.Scan() { fmt.Println(cmdErrOutReader.Text()) } }() if err := command.Run(); err != nil { CommandPrintErrorln("Client Tests failed") os.Exit(1) return } } func runWebClientTests() { if webappDir := os.Getenv("WEBAPP_DIR"); webappDir != "" { os.Chdir(webappDir) } else { os.Chdir("../xenia-webapp") } cmd := exec.Command("npm", "test") executeTestCommand(cmd) }
[ "\"WEBAPP_DIR\"" ]
[]
[ "WEBAPP_DIR" ]
[]
["WEBAPP_DIR"]
go
1
0
rateLimit_test.go
package imgur import ( "net/http" "os" "testing" ) func TestRateLimitImgurSimulated(t *testing.T) { httpC, server := testHTTPClientJSON("{\"success\": true, \"status\": 200 }") defer server.Close() client := createClient(httpC, "testing", "") rl, err := client.GetRateLimit() if err != nil { t.Errorf("GetRateLimit() failed with error: %v", err) t.FailNow() } if rl.ClientLimit != 40 || rl.UserLimit != 10 || rl.UserRemaining != 2 || rl.ClientRemaining != 5 { client.Log.Debugf("Found ClientLimit: %v and UserLimit: %v", rl.ClientLimit, rl.UserLimit) t.Error("Client/User limits are wrong. Probably something broken. Or IMGUR changed their limits. Or you are not using a free account for testing. Sorry. No real good way to test this.") } } func TestRateLimitRealRapidAPI(t *testing.T) { key := os.Getenv("IMGURCLIENTID") if key == "" { t.Skip("IMGURCLIENTID environment variable not set.") } RapidAPIKey := os.Getenv("RapidAPIKEY") if RapidAPIKey == "" { t.Skip("RapidAPIKEY environment variable not set.") } client := createClient(new(http.Client), key, RapidAPIKey) rl, err := client.GetRateLimit() if err != nil { t.Errorf("GetRateLimit() failed with error: %v", err) t.FailNow() } // There seem to be not rate limites when using the paid API if rl.ClientLimit != 0 || rl.UserLimit != 0 { client.Log.Debugf("Found ClientLimit: %v and UserLimit: %v", rl.ClientLimit, rl.UserLimit) t.Error("Client/User limits are wrong. Probably something broken. Or IMGUR changed their limits. Or you are using a free account for testing. Sorry. No real good way to test this.") } } func TestRateLimitRealImgur(t *testing.T) { key := os.Getenv("IMGURCLIENTID") if key == "" { t.Skip("IMGURCLIENTID environment variable not set.") } client := createClient(new(http.Client), key, "") rl, err := client.GetRateLimit() if err != nil { t.Errorf("GetRateLimit() failed with error: %v", err) t.FailNow() } if rl.ClientLimit != 12500 || rl.UserLimit != 500 { client.Log.Debugf("Found ClientLimit: %v and UserLimit: %v", rl.ClientLimit, rl.UserLimit) t.Error("Client/User limits are wrong. Probably something broken. Or IMGUR changed their limits. Or you are not using a free account for testing. Sorry. No real good way to test this.") } }
[ "\"IMGURCLIENTID\"", "\"RapidAPIKEY\"", "\"IMGURCLIENTID\"" ]
[]
[ "IMGURCLIENTID", "RapidAPIKEY" ]
[]
["IMGURCLIENTID", "RapidAPIKEY"]
go
2
0
modules/nltk_contrib/coref/tag.py
import os import re import subprocess try: from cStringIO import StringIO except: from StringIO import StringIO from nltk.util import LazyMap, LazyConcatenation from nltk.internals import find_binary, java from nltk.tag import TaggerI from nltk_contrib.coref import CorpusReaderDecorator class TaggerCorpusReader(CorpusReaderDecorator): """ A C{CorpusReaderDecorator} that adds tagger functionality to an arbitrary C{CorpusReader}. """ def __init__(self, reader, **kwargs): """ @return: a corpus reader @rtype: C{TaggerCorpusReader} @param reader: the corpus reader to decorate @type reader: C{CorpusReader} @kwparam tagger: a tagger object to defer tagging to @type tagger: C{TaggerI} """ self._tagger = kwargs.get('tagger') CorpusReaderDecorator.__init__(self, reader, **kwargs) def tagged_sents(self): return LazyMap(self._tagger.tag, self.sents()) def tagged_words(self): return LazyConcatenation(LazyMap(self._tagger.tag, self.sents())) def tagger(self): return self._tagger class MXPostTaggerCorpusReader(TaggerCorpusReader): def __init__(self, reader, **kwargs): kwargs['tagger'] = MXPostTagger() TaggerCorpusReader.__init__(self, reader, **kwargs) def tagged_sents(self): sents = self.sents() batch_indices = range(len(sents) / 1024 + 1) return LazyConcatenation(LazyMap(lambda i: self._tagger.batch_tag(sents[i * 1024: i * 1024 + 1024]), batch_indices)) class MXPostTagger(TaggerI): def tag(self, tokens): return self.batch_tag([tokens])[0] def batch_tag(self, sents): return mxpost_tag(sents) _mxpost_home = None _mxpost_classpath = None def config_mxpost(mxpost_home=None): global _mxpost_classpath, _mxpost_home classpath = os.environ.get('CLASSPATH', '').split(':') mxpost_jar = filter(lambda c: c.endswith('mxpost.jar'), classpath) if mxpost_jar: _mxpost_home = os.path.dirname(mxpost_jar[0]) _mxpost_classpath = mxpost_jar[0] elif os.environ.get('MXPOST'): _mxpost_home = os.environ.get('MXPOST') _mxpost_classpath = '%s/mxpost.jar' % os.environ.get('MXPOST') elif os.environ.get('MXPOST_HOME'): _mxpost_home = os.environ.get('MXPOST_HOME') _mxpost_classpath = '%s/mxpost.jar' % os.environ.get('MXPOST_HOME') elif os.path.exists('/usr/local/mxpost/mxpost.jar'): _mxpost_home = '/usr/local/mxpost' _mxpost_classpath = '/usr/local/mxpost/mxpost.jar' else: _mxpost_home = None _mxpost_classpath = None raise Exception, "can't find mxpost.jar" def call_mxpost(classpath=None, stdin=None, stdout=None, stderr=None, blocking=False): if not classpath: config_mxpost() if not classpath: classpath = _mxpost_classpath elif 'mxpost.jar' not in classpath: classpath += ':%s' % _mxpost_classpath cmd = ['tagger.TestTagger', '%s/%s' % (_mxpost_home, 'wsj-02-21.mxpost')] return java(cmd, classpath, stdin, stdout, stderr, blocking) _MXPOST_OUTPUT_RE = \ re.compile(r'^\s*(?P<word>\S+)\_(?P<tag>\S+)\s*$') def mxpost_parse_output(mxpost_output): result = [] mxpost_output = mxpost_output.strip() for sent in filter(None, mxpost_output.split('\n')): tokens = filter(None, re.split(r'\s+', sent)) if tokens: result.append([]) for token in tokens: m = _MXPOST_OUTPUT_RE.match(token) if not m: raise Exception, "invalid mxpost tag pattern: %s, %s" % (token, tokens) word = m.group('word') tag = m.group('tag') result[-1].append((word, tag)) return result def mxpost_tag(sents, **kwargs): p = call_mxpost(stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = \ p.communicate('\n'.join([' '.join(sent) for sent in sents])) rc = p.returncode if rc != 0: raise Exception, 'exited with non-zero status %s' % rc if kwargs.get('verbose'): print 'warning: %s' % stderr return mxpost_parse_output(stdout)
[]
[]
[ "MXPOST", "CLASSPATH", "MXPOST_HOME" ]
[]
["MXPOST", "CLASSPATH", "MXPOST_HOME"]
python
3
0
deep_t2i/trainer_GAN.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/04b_trainer_GAN.ipynb (unless otherwise specified). __all__ = ['AnimeHeadsTrainer', 'BirdsTrainer'] # Cell import time from tqdm.auto import tqdm import torch import torch.nn as nn import torch.optim as optim from torch import autograd from kornia.augmentation import RandomHorizontalFlip, RandomCrop from kornia.geometry.transform import resize from fastcore.all import * from .data_anime_heads import Datasets as AnimeHeadsDatasets, DataLoaders as AnimeHeadsDataLoaders from .data_birds import Datasets as BirdsDatasets, DataLoaders as BirdsDataLoaders from .model import RnnEncoder, CnnEncoder, get_pretrained_DAMSM, Anime_G, Anime_D, Birds_G, Birds_D from .trainer_DAMSM import compute_sent_loss, compute_word_loss from .torch_utils import * # Cell import os if os.getenv('COLAB_TPU_ADDR'): import torch_xla import torch_xla.core.xla_model as xm # Internal Cell bce_loss = nn.BCEWithLogitsLoss() random_hflip = RandomHorizontalFlip().requires_grad_(False).eval() random_crop = RandomCrop((256, 256)).requires_grad_(False).eval() # Internal Cell def compute_gradient_penalty(d, true_imgs, fake_imgs, sent_emb): bs = true_imgs[0].shape[0] device = true_imgs[0].device alpha = torch.rand(bs, 1, 1, 1, device=device) interpolates = [(alpha * true_img.detach() + ((1 - alpha) * fake_img.detach())).requires_grad_(True) for true_img, fake_img in zip(true_imgs, fake_imgs)] uncond_logit, cond_logit = d(interpolates, sent_emb) # (bs, 1), (bs, 1) uncond_grads = autograd.grad( outputs=uncond_logit, inputs=interpolates, grad_outputs=torch.ones_like(uncond_logit), create_graph=True, retain_graph=True, only_inputs=True, ) uncond_gps = [] for uncond_grad in uncond_grads: uncond_grad = uncond_grad.contiguous().view(uncond_grad.size(0), -1) uncond_gp = ((uncond_grad.norm(2, dim=1) - 1) ** 2).mean() uncond_gps.append(uncond_gp) uncond_gp = torch.stack(uncond_gps).mean() cond_grads = autograd.grad( outputs=cond_logit, inputs=interpolates, grad_outputs=torch.ones_like(cond_logit), create_graph=True, retain_graph=True, only_inputs=True, ) cond_gps = [] for cond_grad in cond_grads: cond_grad = cond_grad.contiguous().view(cond_grad.size(0), -1) cond_gp = ((cond_grad.norm(2, dim=1) - 1) ** 2).mean() cond_gps.append(cond_gp) cond_gp = torch.stack(cond_gps).mean() return uncond_gp, cond_gp # Internal Cell def compute_d_loss(d, fake_imgs, true_imgs, sent_emb, gp_lambda=None): fake_imgs = detach(fake_imgs) bs = sent_emb.shape[0] device = sent_emb.device ones = torch.ones((bs, 1), device=device) zeros = torch.zeros((bs, 1), device=device) false_sent_emb = torch.cat([sent_emb[bs//2:], sent_emb[:bs//2]]) true_sent_code = d.get_sent_code(true_imgs) fake_sent_code = d.get_sent_code(fake_imgs) uncond_true_logit = d.uncond_cls(true_sent_code) # (bs, 1) uncond_fake_logit = d.uncond_cls(fake_sent_code) cond_tt_logit = d.cond_cls(true_sent_code, sent_emb) cond_tf_logit = d.cond_cls(true_sent_code, false_sent_emb) cond_ft_logit = d.cond_cls(fake_sent_code, sent_emb) cond_ff_logit = d.cond_cls(fake_sent_code, false_sent_emb) uncond_true_loss = bce_loss(uncond_true_logit, ones) uncond_fake_loss = bce_loss(uncond_fake_logit, zeros) cond_tt_loss = bce_loss(cond_tt_logit, ones) cond_tf_loss = bce_loss(cond_tf_logit, zeros) cond_ft_loss = bce_loss(cond_ft_logit, zeros) cond_ff_loss = bce_loss(cond_ff_logit, zeros) # loss = (uncond_true_loss+cond_tt_loss)/2. + (uncond_fake_loss+cond_ft_loss+cond_tf_loss)/3. loss = (uncond_true_loss+uncond_fake_loss) + (cond_tt_loss+(cond_tf_loss+cond_ft_loss+cond_ff_loss)/3) if gp_lambda: uncond_gp, cond_gp = compute_gradient_penalty(d, true_imgs, fake_imgs, sent_emb) uncond_gp_loss = uncond_gp*gp_lambda cond_gp_loss = cond_gp*gp_lambda loss += uncond_gp_loss+cond_gp_loss return loss # Internal Cell def compute_g_loss( d_net, fake_imgs, sent_emb, cnn_code, word_features, word_emb, cap_len, gamma1=4.0, gamma2=5.0, gamma3=10.0, smooth_lambda=2.0, ): bs = fake_imgs[0].shape[0] device = fake_imgs[0].device ones = torch.ones((bs, 1), device=device) zeros = torch.zeros((bs, 1), device=device) # loss from discriminator uncond_logit, cond_logit = d_net(fake_imgs, sent_emb) d_loss = bce_loss(uncond_logit, ones) + bce_loss(cond_logit, ones) # loss from DAMSM s_loss0, s_loss1 = compute_sent_loss(cnn_code, sent_emb, gamma3=gamma3) w_loss0, w_loss1, attn_maps = compute_word_loss(word_features, word_emb, cap_len, gamma1=gamma1, gamma2=gamma2, gamma3=gamma3) damsm_loss = (w_loss0+w_loss1)*smooth_lambda + (s_loss0+s_loss1)*smooth_lambda return d_loss + damsm_loss # Internal Cell @torch.no_grad() def update_average(tgt, src, decay): """ update the model_target using exponential moving averages :param tgt: target model :param src: source model :param decay: value of decay :return: None (updates the target model) """ src_dict = src.state_dict() tgt_dict = tgt.state_dict() param_names = [name for name, param in src.named_parameters()] for key in src_dict: ## Only use ema in parameters, others are just copy if key in param_names: tgt_dict[key].data.copy_(tgt_dict[key].data * decay + src_dict[key].data * (1 - decay)) else: tgt_dict[key].data.copy_(src_dict[key].data) # Cell class AnimeHeadsTrainer(): def __init__( self, data_dir, bs, data_pct=1, g_lr=1e-3, d_lr=1e-3, device='cpu', pretrained_damsm_path: Path=None, smooth_lambda = 2.0, noise_sz=100, ): super().__init__() self.smooth_lambda = smooth_lambda self.noise_sz = noise_sz self.device = torch.device(device) self.normalizer = Normalizer(device=self.device) dsets = AnimeHeadsDatasets(data_dir, pct=data_pct, valid_pct=0) self.dls = AnimeHeadsDataLoaders(dsets, bs) if pretrained_damsm_path is not None: self.rnn_encoder, self.cnn_encoder, self.vocab_sz, self.emb_sz, self.pad_id, self.rnn_layers, self.rnn_drop_p, self.gamma1, self.gamma2, self.gamma3 = get_pretrained_DAMSM(pretrained_damsm_path, device=self.device) self.rnn_encoder = self.rnn_encoder.requires_grad_(False).eval() self.cnn_encoder = self.cnn_encoder.requires_grad_(False).eval() assert dsets.train.tokenizer.vocab_sz==self.vocab_sz and dsets.train.tokenizer.pad_id==self.pad_id else: self.vocab_sz = dsets.train.tokenizer.vocab_sz self.emb_sz = 10 self.pad_id = dsets.train.tokenizer.pad_id self.rnn_layers = 2 self.rnn_drop_p = 0.5 self.gamma1 = 4.0 self.gamma2 = 5.0 self.gamma3 = 10.0 self.rnn_encoder = RnnEncoder(self.vocab_sz, self.emb_sz, self.pad_id, n_layers=self.rnn_layers, drop_p=self.rnn_drop_p).requires_grad_(False).eval().to(device) self.cnn_encoder = CnnEncoder(self.emb_sz).requires_grad_(False).eval().to(device) self.g_net = Anime_G(self.emb_sz, self.noise_sz).to(self.device) self.g_shadow = Anime_G(self.emb_sz, self.noise_sz).to(self.device) self.g_shadow.load_state_dict(self.g_net.state_dict()) self.d_net = Anime_D(self.emb_sz).to(self.device) self.optim_g = optim.Adam(self.g_net.parameters(), lr=g_lr, betas=(0, 0.999)) self.optim_d = optim.Adam(self.d_net.parameters(), lr=d_lr, betas=(0, 0.999)) def after_batch_tfm(self, cap, cap_len, img): "cap: (bs, 2), cap_len: (bs,), img: (bs, 64, 64, 3)" img64 = img.permute(0, 3, 1, 2).float() # (bs, 3, 64, 64) img64 = random_hflip(img64) img4 = resize(img64, size=(4, 4)) img8 = resize(img64, size=(8, 8)) img16 = resize(img64, size=(16, 16)) img32 = resize(img64, size=(32, 32)) img4 = self.normalizer.encode(img4) # (bs, 3, 4, 4) img8 = self.normalizer.encode(img8) # (bs, 3, 8, 8) img16 = self.normalizer.encode(img16) # (bs, 3, 16, 16) img32 = self.normalizer.encode(img32) # (bs, 3, 32, 32) img64 = self.normalizer.encode(img64) # (bs, 3, 64, 64) return cap, cap_len, (img64, img32, img16, img8, img4) # Cell class BirdsTrainer(): def __init__( self, data_dir, bs, data_pct=1, g_lr=1e-3, d_lr=1e-3, device='cpu', pretrained_damsm_path: Path=None, smooth_lambda=2.0, noise_sz=100, ): super().__init__() self.smooth_lambda = smooth_lambda self.noise_sz = noise_sz self.device = torch.device(device) self.normalizer = Normalizer(device=self.device) dsets = BirdsDatasets(data_dir, pct=data_pct) self.dls = BirdsDataLoaders(dsets, bs) if pretrained_damsm_path is not None: self.rnn_encoder, self.cnn_encoder, self.vocab_sz, self.emb_sz, self.pad_id, self.rnn_layers, self.rnn_drop_p, self.gamma1, self.gamma2, self.gamma3 = get_pretrained_DAMSM(pretrained_damsm_path, device=self.device) self.rnn_encoder = self.rnn_encoder.requires_grad_(False).eval() self.cnn_encoder = self.cnn_encoder.requires_grad_(False).eval() assert dsets.train.tokenizer.vocab_sz==self.vocab_sz and dsets.train.tokenizer.pad_id==self.pad_id else: self.vocab_sz = dsets.train.tokenizer.vocab_sz self.emb_sz = 256 self.pad_id = dsets.train.tokenizer.pad_id self.rnn_layers = 2 self.rnn_drop_p = 0.5 self.gamma1 = 4.0 self.gamma2 = 5.0 self.gamma3 = 10.0 self.rnn_encoder = RnnEncoder(self.vocab_sz, self.emb_sz, self.pad_id, n_layers=self.rnn_layers, drop_p=self.rnn_drop_p).requires_grad_(False).eval().to(device) self.cnn_encoder = CnnEncoder(self.emb_sz).requires_grad_(False).eval().to(device) self.g_net = Birds_G(self.emb_sz, self.noise_sz).to(self.device) self.g_shadow = Birds_G(self.emb_sz, self.noise_sz).to(self.device) self.g_shadow.load_state_dict(self.g_net.state_dict()) self.d_net = Birds_D(self.emb_sz).to(self.device) self.optim_g = optim.Adam(self.g_net.parameters(), lr=g_lr, betas=(0, 0.999)) self.optim_d = optim.Adam(self.d_net.parameters(), lr=d_lr, betas=(0, 0.999)) def after_batch_tfm(self, cap, cap_len, img): " cap: (bs, 25), img: (bs, 256, 256, 3) " img256 = img.permute(0, 3, 1, 2).float() # (bs, 3, 256, 256) img256 = resize(img256, size=(int(256 * 76 / 64), int(256 * 76 / 64))) # (bs, 3, 304, 304) img256 = random_crop(img256) # (bs, 3, 256, 256) img256 = random_hflip(img256) img4 = resize(img256, size=(4, 4)) img8 = resize(img256, size=(8, 8)) img16 = resize(img256, size=(16, 16)) img32 = resize(img256, size=(32, 32)) img64 = resize(img256, size=(64, 64)) img128 = resize(img256, size=(128, 128)) img4 = self.normalizer.encode(img4) # (bs, 3, 4, 4) img8 = self.normalizer.encode(img8) # (bs, 3, 8, 8) img16 = self.normalizer.encode(img16) # (bs, 3, 16, 16) img32 = self.normalizer.encode(img32) # (bs, 3, 32, 32) img64 = self.normalizer.encode(img64) # (bs, 3, 64, 64) img128 = self.normalizer.encode(img128) # (bs, 3, 128, 128) img256 = self.normalizer.encode(img256) # (bs, 3, 256, 256) return cap, cap_len, (img256, img128, img64, img32, img16, img8, img4) # Internal Cell @patch def set_device(self: [AnimeHeadsTrainer, BirdsTrainer], device='cpu'): self.device = torch.device(device) self.normalizer.set_device(self.device) self.c_encoder.to(self.device) self.g_net.to(self.device) self.g_shadow.to(self.device) self.d_net.to(self.device) @patch def set_model_mode(self: [AnimeHeadsTrainer, BirdsTrainer], mode): if mode=='D': # self.g_net.eval() self.g_net.requires_grad_(False) self.d_net.train() self.d_net.requires_grad_(True) elif mode=='G': self.g_net.train() self.g_net.requires_grad_(True) # self.d_net.eval() self.d_net.requires_grad_(False) else: raise Exception('Oops!!') @patch def save_checkpoint(self: [AnimeHeadsTrainer, BirdsTrainer], path): state = { 'g_net': self.g_net.state_dict(), 'g_shadow': self.g_shadow.state_dict(), 'd_net': self.d_net.state_dict(), 'optim_g': self.optim_g.state_dict(), 'optim_d': self.optim_d.state_dict(), } torch.save(state, path) @patch def load_checkpoint(self: [AnimeHeadsTrainer, BirdsTrainer], path): state = torch.load(path, map_location=self.device) self.g_net.load_state_dict(state['g_net']) if 'g_shadow' in state: self.g_shadow.load_state_dict(state['g_shadow']) else: self.g_shadow.load_state_dict(state['g_net']) self.d_net.load_state_dict(state['d_net']) self.optim_g.load_state_dict(state['optim_g']) self.optim_d.load_state_dict(state['optim_d']) @patch def export(self: [AnimeHeadsTrainer, BirdsTrainer], path, is_ema=True): g_net = self.g_shadow if is_ema else self.g_net state = { 'vocab_sz': self.vocab_sz, 'emb_sz': self.emb_sz, 'pad_id': self.pad_id, 'rnn_layers': self.rnn_layers, 'rnn_drop_p': self.rnn_drop_p, 'noise_sz': self.noise_sz, 'rnn_encoder': self.rnn_encoder.state_dict(), 'g_net': g_net.state_dict(), } torch.save(state, path) @patch def generate_imgs(self: [AnimeHeadsTrainer, BirdsTrainer], cap, cap_len, img, noise, is_ema=False): g_net = self.g_shadow if is_ema else self.g_net cap, cap_len, true_imgs = self.after_batch_tfm(cap, cap_len, img) bs, max_seq_len = cap.shape device = cap.device src_mask = get_src_mask(cap_len, max_seq_len, device) sent_emb, word_emb = detach(self.rnn_encoder(cap, cap_len)) fake_imgs = g_net(sent_emb, noise, word_emb, src_mask) fake_imgs = list(reversed(fake_imgs)) return cap, cap_len, true_imgs, sent_emb, word_emb, fake_imgs # true_imgs and fake_imgs: large to small @patch @torch.no_grad() def check_d(self: [AnimeHeadsTrainer, BirdsTrainer], is_ema=False): cap, cap_len, img = iter(self.dls.train).next() cap, cap_len, img = to_device([cap, cap_len, img], device=self.device) noise = noise_gen.sample((cap.shape[0], self.noise_sz)).to(self.device) cap, cap_len, true_imgs, sent_emb, word_emb, fake_imgs = self.generate_imgs(cap, cap_len, img, noise, is_ema=is_ema) t_logits = self.d_net(true_imgs, sent_emb) f_logits = self.d_net(fake_imgs, sent_emb) ts = [torch.sigmoid(logit) for logit in t_logits] # t_uncond_s, t_cond_s fs = [torch.sigmoid(logit) for logit in f_logits] # f_uncond_s, f_cond_s return list(zip(ts, fs)) # Internal Cell @patch def decode(self: [AnimeHeadsTrainer, BirdsTrainer], tag, true_img, *fake_imgs): caps = [self.dls.dsets.train.tokenizer.decode(t) for t in tag] true_imgs = self.normalizer.decode(true_img).permute(0, 2, 3, 1).cpu() fake_imgs = [self.normalizer.decode(fake_img).permute(0, 2, 3, 1).cpu() for fake_img in fake_imgs] return caps, true_imgs, fake_imgs @patch @torch.no_grad() def fig_for_show(self: [AnimeHeadsTrainer, BirdsTrainer], is_valid=False, is_ema=False): dl = self.dls.valid if is_valid else self.dls.train cap, cap_len, img = iter(dl).next() cap, cap_len, img = to_device([cap, cap_len, img], device=self.device) noise = noise_gen.sample((cap.shape[0], self.noise_sz)).to(self.device) cap, cap_len, true_imgs, sent_emb, word_emb, fake_imgs = self.generate_imgs(cap, cap_len, img, noise, is_ema=is_ema) caps, true_img, fake_imgs = self.decode(cap, true_imgs[0], *fake_imgs) # List of cap, (bs,), List of (bs,) ncols = len(fake_imgs)+1 nrows = 4 figsize = (ncols*4, nrows*4) fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize) axs = ax.flatten() for i in range(nrows): ax[i][0].imshow(true_img[i]) for j in range(len(fake_imgs)): ax[i][j+1].imshow(fake_imgs[j][i]) ax[i][0].text(0, -1.5, caps[i]) return fig @patch def show(self: [AnimeHeadsTrainer, BirdsTrainer], is_valid=False, is_ema=False): fig = self.fig_for_show(is_valid, is_ema) display(fig) plt.close() @patch def save_jpg(self: [AnimeHeadsTrainer, BirdsTrainer], path, is_valid=False, is_ema=False): fig = self.fig_for_show(is_valid, is_ema) fig.savefig(path) plt.close() # Internal Cell @patch def train( self: [AnimeHeadsTrainer, BirdsTrainer], n_step, # 1 step = train discriminator 1 and train generator 1 step_per_epoch=500, # print loss each step_per_epoch savejpg_every=None, jpg_path:str=None, is_jpg_ema=False, saveck_every=None, ck_path:str=None, n_gradient_acc=1, gp_lambda=None, ema_decay=0.999, ): assert n_step%step_per_epoch==0, f'n_step: {n_step} % step_per_epoch: {step_per_epoch} should be 0' g_losses = [] d_losses = [] total_start_t = time.time() log_start_t = time.time() dl = InfiniteDl(self.dls.train) pb = tqdm(range(1, n_step+1)) for step in pb: # Train Discriminator self.set_model_mode('D') self.optim_d.zero_grad() d_ls = 0 caches = list(range(n_gradient_acc)) for i in range(n_gradient_acc): cap, cap_len, img = to_device(dl.next(), device=self.device) noise = noise_gen.sample((cap.shape[0], self.noise_sz)).to(self.device) caches[i] = (cap.cpu(), cap_len.cpu(), img.cpu(), noise.cpu()) cap, cap_len, true_imgs, sent_emb, word_emb, fake_imgs = self.generate_imgs(cap, cap_len, img, noise, is_ema=False) d_loss = compute_d_loss(self.d_net, fake_imgs, true_imgs, sent_emb, gp_lambda=gp_lambda) / n_gradient_acc d_ls += d_loss d_loss.backward() d_losses.append(d_ls.detach().cpu()) self.optim_d.step() if self.device.type!='xla' else xm.optimizer_step(self.optim_d, barrier=True) # Train Generator self.set_model_mode('G') self.optim_g.zero_grad() g_ls = 0 for i in range(n_gradient_acc): cap, cap_len, img, noise = to_device(caches[i], device=self.device) cap, cap_len, true_imgs, sent_emb, word_emb, fake_imgs = self.generate_imgs(cap, cap_len, img, noise, is_ema=False) word_features, cnn_code = self.cnn_encoder(fake_imgs[0]) g_loss = compute_g_loss(self.d_net, fake_imgs, sent_emb, cnn_code, word_features, word_emb, cap_len, gamma1=self.gamma1, gamma2=self.gamma2, gamma3=self.gamma3, smooth_lambda=self.smooth_lambda) / n_gradient_acc g_ls += g_loss g_loss.backward() g_losses.append(g_ls.detach().cpu()) self.optim_g.step() if self.device.type!='xla' else xm.optimizer_step(self.optim_g, barrier=True) update_average(self.g_shadow, self.g_net, ema_decay) pb.set_postfix(g_loss=g_ls.detach().cpu().numpy(), d_loss=d_ls.detach().cpu().numpy()) # show or save something if savejpg_every and step%savejpg_every == 0: self.save_jpg(path=jpg_path+f'-{step//savejpg_every}.jpg', is_ema=is_jpg_ema) if saveck_every and step%saveck_every == 0: self.save_checkpoint(path=ck_path+f'-{step//saveck_every}.pt') if step%step_per_epoch == 0: duration = time.time() - log_start_t msg = f'{step//step_per_epoch}, time: {duration:.1f}s, g_loss: {torch.tensor(g_losses).mean():.4f}, d_loss: {torch.tensor(d_losses).mean():.4f}' tqdm.write(msg) g_losses = [] d_losses = [] log_start_t = time.time() pb.close() tqdm.write(f'total_time: {(time.time()-total_start_t)/60:.1f}min')
[]
[]
[ "COLAB_TPU_ADDR" ]
[]
["COLAB_TPU_ADDR"]
python
1
0
app/dao/__init__.py
import os from flask import Flask from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS PSQL_CONNECTION = os.environ.get('PSQL_CONNECTION', '') app = Flask(__name__) CORS(app) app.secret_key = 'hidden secret key' # 'postgresql+psycopg2://user:password@ip_adress:5432/db_name' - real name in system environment PSQL_CONNECTION app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://' + PSQL_CONNECTION # app.config['SQLALCHEMY_BINDS'] = {'schema': 'test_flask'} app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False login_manager = LoginManager(app) db = SQLAlchemy(app) # сразу создать таблицы при запуске - не для продакшена def create_database(): db.create_all() db.session.commit() from app.dao import models, routes
[]
[]
[ "PSQL_CONNECTION" ]
[]
["PSQL_CONNECTION"]
python
1
0
example/go_rpc/server/server.go
package main import ( "errors" "log" "net" "net/http" "net/rpc" ) type Args struct { A, B int } type Quotient struct { Quo, Rem int } type Arith int func (t *Arith) Multiply(args *Args, reply *int) error { *reply = args.A * args.B return nil } func (t *Arith) Divide(args *Args, quo *Quotient) error { if args.B == 0 { return errors.New("divide by zero") } quo.Quo = args.A / args.B quo.Rem = args.A % args.B return nil } func main() { arith := new(Arith) rpc.Register(arith) rpc.HandleHTTP() l, e := net.Listen("tcp", ":1234") if e != nil { log.Fatal("listen error:", e) } http.Serve(l, nil) }
[]
[]
[]
[]
[]
go
null
null
null
optional-container-engine/config.py
# Copyright 2015 Google Inc. # # 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. """ This file contains all of the configuration values for the application. Update this file with the values for your specific Google Cloud project. You can create and manage projects at https://console.developers.google.com """ import os # The secret key is used by Flask to encrypt session cookies. SECRET_KEY = 'secret' # There are three different ways to store the data in the application. # You can choose 'datastore', 'cloudsql', or 'mongodb'. Be sure to # configure the respective settings for the one you choose below. # You do not have to configure the other data backends. If unsure, choose # 'datastore' as it does not require any additional configuration. DATA_BACKEND = 'datastore' # Google Cloud Project ID. This can be found on the 'Overview' page at # https://console.developers.google.com PROJECT_ID = 'your-project-id' # CloudSQL & SQLAlchemy configuration # Replace the following values the respective values of your Cloud SQL # instance. CLOUDSQL_USER = 'root' CLOUDSQL_PASSWORD = 'your-cloudsql-password' CLOUDSQL_DATABASE = 'bookshelf' # Set this value to the Cloud SQL connection name, e.g. # "project:region:cloudsql-instance". # You must also update the value in app.yaml. CLOUDSQL_CONNECTION_NAME = 'your-cloudsql-connection-name' # The CloudSQL proxy is used locally to connect to the cloudsql instance. # To start the proxy, use: # # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306 # # Alternatively, you could use a local MySQL instance for testing. LOCAL_SQLALCHEMY_DATABASE_URI = ( 'mysql+pymysql://{user}:{password}@localhost/{database}').format( user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD, database=CLOUDSQL_DATABASE) # When running on App Engine a unix socket is used to connect to the cloudsql # instance. LIVE_SQLALCHEMY_DATABASE_URI = ( 'mysql+pymysql://{user}:{password}@localhost/{database}' '?unix_socket=/cloudsql/{connection_name}').format( user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD, database=CLOUDSQL_DATABASE, connection_name=CLOUDSQL_CONNECTION_NAME) if os.environ.get('GAE_INSTANCE'): SQLALCHEMY_DATABASE_URI = LIVE_SQLALCHEMY_DATABASE_URI else: SQLALCHEMY_DATABASE_URI = LOCAL_SQLALCHEMY_DATABASE_URI # Mongo configuration # If using mongolab, the connection URI is available from the mongolab control # panel. If self-hosting on compute engine, replace the values below. MONGO_URI = 'mongodb://user:password@host:27017/database' # Google Cloud Storage and upload settings. # Typically, you'll name your bucket the same as your project. To create a # bucket: # # $ gsutil mb gs://<your-bucket-name> # # You also need to make sure that the default ACL is set to public-read, # otherwise users will not be able to see their upload images: # # $ gsutil defacl set public-read gs://<your-bucket-name> # # You can adjust the max content length and allow extensions settings to allow # larger or more varied file types if desired. CLOUD_STORAGE_BUCKET = 'your-project-id' MAX_CONTENT_LENGTH = 8 * 1024 * 1024 ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) # OAuth2 configuration. # This can be generated from the Google Developers Console at # https://console.developers.google.com/project/_/apiui/credential. # Note that you will need to add all URLs that your application uses as # authorized redirect URIs. For example, typically you would add the following: # # * http://localhost:8080/oauth2callback # * https://<your-app-id>.appspot.com/oauth2callback. # # If you receive a invalid redirect URI error review you settings to ensure # that the current URI is allowed. GOOGLE_OAUTH2_CLIENT_ID = \ 'your-client-id' GOOGLE_OAUTH2_CLIENT_SECRET = 'your-client-secret'
[]
[]
[ "GAE_INSTANCE" ]
[]
["GAE_INSTANCE"]
python
1
0
trash/train_pixelCT_both_negative_normalized_WTA01.py
from __future__ import print_function, division import os import numpy as np import numpy.random import datetime import torch import torch.optim as optim from torch.nn.functional import relu from lib.dataloader import DataLoader # modified dataloader from lib.model_train.model_pixelCT_both_normalized import ImMatchNet from lib.im_pair_dataset import ImagePairDataset from lib.normalization import NormalizeImageDict from lib.torch_util import save_checkpoint from lib.torch_util import BatchTensorToVars import argparse from lib.matching_model import EPE from tensorboardX import SummaryWriter import matplotlib.pyplot as plt import random from lib.matching_model import multiscaleEPE import torch.nn.functional as F # Seed and CUDA use_cuda = torch.cuda.is_available() torch.cuda.manual_seed_all(1) # if use multi-GPU os.environ['PYTHONHASHSEED'] = str(1) print("use_cuda:",use_cuda) GPU_NUM = 1 device = torch.device(f'cuda:{GPU_NUM}' if torch.cuda.is_available() else 'cpu') print('Available devices', torch.cuda.device_count()) print('Current cuda device', torch.cuda.current_device()) print(torch.cuda.get_device_name(device)) torch.cuda.set_device(device) print('Current cuda device', torch.cuda.current_device()) print('ImMatchNet training script') # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Pascal matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--dataset_image_path', type=str, default='datasets/pf-pascal/', help='path to PF Pascal dataset') parser.add_argument('--dataset_csv_path', type=str, default='datasets/pf-pascal/image_pairs/', help='path to PF Pascal training csv') parser.add_argument('--num_epochs', type=int, default=5, help='number of training epochs') parser.add_argument('--batch_size', type=int, default=16, help='training batch size') parser.add_argument('--lr', type=float, default=0.0000001, help='learning rate') parser.add_argument('--ncons_kernel_sizes', nargs='+', type=int, default=[5,5,5], help='kernels sizes in neigh. cons.') parser.add_argument('--ncons_channels', nargs='+', type=int, default=[16,16,1], help='channels in neigh. cons') parser.add_argument('--result_model_fn', type=str, default='checkpoint_pixelCT_both_neg_fixed_lr7_WTA01', help='trained model filename') parser.add_argument('--result-model-dir', type=str, default='trained_models', help='path to trained models folder') parser.add_argument('--fe_finetune_params', type=int, default=0, help='number of layers to finetune') parser.add_argument('--temperature', type=float, default=0.03, help='pixelCT_temperature') parser.add_argument('--threshold', type=float, default=0.4, help='pixelCT_threshold') def calc_pixelCT_mask(nc_vec, index_NET, mask, temperature): batch_size, _, feature_size, feature_size = nc_vec.size() nc_BSS = nc_vec.contiguous().view(batch_size * feature_size * feature_size, feature_size * feature_size) nc_BSS_numpy = nc_BSS.detach().cpu().numpy() index1D_NET = index_NET.view(batch_size * feature_size * feature_size, 1) index1D_NET_numpy = index1D_NET.detach().cpu().numpy() #(B * tgt_s * tgt_s, src_s * src_s) mask_pixelCT = torch.zeros(batch_size * feature_size * feature_size, feature_size * feature_size).bool() mask_pixelCT[torch.arange(batch_size * feature_size * feature_size), index1D_NET.detach().squeeze(1)] = True mask_pixelCT_numpy = mask_pixelCT.detach().cpu().numpy() # positive = scores_WTA_B.view(batch_size * feature_size * feature_size, -1) positive = nc_BSS[mask_pixelCT].view(batch_size * feature_size * feature_size, -1) positive_numpy = positive.detach().cpu().numpy() negative = nc_BSS[~mask_pixelCT].view(batch_size * feature_size * feature_size, -1) negative_numpy = negative.detach().cpu().numpy() mask1D = torch.zeros(batch_size * feature_size * feature_size, 1).bool() mask_label = mask.view(-1, 1).bool() mask_label_numpy = mask_label.detach().cpu().numpy() mask1D[mask_label] = True mask1D_numpy = mask1D.detach().cpu().numpy() positive= positive[mask1D.squeeze(1), :] positive_numpy2 = positive.detach().cpu().numpy() negative = negative[mask1D.squeeze(1), :] negative_numpy2 = negative.detach().cpu().numpy() masked_logits = torch.cat([positive, negative], dim=1) eps_temp = 1e-6 masked_logits = masked_logits / (temperature + eps_temp) src_num_fgnd = mask.sum(dim=3, keepdim=True).sum(dim=2, keepdim=True).sum(dim=0, keepdim=True) src_num_fgnd_label = src_num_fgnd.item() labels = torch.zeros(int(src_num_fgnd_label), device=device, dtype=torch.int64) loss_pixelCT = F.cross_entropy(masked_logits, labels, reduction='sum') loss_pixelCT = (loss_pixelCT / src_num_fgnd).sum() return loss_pixelCT def writer_grad_flow(named_parameters, writer, writer_position): ave_grads = [] layers = [] for n, p in named_parameters: if(p.requires_grad) and ("bias" not in n): if p.grad is None: continue print(n, "p.grad is None") writer.add_scalar('gradient_flow/{}'.format(n), p.grad.abs().mean().data.cpu().numpy(), writer_position) def plot_grad_flow(named_parameters): ave_grads = [] layers = [] for n, p in named_parameters: if(p.requires_grad) and ("bias" not in n): if p.grad is None: continue print(n) print(n) layers.append(n) ave_grads.append(p.grad.abs().mean()) print(p.grad.abs().mean()) plt.plot(ave_grads, alpha=0.3, color="b") plt.hlines(0, 0, len(ave_grads)+1, linewidth=1, color="k" ) plt.xticks(range(0,len(ave_grads), 1), layers, rotation="vertical") plt.xlim(xmin=0, xmax=len(ave_grads)) plt.xlabel("Layers") plt.ylabel("average gradient") plt.title("Gradient flow") plt.grid(True) args = parser.parse_args() print(args) save_path = 'trainLog_pixelCT_both_neg_fixed_lr7_WTA01' if not os.path.isdir(save_path): os.mkdir(save_path) writer = SummaryWriter(os.path.join(save_path, '')) # Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint, ncons_kernel_sizes=args.ncons_kernel_sizes, ncons_channels=args.ncons_channels, threshold = args.threshold) torch.manual_seed(1) if use_cuda: print('torch cuda manual seed used =========================') torch.cuda.manual_seed(1) np.random.seed(1) random.seed(1) # Set which parts of the model to train if args.fe_finetune_params>0: for i in range(args.fe_finetune_params): for p in model.FeatureExtraction.model[-1][-(i+1)].parameters(): p.requires_grad=True print('Trainable parameters:') for i,p in enumerate(filter(lambda p: p.requires_grad, model.parameters())): print(str(i+1)+": "+str(p.shape)) for i, p in model.named_parameters(): # print(str(i + 1) + ": " + str(p.shape)) writer.add_histogram(i, p.clone().cpu().data.numpy(), 0) # Optimizer print('using Adam optimizer') optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr) cnn_image_size=(args.image_size,args.image_size) Dataset = ImagePairDataset train_csv = 'train_pairs.csv' test_csv = 'val_pairs.csv' normalization_tnf = NormalizeImageDict(['source_image','target_image']) batch_preprocessing_fn = BatchTensorToVars(use_cuda=use_cuda) # Dataset and dataloader dataset = Dataset(transform=normalization_tnf, dataset_image_path=args.dataset_image_path, dataset_csv_path=args.dataset_csv_path, dataset_csv_file = train_csv, output_size=cnn_image_size) print(args.batch_size) dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers=0) dataset_test = Dataset(transform=normalization_tnf, dataset_image_path=args.dataset_image_path, dataset_csv_path=args.dataset_csv_path, dataset_csv_file=test_csv, output_size=cnn_image_size) dataloader_test = DataLoader(dataset_test, batch_size=args.batch_size, shuffle=True, num_workers=4) # Train best_test_loss = float("inf") def weak_loss(model,batch,writer_position, normalization='softmax',alpha=30): if normalization is None: normalize = lambda x: x elif normalization=='softmax': normalize = lambda x: torch.nn.functional.softmax(x,1) elif normalization=='l1': normalize = lambda x: x/(torch.sum(x,dim=1,keepdim=True)+0.0001) b = batch['source_image'].size(0) # positive #corr4d = model({'source_image':batch['source_image'], 'target_image':batch['target_image']}) corr_WTA , corr_NET, mask_B_Avec, masked_index_B_Avec = model(batch, writer, writer_position) batch_size = corr_WTA.size(0) feature_size = corr_WTA.size(2) nc_WTA_B_Avec = corr_WTA.view(batch_size, feature_size * feature_size, feature_size, feature_size) # [batch_idx,k_A,i_B,j_B] nc_NET_B_Avec = corr_NET.view(batch_size, feature_size * feature_size, feature_size, feature_size) #PixelCT loss_pixelCT_WTA_B_Avec_pos = calc_pixelCT_mask(nc_WTA_B_Avec, masked_index_B_Avec, mask_B_Avec, args.temperature) loss_pixelCT_NET_B_Avec_pos = calc_pixelCT_mask(nc_NET_B_Avec, masked_index_B_Avec, mask_B_Avec, args.temperature) score_pos_pixelCT = loss_pixelCT_WTA_B_Avec_pos + loss_pixelCT_NET_B_Avec_pos loss_pixelCT_WTA_B_Avec_pos = loss_pixelCT_WTA_B_Avec_pos * 0.1 #neg batch['source_image'] = batch['source_image'][np.roll(np.arange(b), -1), :] # roll corr_WTA , corr_NET, mask_B_Avec, masked_index_B_Avec = model(batch, writer, writer_position) batch_size = corr_WTA.size(0) feature_size = corr_WTA.size(2) nc_WTA_B_Avec = corr_WTA.view(batch_size, feature_size * feature_size, feature_size, feature_size) # [batch_idx,k_A,i_B,j_B] nc_NET_B_Avec = corr_NET.view(batch_size, feature_size * feature_size, feature_size, feature_size) #PixelCT loss_pixelCT_WTA_B_Avec_neg = calc_pixelCT_mask(nc_WTA_B_Avec, masked_index_B_Avec, mask_B_Avec, args.temperature) loss_pixelCT_NET_B_Avec_neg = calc_pixelCT_mask(nc_NET_B_Avec, masked_index_B_Avec, mask_B_Avec, args.temperature) loss_pixelCT_WTA_B_Avec_neg = loss_pixelCT_WTA_B_Avec_neg * 0.1 return loss_pixelCT_WTA_B_Avec_pos, loss_pixelCT_NET_B_Avec_pos, loss_pixelCT_WTA_B_Avec_neg, loss_pixelCT_NET_B_Avec_neg loss_fn = lambda model,batch, writer_position : weak_loss(model,batch,writer_position, normalization='softmax') # define epoch function def process_epoch(mode,epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn, writer, use_cuda=True,log_interval=50): epoch_loss = 0 for batch_idx, batch in enumerate(dataloader): if mode=='train': optimizer.zero_grad() writer_position = (epoch -1) * len(dataloader) + batch_idx tnf_batch = batch_preprocessing_fn(batch) # loss_nc, loss_flow, loss_contrastive = loss_fn(model,tnf_batch, batch_idx) loss_pixelCT_WTA_B_Avec_pos, loss_pixelCT_NET_B_Avec_pos, loss_pixelCT_WTA_B_Avec_neg, loss_pixelCT_NET_B_Avec_neg = loss_fn(model, tnf_batch, writer_position) score_pos_pixelCT = loss_pixelCT_WTA_B_Avec_pos + loss_pixelCT_NET_B_Avec_pos score_neg_pixelCT = loss_pixelCT_WTA_B_Avec_neg + loss_pixelCT_NET_B_Avec_neg writer.add_scalar('Loss_{}/loss_pixelCT_WTA_B_Avec_pos01'.format(mode), loss_pixelCT_WTA_B_Avec_pos, writer_position) writer.add_scalar('Loss_{}/loss_pixelCT_NET_B_Avec_pos'.format(mode), loss_pixelCT_NET_B_Avec_pos, writer_position) writer.add_scalar('Loss_{}/loss_pixelCT_WTA_B_Avec_neg01'.format(mode), loss_pixelCT_WTA_B_Avec_neg, writer_position) writer.add_scalar('Loss_{}/loss_pixelCT_NET_B_Avec_neg'.format(mode), loss_pixelCT_NET_B_Avec_neg, writer_position) writer.add_scalar('Loss_{}/score_pos_pixelCT'.format(mode), score_pos_pixelCT, writer_position) writer.add_scalar('Loss_{}/score_neg_pixelCT'.format(mode), score_neg_pixelCT, writer_position) print("score_pos_pixelCT:"+ str(score_pos_pixelCT.data.cpu().numpy())) print("score_neg_pixelCT:" + str(score_neg_pixelCT.data.cpu().numpy())) loss = score_pos_pixelCT - score_neg_pixelCT writer.add_scalar('Loss_total/score_both_pixelCT', loss, writer_position) loss_np = loss.data.cpu().numpy() epoch_loss += loss_np # save_checkpoint({ # 'epoch': epoch, # 'args': args, # 'state_dict': model.state_dict(), # 'best_test_loss': best_test_loss, # 'optimizer': optimizer.state_dict(), # 'train_loss': epoch_loss, # 'test_loss': epoch_loss, # }, False, os.path.join('./trained_models/', # 'baseline_feature_extraction' + '.pth.tar')) # print("baseline!!") if mode=='train': loss.backward() writer_grad_flow(model.named_parameters(), writer,writer_position) # plot_grad_flow(model.named_parameters()) if writer_position % 100 == 0: for i,p in model.named_parameters(): if(p.requires_grad) and ("bias" not in i): writer.add_histogram(i, p.clone().cpu().data.numpy(), writer_position) optimizer.step() else: loss=None if batch_idx % log_interval == 0: print(mode.capitalize()+' Epoch: {} [{}/{} ({:.0f}%)]\t\tLoss: {:.6f}'.format(epoch, batch_idx , len(dataloader), 100. * batch_idx / len(dataloader), loss_np)) epoch_loss /= len(dataloader) print(mode.capitalize()+' set: Average loss: {:.4f}'.format(epoch_loss)) return epoch_loss train_loss = np.zeros(args.num_epochs) test_loss = np.zeros(args.num_epochs) print('Starting training...') model.FeatureExtraction.eval() for epoch in range(1, args.num_epochs+1): train_loss[epoch-1] = process_epoch('train',epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,writer, log_interval=1) test_loss[epoch-1] = process_epoch('test',epoch,model,loss_fn,optimizer,dataloader_test,batch_preprocessing_fn,writer, log_interval=1) # remember best loss is_best = test_loss[epoch-1] < best_test_loss best_test_loss = min(test_loss[epoch-1], best_test_loss) # Define checkpoint name checkpoint_name = os.path.join(args.result_model_dir, datetime.datetime.now().strftime( "%Y-%m-%d_%H:%M") + '_epoch_' + str(epoch) + '_' + args.result_model_fn + '.pth.tar') print('Checkpoint name: ' + checkpoint_name) save_checkpoint({ 'epoch': epoch, 'args': args, 'state_dict': model.state_dict(), 'best_test_loss': best_test_loss, 'optimizer' : optimizer.state_dict(), 'train_loss': train_loss, 'test_loss': test_loss, }, is_best,checkpoint_name) print('Done!')
[]
[]
[ "PYTHONHASHSEED" ]
[]
["PYTHONHASHSEED"]
python
1
0
10.go-redis/99.poc/redis_expire.go
package main import ( "fmt" "math/rand" "os" "time" "github.com/go-redis/redis" ) var ( min = 1 // sec max = 10 // sec ) func main() { rand.Seed(time.Now().UnixNano()) go Monitoring() client := GetRedisClient() client.Ping() now := time.Now() SetTimer(client, 100) // 10 일때에는 정상 동작 fmt.Println("End.Since=", time.Since(now)) time.Sleep(time.Duration(max+20) * time.Second) // Monitoring 이벤트 종료를 위해 대기 중 fmt.Println("Done...") } func GetRedisClient() *redis.Client { redisAddr := os.Getenv("REDIS_HOST") + ":" + os.Getenv("REDIS_PORT") fmt.Println("REDIS=", redisAddr) now := time.Now() client := redis.NewClient(&redis.Options{ Addr: redisAddr, Password: "", DB: 0, }) ret := client.Ping() fmt.Println("Ping=", ret, "Connect.Since=", time.Since(now)) return client } // TM- + 일련번호 + 현재시간(시분초) + Expire 시간(초) func SetTimer(client *redis.Client, nLoop int) { var key, value string var nExpire int var tExpire time.Duration var err error value = "0" for i := 0; i < nLoop; i++ { nExpire = rand.Intn(max) + min now := time.Now() key = fmt.Sprintf("TM-%03d-%s-%03d", i, now.Format("20060102150405"), nExpire) tExpire = time.Duration(nExpire) * time.Second err = client.Set(key, value, tExpire).Err() if err != nil { panic(err) } fmt.Println("Set(", key, ",", tExpire, ")", "Since=", time.Since(now)) time.Sleep(10 * time.Millisecond) } } // Key expired 이벤트를 수신하여 화면에 표시 func Monitoring() { var err error client := GetRedisClient() now := time.Now() //CONFIG SET notify-keyspace-events KEA err = client.ConfigSet("notify-keyspace-events", "KEx").Err() if err != nil { panic(err) } fmt.Println("ConfigSet", "Since=", time.Since(now)) now = time.Now() //PSUBSCRIBE '__key*__:expired' pubsub := client.PSubscribe("__key*__:expired") _, err = pubsub.Receive() if err != nil { panic(err) } fmt.Println("PSubscribe", "Since=", time.Since(now)) var nIndex, nExpire int var timeStr string eventTime := time.Now() ch := pubsub.Channel() for msg := range ch { now = time.Now() fmt.Sscanf(msg.Payload, "TM-%03d-%14s-%03d", &nIndex, &timeStr, &nExpire) eventTime, _ = time.Parse("20060102150405", timeStr) eventTime = eventTime.Add(time.Duration(nExpire) * time.Second) // "Channel=", msg.Channel, fmt.Println(now.Format("2006/01/02 15:04:05"), "Payload=", msg.Payload, "Expire=", eventTime.Format("2006/01/02 15:04:05"), "diff=", now.Sub(eventTime)) } }
[ "\"REDIS_HOST\"", "\"REDIS_PORT\"" ]
[]
[ "REDIS_PORT", "REDIS_HOST" ]
[]
["REDIS_PORT", "REDIS_HOST"]
go
2
0
3d-tracking/run_estimation.py
import os import sys import argparse import pickle import subprocess from time import sleep ''' Multiple GPUs and processes script for monocular 3D Tracking ''' def parse_args(): parser = argparse.ArgumentParser(description='Monocular 3D Estimation', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('set', choices=['gta', 'kitti']) parser.add_argument('split', choices=['train', 'val', 'test'], help='Which data split to use in testing') parser.add_argument('--session', default='616', help='Name of the session, to separate exp') parser.add_argument('--epoch', default='030', help='How many epochs you used to separate exp') parser.add_argument('--flag', default='-j 4 -b 1 --n_box_limit 300', help='Flags for running evaluation code') parser.add_argument('--gpu', type=str, default='0,1,2,3,4', help='Which GPU to use in testing.') parser.add_argument('--n_tasks', type=int, default=1, help='number of tasks running per GPU. n=1 is enough.') parser.add_argument('--dry_run', action='store_true', default=False, help='Show command without running') parser.add_argument('--overwrite', action='store_true', default=False, help='Overwrite the output files') parser.add_argument('--not_gen_output', action='store_true', default=False, help='Run 3D estimation and store tracking info') parser.add_argument('--not_merge_result', action='store_true', default=False, help='Merge 3D result for tracking') args = parser.parse_args() args.gen_output = not args.not_gen_output args.merge_result = not args.not_merge_result return args print(' '.join(sys.argv)) args = parse_args() GPUS = args.gpu.split(',') # Metadata if args.set == 'gta': JSON_ROOT = './data/gta5_tracking/{}/label/'.format(args.split) CMD = 'python mono_3d_estimation.py gta test \ --data_split {SPLIT} \ --resume ./checkpoint/{CKPT} \ --json_path {JSON} \ --track_name {TRK} \ --session {SESS} {FLAG} --start_epoch {EPOCH}' else: JSON_ROOT = './data/kitti_tracking/{}ing/label_02/'.format(args.split) CMD = 'python mono_3d_estimation.py kitti test \ --data_split {SPLIT} \ --resume ./checkpoint/{CKPT} \ --json_path {JSON} \ --track_name {TRK} \ --is_tracking \ --is_normalizing \ --session {SESS} {FLAG} --start_epoch {EPOCH}' SAVE_PATH = 'output/{SESS}_{EP}_{SET}_{SPLIT}_set/'.format( **{'SESS': args.session, 'EP': args.epoch, 'SET': args.set, 'SPLIT': args.split}) if not os.path.isdir(SAVE_PATH): print("Making {}...".format(SAVE_PATH)) os.mkdir(SAVE_PATH) CKPT = '{}_{}_checkpoint_{}.pth.tar'.format(args.session, args.set, args.epoch) SAVE_NAME = '{PATH}{SESS}_{EP}_{SET}_roipool_output.pkl'.format( **{'PATH': SAVE_PATH, 'SESS': args.session, 'EP': args.epoch, 'SET': args.set}) JSON_PATHS = sorted( [n for n in os.listdir(JSON_ROOT) if n.endswith('bdd.json')]) # Script def gen_3d_output(): m = len(GPUS) * args.n_tasks ps = [] for i in range(len(JSON_PATHS) // m + 1): for JSON, GPU in zip(JSON_PATHS[m * i:m * i + m], GPUS * args.n_tasks): TRK = '{}{}_{}_{}_roipool_output.pkl'.format( SAVE_PATH.replace('output/', ''), args.session, args.epoch, JSON.replace('.json', '')) cmd = CMD.format( **{'CKPT': CKPT, 'JSON': os.path.join(JSON_ROOT, JSON), 'TRK': TRK, 'SESS': args.session, 'EPOCH': args.epoch, 'FLAG': args.flag, 'SPLIT': args.split}) print(i, GPU, cmd) if not args.dry_run: if not args.overwrite and os.path.isfile(os.path.join('output', TRK)): print("SKIP running. Generated file {} Found".format(TRK)) continue subprocess_env = os.environ.copy() subprocess_env['CUDA_VISIBLE_DEVICES'] = GPU p = subprocess.Popen(cmd, shell=True, env=subprocess_env) ps.append(p) sleep(1) if not args.dry_run: for p in ps: p.wait() def merge_3d_results(): all_pkl = [] for JSON in JSON_PATHS: TRK = '{}{}_{}_{}_roipool_output.pkl'.format(SAVE_PATH, args.session, args.epoch, JSON.replace('.json', '')) print("Reading {}...".format(TRK)) if not args.dry_run: all_pkl += pickle.load(open(TRK, 'rb')) if not args.dry_run and len(all_pkl) > 0: print("Save to {}".format(SAVE_NAME)) with open(SAVE_NAME, 'wb') as f: pickle.dump(all_pkl, f) if __name__ == '__main__': if args.gen_output: gen_3d_output() if args.merge_result: merge_3d_results()
[]
[]
[]
[]
[]
python
0
0
src/main/java/qa/qcri/iyas/RunClient.java
/** * Copyright 2017 Salvatore Romeo * * 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 qa.qcri.iyas; import java.util.HashMap; import java.util.Map; import org.apache.uima.UIMAFramework; import org.apache.uima.aae.client.UimaAsBaseCallbackListener; import org.apache.uima.aae.client.UimaAsynchronousEngine; import org.apache.uima.adapter.jms.client.BaseUIMAAsynchronousEngine_impl; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionReader; import org.apache.uima.collection.CollectionReaderDescription; import org.apache.uima.collection.EntityProcessStatus; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.factory.ExternalResourceFactory; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.jcas.tcas.DocumentAnnotation; import org.apache.uima.resource.ExternalResourceDescription; import qa.qcri.iyas.data.reader.InputCollectionDataReader; import qa.qcri.iyas.data.reader.PlainTextDataReader; import qa.qcri.iyas.type.cqa.Comment; import qa.qcri.iyas.type.cqa.RelatedQuestion; import qa.qcri.iyas.type.cqa.RelatedQuestionBody; import qa.qcri.iyas.type.cqa.RelatedQuestionSubject; import qa.qcri.iyas.type.cqa.UserQuestion; import qa.qcri.iyas.type.cqa.UserQuestionBody; import qa.qcri.iyas.type.cqa.UserQuestionSubject; class ProcessingOutputListener extends UimaAsBaseCallbackListener { @Override public void entityProcessComplete(CAS cas, EntityProcessStatus aStatus) { try { if (!aStatus.getStatusMessage().equals("success")) { System.err.println(aStatus.getStatusMessage()); } else { for (Annotation annotation : cas.getJCas().getAnnotationIndex()) { if (annotation instanceof UserQuestion) { UserQuestion cqaAnnotation = (UserQuestion)annotation; System.out.println(cqaAnnotation.getID()+" complete "); } else if (annotation instanceof UserQuestionSubject) { UserQuestionSubject cqaAnnotation = (UserQuestionSubject)annotation; System.out.println(cqaAnnotation.getID()+" subject "); } else if (annotation instanceof UserQuestionBody) { UserQuestionBody cqaAnnotation = (UserQuestionBody)annotation; System.out.println(cqaAnnotation.getID()+" body "+cqaAnnotation.getNumberOfCandidates()); } else if (annotation instanceof RelatedQuestion) { RelatedQuestion cqaAnnotation = (RelatedQuestion)annotation; System.out.println(cqaAnnotation.getID()+" complete"); } else if (annotation instanceof RelatedQuestionSubject) { RelatedQuestionSubject cqaAnnotation = (RelatedQuestionSubject)annotation; System.out.println(cqaAnnotation.getID()+" subject "); } else if (annotation instanceof RelatedQuestionBody) { RelatedQuestionBody cqaAnnotation = (RelatedQuestionBody)annotation; System.out.println(cqaAnnotation.getID()+" body "+cqaAnnotation.getNumberOfCandidates()); } else if (annotation instanceof Comment) { Comment cqaAnnotation = (Comment)annotation; System.out.println(cqaAnnotation.getID()+" comment "); } else if (annotation instanceof DocumentAnnotation) { // if (!JCasUtil.exists(cas.getJCas(), UserQuestion.class) && // !JCasUtil.exists(cas.getJCas(), RelatedQuestion.class)) // System.out.println(cas.getDocumentText()); } // else { // for (Annotation ann : cas.getJCas().getAnnotationIndex()) { // System.err.println(ann.toString()); // } // throw new RuntimeException("The input CAS must have only one annotation!",null); // } } } } catch (CASException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class RunClient { public static void main(String[] args) throws Exception { UimaAsynchronousEngine uimaAsEngine = new BaseUIMAAsynchronousEngine_impl(); // create a Map to hold required parameters Map<String,Object> appCtx = new HashMap<String,Object>(); appCtx.put(UimaAsynchronousEngine.DD2SpringXsltFilePath,System.getenv("UIMA_HOME") + "/bin/dd2spring.xsl"); appCtx.put(UimaAsynchronousEngine.SaxonClasspath,"file:" + System.getenv("UIMA_HOME") + "/saxon/saxon8.jar"); // CollectionReaderDescription collectionReaderDescr = CollectionReaderFactory.createReaderDescriptionFromPath( // RunClient.class.getResource("/descriptors/qa/qcri/iyas/data/reader/InputCollectionDataReaderAE_Descriptor.xml").getPath()); CollectionReaderDescription collectionReaderDescr = CollectionReaderFactory.createReaderDescription( InputCollectionDataReader.class); ExternalResourceDescription reader = ExternalResourceFactory.createExternalResourceDescription(PlainTextDataReader.class, PlainTextDataReader.FILE_PARAM,"/home/sromeo/workspaces/UIMA/workspace/S3QACoreFramework/data/dev.txt", PlainTextDataReader.TASK_PARAM, PlainTextDataReader.INSTANCE_C_TASK); ExternalResourceFactory.bindExternalResource(collectionReaderDescr, InputCollectionDataReader.INPUT_READER_PARAM, reader); CollectionReader collectionReader = UIMAFramework.produceCollectionReader(collectionReaderDescr); uimaAsEngine.setCollectionReader(collectionReader); uimaAsEngine.addStatusCallbackListener(new ProcessingOutputListener()); appCtx.put(UimaAsynchronousEngine.ServerUri, "tcp://localhost:61616"); appCtx.put(UimaAsynchronousEngine.ENDPOINT, "myQueueName"); appCtx.put(UimaAsynchronousEngine.CasPoolSize, 100); uimaAsEngine.initialize(appCtx); double start = System.currentTimeMillis(); uimaAsEngine.process(); double end = System.currentTimeMillis(); double seconds = (end - start)/1000; System.out.println(seconds+" seconds"); uimaAsEngine.stop(); } }
[ "\"UIMA_HOME\"", "\"UIMA_HOME\"" ]
[]
[ "UIMA_HOME" ]
[]
["UIMA_HOME"]
java
1
0
utils/SwiftBuildSupport.py
# utils/SwiftBuildSupport.py - Utilities for Swift build scripts -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors from __future__ import print_function try: # Python 2 import ConfigParser except ImportError: # Python 3 import configparser as ConfigParser import os import pipes import platform import subprocess import sys HOME = os.environ.get("HOME", "/") def _get_default_source_root(): result = "" # Are we in a Swift checkout? Start from this file and check its parent # directories. # # $SWIFT_SOURCE_ROOT/swift/utils/SwiftBuildSupport.py (swift_path, parent_dirname) = os.path.split(os.path.dirname(__file__)) if parent_dirname != "utils": return result if not os.path.exists(os.path.join(swift_path, 'CMakeLists.txt')): return result result = os.path.dirname(swift_path) # Are we in an LLVM checkout? Start from the Swift checkout and check /its/ # parent directories. # # $SWIFT_SOURCE_ROOT/llvm/tools/swift/utils/SwiftBuildSupport.py (llvm_path, parent_dirname) = os.path.split(result) if parent_dirname != "tools": return result if not os.path.exists(os.path.join(llvm_path, 'CMakeLists.txt')): return result result = os.path.dirname(llvm_path) return result # Set SWIFT_SOURCE_ROOT in your environment to control where the sources # are found. SWIFT_SOURCE_ROOT = os.environ.get( "SWIFT_SOURCE_ROOT", _get_default_source_root()) # Set SWIFT_BUILD_ROOT to a directory that will contain a subdirectory # for each build configuration SWIFT_BUILD_ROOT = os.environ.get( "SWIFT_BUILD_ROOT", os.path.join(SWIFT_SOURCE_ROOT, "build")) def print_with_argv0(message): print(sys.argv[0] + ": " + message) def quote_shell_command(args): return " ".join([pipes.quote(a) for a in args]) def check_call(args, print_command=False, verbose=False, disable_sleep=False): if disable_sleep: if platform.system() == 'Darwin': # Don't mutate the caller's copy of the arguments. args = list(args) args.insert(0, "caffeinate") if print_command: print(os.getcwd() + "$ " + quote_shell_command(args)) try: return subprocess.check_call(args) except subprocess.CalledProcessError as e: print_with_argv0( "command terminated with a non-zero exit status " + str(e.returncode) + ", aborting") sys.stdout.flush() sys.exit(1) except OSError as e: print_with_argv0( "could not execute '" + quote_shell_command(args) + "': " + e.strerror) sys.stdout.flush() sys.exit(1) def check_output(args, print_command=False, verbose=False): if print_command: print(os.getcwd() + "$ " + quote_shell_command(args)) try: return subprocess.check_output(args) except subprocess.CalledProcessError as e: print_with_argv0( "command terminated with a non-zero exit status " + str(e.returncode) + ", aborting") sys.stdout.flush() sys.exit(1) except OSError as e: print_with_argv0( "could not execute '" + quote_shell_command(args) + "': " + e.strerror) sys.stdout.flush() sys.exit(1) def _load_preset_files_impl(preset_file_names, substitutions={}): config = ConfigParser.SafeConfigParser(substitutions, allow_no_value=True) if config.read(preset_file_names) == []: print_with_argv0( "preset file not found (tried " + str(preset_file_names) + ")") sys.exit(1) return config _PRESET_PREFIX = "preset: " def _get_preset_options_impl(config, substitutions, preset_name): section_name = _PRESET_PREFIX + preset_name if section_name not in config.sections(): return (None, None, None) build_script_opts = [] build_script_impl_opts = [] missing_opts = [] dash_dash_seen = False for o in config.options(section_name): try: a = config.get(section_name, o) except ConfigParser.InterpolationMissingOptionError as e: # e.reference contains the correctly formatted option missing_opts.append(e.reference) continue if not a: a = "" if o in substitutions: continue opt = None if o == "mixin-preset": # Split on newlines and filter out empty lines. mixins = filter(None, [m.strip() for m in a.splitlines()]) for mixin in mixins: (base_build_script_opts, base_build_script_impl_opts, base_missing_opts) = \ _get_preset_options_impl(config, substitutions, mixin) build_script_opts += base_build_script_opts build_script_impl_opts += base_build_script_impl_opts missing_opts += base_missing_opts elif o == "dash-dash": dash_dash_seen = True elif a == "": opt = "--" + o else: opt = "--" + o + "=" + a if opt: if not dash_dash_seen: build_script_opts.append(opt) else: build_script_impl_opts.append(opt) return (build_script_opts, build_script_impl_opts, missing_opts) def get_preset_options(substitutions, preset_file_names, preset_name): config = _load_preset_files_impl(preset_file_names, substitutions) (build_script_opts, build_script_impl_opts, missing_opts) = \ _get_preset_options_impl(config, substitutions, preset_name) if not build_script_opts and not build_script_impl_opts: print_with_argv0("preset '" + preset_name + "' not found") sys.exit(1) if missing_opts: print_with_argv0("missing option(s) for preset '" + preset_name + "': " + ", ".join(missing_opts)) sys.exit(1) return build_script_opts + ["--"] + build_script_impl_opts def get_all_preset_names(preset_file_names): config = _load_preset_files_impl(preset_file_names) return [name[len(_PRESET_PREFIX):] for name in config.sections() if name.startswith(_PRESET_PREFIX)] # A context manager for changing the current working directory. # # with WorkingDirectory('/tmp'): # ... do work in /tmp... class WorkingDirectory(object): def __init__(self, new_cwd): self.new_cwd = new_cwd def __enter__(self): self.old_cwd = os.getcwd() os.chdir(self.new_cwd) def __exit__(self, type, value, traceback): os.chdir(self.old_cwd)
[]
[]
[ "SWIFT_BUILD_ROOT", "HOME", "SWIFT_SOURCE_ROOT" ]
[]
["SWIFT_BUILD_ROOT", "HOME", "SWIFT_SOURCE_ROOT"]
python
3
0
test/e2e/predictor/test_tensorflow.py
# Copyright 2019 kubeflow.org. # # 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. import os import numpy as np from kubernetes import client from kfserving import KFServingClient from kfserving import constants from kfserving import V1alpha2EndpointSpec from kfserving import V1alpha2PredictorSpec from kfserving import V1alpha2TensorflowSpec from kfserving import V1alpha2InferenceServiceSpec from kfserving import V1alpha2InferenceService from kubernetes.client import V1ResourceRequirements from ..common.utils import predict from ..common.utils import KFSERVING_TEST_NAMESPACE api_version = constants.KFSERVING_GROUP + '/' + constants.KFSERVING_VERSION KFServing = KFServingClient(config_file=os.environ.get("KUBECONFIG", "~/.kube/config")) def test_tensorflow_kfserving(): service_name = 'isvc-tensorflow' default_endpoint_spec = V1alpha2EndpointSpec( predictor=V1alpha2PredictorSpec( min_replicas=1, tensorflow=V1alpha2TensorflowSpec( storage_uri='gs://kfserving-samples/models/tensorflow/flowers', resources=V1ResourceRequirements( requests={'cpu': '1', 'memory': '2Gi'}, limits={'cpu': '1', 'memory': '2Gi'})))) isvc = V1alpha2InferenceService(api_version=api_version, kind=constants.KFSERVING_KIND, metadata=client.V1ObjectMeta( name=service_name, namespace=KFSERVING_TEST_NAMESPACE), spec=V1alpha2InferenceServiceSpec(default=default_endpoint_spec)) KFServing.create(isvc) KFServing.wait_isvc_ready(service_name, namespace=KFSERVING_TEST_NAMESPACE) res = predict(service_name, './data/flower_input.json') assert(np.argmax(res["predictions"][0].get('scores')) == 0) # Delete the InferenceService KFServing.delete(service_name, namespace=KFSERVING_TEST_NAMESPACE)
[]
[]
[ "KUBECONFIG" ]
[]
["KUBECONFIG"]
python
1
0
potato/db/mongo.go
package db import ( "context" "fmt" "os" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var client = Connection() var database = client.Database("go-potato") var UsersCollection = database.Collection("users") var TVShowsCollection = database.Collection("tv-shows") var MoviesCollection = database.Collection("movies") var MessagesDataCollection = database.Collection("messages") func Connection() *mongo.Client { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGODB_URI"))) if err != nil { fmt.Println(err) } fmt.Println("connected to MongoDB") return client }
[ "\"MONGODB_URI\"" ]
[]
[ "MONGODB_URI" ]
[]
["MONGODB_URI"]
go
1
0
utils/helpers.py
""" Module containing helper functions for accessing Algorand blockchain. Forked from https://github.com/ipaleka/algorand-contracts-testing """ import base64 import os import pty import subprocess import time from pathlib import Path from algosdk import account, mnemonic from algosdk.error import IndexerHTTPError from algosdk.future.transaction import LogicSig, LogicSigTransaction, PaymentTxn from algosdk.v2client import algod, indexer INDEXER_TIMEOUT = 10 # 61 for devMode ## SANDBOX def _cli_passphrase_for_account(address): """Return passphrase for provided address.""" process = call_sandbox_command("goal", "account", "export", "-a", address) if process.stderr: raise RuntimeError(process.stderr.decode("utf8")) passphrase = "" parts = process.stdout.decode("utf8").split('"') if len(parts) > 1: passphrase = parts[1] if passphrase == "": raise ValueError( "Can't retrieve passphrase from the address: %s\nOutput: %s" % (address, process.stdout.decode("utf8")) ) return passphrase def _sandbox_directory(): """Return full path to Algorand's sandbox executable. The location of sandbox directory is retrieved either from the SANDBOX_DIR environment variable or if it's not set then the location of sandbox directory is implied to be the sibling of this Django project in the directory tree. """ return os.environ.get("SANDBOX_DIR") or str( Path(__file__).resolve().parent.parent / "sandbox" ) def _sandbox_executable(): """Return full path to Algorand's sandbox executable.""" return _sandbox_directory() + "/sandbox" def call_sandbox_command(*args): """Call and return sandbox command composed from provided arguments.""" return subprocess.run( [_sandbox_executable(), *args], stdin=pty.openpty()[1], capture_output=True ) ## CLIENTS def _algod_client(): """Instantiate and return Algod client object.""" algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" return algod.AlgodClient(algod_token, algod_address) def _indexer_client(): """Instantiate and return Indexer client object.""" indexer_address = "http://localhost:8980" indexer_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" return indexer.IndexerClient(indexer_token, indexer_address) ## TRANSACTIONS def _add_transaction(sender, receiver, passphrase, amount, note): """Create and sign transaction from provided arguments. Returned non-empty tuple carries field where error was raised and description. If the first item is None then the error is non-field/integration error. Returned two-tuple of empty strings marks successful transaction. """ client = _algod_client() params = client.suggested_params() unsigned_txn = PaymentTxn(sender, params, receiver, amount, None, note.encode()) signed_txn = unsigned_txn.sign(mnemonic.to_private_key(passphrase)) transaction_id = client.send_transaction(signed_txn) _wait_for_confirmation(client, transaction_id, 4) return transaction_id def _wait_for_confirmation(client, transaction_id, timeout): """ Wait until the transaction is confirmed or rejected, or until 'timeout' number of rounds have passed. Args: transaction_id (str): the transaction to wait for timeout (int): maximum number of rounds to wait Returns: dict: pending transaction information, or throws an error if the transaction is not confirmed or rejected in the next timeout rounds """ start_round = client.status()["last-round"] + 1 current_round = start_round while current_round < start_round + timeout: try: pending_txn = client.pending_transaction_info(transaction_id) except Exception: return if pending_txn.get("confirmed-round", 0) > 0: return pending_txn elif pending_txn["pool-error"]: raise Exception("pool error: {}".format(pending_txn["pool-error"])) client.status_after_block(current_round) current_round += 1 raise Exception( "pending tx not found in timeout rounds, timeout value = : {}".format(timeout) ) def create_payment_transaction(escrow_address, params, receiver, amount): """Create and return payment transaction from provided arguments.""" return PaymentTxn(escrow_address, params, receiver, amount) def process_logic_sig_transaction(logic_sig, payment_transaction): """Create logic signature transaction and send it to the network.""" client = _algod_client() logic_sig_transaction = LogicSigTransaction(payment_transaction, logic_sig) transaction_id = client.send_transaction(logic_sig_transaction) _wait_for_confirmation(client, transaction_id, 4) return transaction_id def process_transactions(transactions): """Send provided grouped `transactions` to network and wait for confirmation.""" client = _algod_client() transaction_id = client.send_transactions(transactions) _wait_for_confirmation(client, transaction_id, 4) return transaction_id def suggested_params(): """Return the suggested params from the algod client.""" return _algod_client().suggested_params() ## CREATING def add_standalone_account(): """Create standalone account and return two-tuple of its private key and address.""" private_key, address = account.generate_account() return private_key, address def fund_account(address, initial_funds=1000000000): """Fund provided `address` with `initial_funds` amount of microAlgos.""" initial_funds_address = _initial_funds_address() if initial_funds_address is None: raise Exception("Initial funds weren't transferred!") _add_transaction( initial_funds_address, address, _cli_passphrase_for_account(initial_funds_address), initial_funds, "Initial funds", ) ## RETRIEVING def _initial_funds_address(): """Get the address of initially created account having enough funds. Such an account is used to transfer initial funds for the accounts created in this tutorial. """ return next( ( account.get("address") for account in _indexer_client().accounts().get("accounts", [{}, {}]) if account.get("created-at-round") == 0 and account.get("status") == "Offline" # "Online" for devMode ), None, ) def account_balance(address): """Return funds balance of the account having provided address.""" account_info = _algod_client().account_info(address) return account_info.get("amount") def transaction_info(transaction_id): """Return transaction with provided id.""" timeout = 0 while timeout < INDEXER_TIMEOUT: try: transaction = _indexer_client().transaction(transaction_id) break except IndexerHTTPError: time.sleep(1) timeout += 1 else: raise TimeoutError( "Timeout reached waiting for transaction to be available in indexer" ) return transaction ## UTILITY def _compile_source(source): """Compile and return teal binary code.""" compile_response = _algod_client().compile(source) return base64.b64decode(compile_response["result"]) def logic_signature(teal_source): """Create and return logic signature for provided `teal_source`.""" compiled_binary = _compile_source(teal_source) return LogicSig(compiled_binary)
[]
[]
[ "SANDBOX_DIR" ]
[]
["SANDBOX_DIR"]
python
1
0
column/float64_lc_test.go
package column_test import ( "context" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/vahid-sohrabloo/chconn" "github.com/vahid-sohrabloo/chconn/column" "github.com/vahid-sohrabloo/chconn/setting" ) func TestFloat64LC(t *testing.T) { t.Parallel() connString := os.Getenv("CHX_TEST_TCP_CONN_STRING") conn, err := chconn.Connect(context.Background(), connString) require.NoError(t, err) res, err := conn.Exec(context.Background(), `DROP TABLE IF EXISTS test_lc_float64`) require.NoError(t, err) require.Nil(t, res) settings := setting.NewSettings() settings.AllowSuspiciousLowCardinalityTypes(true) res, err = conn.ExecWithSetting(context.Background(), `CREATE TABLE test_lc_float64 ( float64_lc LowCardinality(Float64), float64_lc_nullable LowCardinality(Nullable(Float64)), float64_lc_array Array(LowCardinality(Float64)), float64_lc_array_nullable Array(LowCardinality(Nullable(Float64))) ) Engine=Memory`, settings) require.NoError(t, err) require.Nil(t, res) col := column.NewFloat64(false) colLC := column.NewLC(col) colNil := column.NewFloat64(true) colNilLC := column.NewLC(colNil) colArrayValues := column.NewFloat64(false) collArrayLC := column.NewLC(colArrayValues) colArray := column.NewArray(collArrayLC) colArrayValuesNil := column.NewFloat64(true) collArrayLCNil := column.NewLC(colArrayValuesNil) colArrayNil := column.NewArray(collArrayLCNil) var colInsert []float64 var colInsertArray [][]float64 var colInsertArrayNil [][]*float64 var colNilInsert []*float64 // var colMap rows := 10 for i := 1; i <= rows; i++ { val := float64(i * -4) valArray := []float64{val, float64(i*-4) + 1} valArrayNil := []*float64{&val, nil} col.AppendDict(val) colInsert = append(colInsert, val) // // example insert array colInsertArray = append(colInsertArray, valArray) colArray.AppendLen(len(valArray)) for _, v := range valArray { colArrayValues.AppendDict(v) } // example insert nullable array colInsertArrayNil = append(colInsertArrayNil, valArrayNil) colArrayNil.AppendLen(len(valArrayNil)) for _, v := range valArrayNil { colArrayValuesNil.AppendDictP(v) } // example add nullable if i%2 == 0 { colNilInsert = append(colNilInsert, &val) if i <= rows/2 { // example to add by poiner colNil.AppendDictP(&val) } else { // example to without poiner colNil.AppendDict(val) } } else { colNilInsert = append(colNilInsert, nil) if i <= rows/2 { // example to add by poiner colNil.AppendDictP(nil) } else { // example to add without poiner colNil.AppendDictNil() } } } insertstmt, err := conn.Insert(context.Background(), `INSERT INTO test_lc_float64(float64_lc,float64_lc_nullable,float64_lc_array,float64_lc_array_nullable) VALUES`) require.NoError(t, err) require.Nil(t, res) err = insertstmt.Commit(context.Background(), colLC, colNilLC, colArray, colArrayNil, ) require.NoError(t, err) // example read all selectStmt, err := conn.Select(context.Background(), `SELECT float64_lc, float64_lc_nullable,float64_lc_array,float64_lc_array_nullable FROM test_lc_float64`) require.NoError(t, err) require.True(t, conn.IsBusy()) colRead := column.NewFloat64(false) colLCRead := column.NewLC(colRead) colNilRead := column.NewFloat64(true) colNilLCRead := column.NewLC(colNilRead) colArrayReadData := column.NewFloat64(false) colArrayLCRead := column.NewLC(colArrayReadData) colArrayRead := column.NewArray(colArrayLCRead) colArrayReadDataNil := column.NewFloat64(true) colArrayLCReadNil := column.NewLC(colArrayReadDataNil) colArrayReadNil := column.NewArray(colArrayLCReadNil) var colDataDict []float64 var colDataKeys []int var colData []float64 var colNilDataDict []float64 var colNilDataKeys []int var colNilData []*float64 var colArrayDataDict []float64 var colArrayData [][]float64 var colArrayDataDictNil []float64 var colArrayDataNil [][]*float64 var colArrayLens []int for selectStmt.Next() { err = selectStmt.NextColumn(colLCRead) require.NoError(t, err) colRead.ReadAll(&colDataDict) colLCRead.ReadAll(&colDataKeys) for _, k := range colDataKeys { colData = append(colData, colDataDict[k]) } err = selectStmt.NextColumn(colNilLCRead) require.NoError(t, err) colNilRead.ReadAll(&colNilDataDict) colNilLCRead.ReadAll(&colNilDataKeys) for _, k := range colNilDataKeys { // 0 means nil if k == 0 { colNilData = append(colNilData, nil) } else { colNilData = append(colNilData, &colNilDataDict[k]) } } // read array colArrayLens = colArrayLens[:0] err = selectStmt.NextColumn(colArrayRead) require.NoError(t, err) colArrayRead.ReadAll(&colArrayLens) colArrayReadData.ReadAll(&colArrayDataDict) for _, l := range colArrayLens { arr := make([]int, l) arrData := make([]float64, l) colArrayLCRead.Fill(arr) for i, k := range arr { arrData[i] = colArrayDataDict[k] } colArrayData = append(colArrayData, arrData) } // read array nil colArrayLens = colArrayLens[:0] err = selectStmt.NextColumn(colArrayReadNil) require.NoError(t, err) colArrayReadNil.ReadAll(&colArrayLens) colArrayReadDataNil.ReadAll(&colArrayDataDictNil) for _, l := range colArrayLens { arr := make([]int, l) arrData := make([]*float64, l) colArrayLCReadNil.Fill(arr) for i, k := range arr { // 0 means nil if k == 0 { arrData[i] = nil } else { arrData[i] = &colArrayDataDictNil[k] } } colArrayDataNil = append(colArrayDataNil, arrData) } } require.NoError(t, selectStmt.Err()) assert.Equal(t, colInsert, colData) assert.Equal(t, colNilInsert, colNilData) assert.Equal(t, colInsertArray, colArrayData) assert.Equal(t, colInsertArrayNil, colArrayDataNil) selectStmt.Close() // example one by one selectStmt, err = conn.Select(context.Background(), `SELECT float64_lc,float64_lc_nullable FROM test_lc_float64`) require.NoError(t, err) require.True(t, conn.IsBusy()) colRead = column.NewFloat64(false) colLCRead = column.NewLC(colRead) colNilRead = column.NewFloat64(true) colNilLCRead = column.NewLC(colNilRead) colDataDict = colDataDict[:0] colData = colData[:0] colNilDataDict = colNilDataDict[:0] colNilData = colNilData[:0] for selectStmt.Next() { err = selectStmt.NextColumn(colLCRead) require.NoError(t, err) colRead.ReadAll(&colDataDict) for colLCRead.Next() { colData = append(colData, colDataDict[colLCRead.Value()]) } err = selectStmt.NextColumn(colNilLCRead) require.NoError(t, err) colNilRead.ReadAll(&colNilDataDict) for colNilLCRead.Next() { k := colNilLCRead.Value() // 0 means nil if k == 0 { colNilData = append(colNilData, nil) } else { colNilData = append(colNilData, &colNilDataDict[k]) } } } require.NoError(t, selectStmt.Err()) selectStmt.Close() assert.Equal(t, colInsert, colData) assert.Equal(t, colNilInsert, colNilData) conn.Close(context.Background()) }
[ "\"CHX_TEST_TCP_CONN_STRING\"" ]
[]
[ "CHX_TEST_TCP_CONN_STRING" ]
[]
["CHX_TEST_TCP_CONN_STRING"]
go
1
0
vendor/github.com/mongodb/jasper/vendor/github.com/tychoish/lru/buildscripts/render-gopath.go
// Simple script to print the current GOPATH with additional vendoring // component for legacy vendoring, as needed. Use in conjunction with // makefile configuration and the "make-vendor" script. package main import ( "fmt" "os" "path/filepath" "strings" "./vendoring" ) func main() { currentGoPath := os.Getenv("GOPATH") pwd, err := os.Getwd() // print error and exit if there's an error if err != nil { fmt.Println(err) os.Exit(1) } // initialize the gopath components. goPathParts := []string{currentGoPath} // if this version of go does not support new-style vendoring, // then we need to mangle the gopath so that the build can use // vendored dependencies. if vendoring.NeedsLegacy() { goPathParts = append(goPathParts, filepath.Join(pwd, vendoring.Path)) // add any additional paths to nested vendored gopaths. for _, path := range os.Args[1:] { absPath, err := filepath.Abs(path) if err == nil { goPathParts = append(goPathParts, absPath) } else { goPathParts = append(goPathParts, path) } } } fmt.Printf("GOPATH=%s", strings.Join(goPathParts, ":")) }
[ "\"GOPATH\"" ]
[]
[ "GOPATH" ]
[]
["GOPATH"]
go
1
0
cli/cmd/send_event_approvalFinished.go
package cmd import ( "bufio" "encoding/json" "errors" "fmt" "net/url" "os" "strconv" "strings" "text/tabwriter" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/google/uuid" apimodels "github.com/keptn/go-utils/pkg/api/models" apiutils "github.com/keptn/go-utils/pkg/api/utils" keptnevents "github.com/keptn/go-utils/pkg/lib" "github.com/keptn/keptn/cli/pkg/credentialmanager" "github.com/keptn/keptn/cli/pkg/logging" "github.com/mitchellh/mapstructure" "github.com/spf13/cobra" ) type sendApprovalFinishedStruct struct { Project *string `json:"project"` Stage *string `json:"stage"` Service *string `json:"service"` ID *string `json:"id"` } var sendApprovalFinishedOptions sendApprovalFinishedStruct var approvalFinishedCmd = &cobra.Command{ Use: "approval.finished", Short: "Sends an approval.finished event to Keptn in order to confirm an open approval " + "with the specified ID in the provided project and stage", Long: `Sends an approval.finished event to Keptn in order to confirm an open approval with the specified ID in the provided project and stage. * This command takes the project (*--project*) and stage (*--stage*). * It is optional to specify the ID (*--id*) of the corresponding approval.triggered event. If the ID is not provided, the command asks the user which open approval should be accepted or declined. * The open approval.triggered events and their ID can be retrieved using the "keptn get event approval.triggered --project=<project> --stage=<stage>" command. `, Example: `keptn send event approval.finished --project=sockshop --stage=hardening --id=1234-5678-9123`, PreRunE: func(cmd *cobra.Command, args []string) error { if *sendApprovalFinishedOptions.ID == "" && *sendApprovalFinishedOptions.Service == "" { logging.PrintLog("Either ID or service must be provided", logging.InfoLevel) return errors.New("either ID or service must be provided") } else if *sendApprovalFinishedOptions.ID != "" && *sendApprovalFinishedOptions.Service != "" { logging.PrintLog("Either ID or service must be provided", logging.InfoLevel) return errors.New("either ID or service must be provided") } return nil }, RunE: func(cmd *cobra.Command, args []string) error { return sendApprovalFinishedEvent(sendApprovalFinishedOptions) }, SilenceUsage: true, } func sendApprovalFinishedEvent(sendApprovalFinishedOptions sendApprovalFinishedStruct) error { var endPoint url.URL var apiToken string var err error if !mocking { endPoint, apiToken, err = credentialmanager.NewCredentialManager().GetCreds() } else { endPointPtr, _ := url.Parse(os.Getenv("MOCK_SERVER")) endPoint = *endPointPtr apiToken = "" } if err != nil { return errors.New(authErrorMsg) } logging.PrintLog("Starting to send approval.finished event", logging.InfoLevel) if endPointErr := checkEndPointStatus(endPoint.String()); endPointErr != nil { return fmt.Errorf("Error connecting to server: %s"+endPointErrorReasons, endPointErr) } apiHandler := apiutils.NewAuthenticatedAPIHandler(endPoint.String(), apiToken, "x-token", nil, endPoint.Scheme) eventHandler := apiutils.NewAuthenticatedEventHandler(endPoint.String(), apiToken, "x-token", nil, endPoint.Scheme) logging.PrintLog(fmt.Sprintf("Connecting to server %s", endPoint.String()), logging.VerboseLevel) var keptnContext string var triggeredID string var approvalFinishedEvent *keptnevents.ApprovalFinishedEventData if *sendApprovalFinishedOptions.ID != "" { keptnContext, triggeredID, approvalFinishedEvent, err = getApprovalFinishedForID(eventHandler, sendApprovalFinishedOptions) } else if *sendApprovalFinishedOptions.Service != "" { serviceHandler := apiutils.NewAuthenticatedServiceHandler(endPoint.String(), apiToken, "x-token", nil, endPoint.Scheme) keptnContext, triggeredID, approvalFinishedEvent, err = getApprovalFinishedForService(eventHandler, serviceHandler, sendApprovalFinishedOptions) } if err != nil { return err } if approvalFinishedEvent == nil { return nil } ID := uuid.New().String() source, _ := url.Parse("https://github.com/keptn/keptn/cli#approval.finished") sdkEvent := cloudevents.NewEvent() sdkEvent.SetID(ID) sdkEvent.SetType(keptnevents.ApprovalFinishedEventType) sdkEvent.SetSource(source.String()) sdkEvent.SetDataContentType(cloudevents.ApplicationJSON) sdkEvent.SetExtension("shkeptncontext", keptnContext) sdkEvent.SetExtension("triggeredid", triggeredID) sdkEvent.SetData(cloudevents.ApplicationJSON, approvalFinishedEvent) eventByte, err := json.Marshal(sdkEvent) if err != nil { return fmt.Errorf("Failed to marshal cloud event. %s", err.Error()) } apiEvent := apimodels.KeptnContextExtendedCE{} err = json.Unmarshal(eventByte, &apiEvent) if err != nil { return fmt.Errorf("Failed to map cloud event to API event model. %s", err.Error()) } responseEvent, errorObj := apiHandler.SendEvent(apiEvent) if errorObj != nil { logging.PrintLog("Send approval.triggered was unsuccessful", logging.QuietLevel) return fmt.Errorf("Send approval.triggered was unsuccessful. %s", *errorObj.Message) } if responseEvent == nil { logging.PrintLog("No event returned", logging.QuietLevel) return nil } return nil } func getApprovalFinishedForService(eventHandler *apiutils.EventHandler, serviceHandler *apiutils.ServiceHandler, approvalFinishedOptions sendApprovalFinishedStruct) (string, string, *keptnevents.ApprovalFinishedEventData, error) { svc, err := serviceHandler.GetService(*approvalFinishedOptions.Project, *approvalFinishedOptions.Stage, *approvalFinishedOptions.Service) if err != nil { logging.PrintLog("Open approval.triggered event for service "+*approvalFinishedOptions.Service+" could not be retrieved: "+err.Error(), logging.InfoLevel) return "", "", nil, err } if svc == nil { logging.PrintLog("Service "+*approvalFinishedOptions.Service+" could not be found", logging.InfoLevel) return "", "", nil, nil } if len(svc.OpenApprovals) == 0 { logging.PrintLog("No open approval.triggered event for service "+*approvalFinishedOptions.Service+" has been found", logging.InfoLevel) return "", "", nil, nil } // print all available options printApprovalOptions(svc.OpenApprovals, eventHandler, approvalFinishedOptions) // select option nrOfOptions := len(svc.OpenApprovals) selectedOption, err := selectApprovalOption(nrOfOptions) if err != nil { return "", "", nil, err } index := selectedOption - 1 eventToBeApproved := svc.OpenApprovals[index] // approve or decline? approve := approveOrDecline() events, errorObj := eventHandler.GetEvents(&apiutils.EventFilter{ Project: *approvalFinishedOptions.Project, Stage: *approvalFinishedOptions.Stage, EventType: keptnevents.ApprovalTriggeredEventType, EventID: eventToBeApproved.EventID, }) if errorObj != nil { logging.PrintLog("Cannot retrieve approval.triggered event with ID "+*approvalFinishedOptions.ID+": "+*errorObj.Message, logging.InfoLevel) return "", "", nil, errors.New(*errorObj.Message) } if len(events) == 0 { logging.PrintLog("No open approval.triggered event with the ID "+*approvalFinishedOptions.ID+" has been found", logging.InfoLevel) return "", "", nil, nil } approvalTriggeredEvent := &keptnevents.ApprovalTriggeredEventData{} err = mapstructure.Decode(events[0].Data, approvalTriggeredEvent) if err != nil { logging.PrintLog("Cannot decode approval.triggered event: "+err.Error(), logging.InfoLevel) return "", "", nil, err } var approvalResult string if approve { approvalResult = "pass" } else { approvalResult = "failed" } approvalFinishedEvent := &keptnevents.ApprovalFinishedEventData{ Project: approvalTriggeredEvent.Project, Service: approvalTriggeredEvent.Service, Stage: approvalTriggeredEvent.Stage, TestStrategy: approvalTriggeredEvent.TestStrategy, DeploymentStrategy: approvalTriggeredEvent.DeploymentStrategy, Tag: approvalTriggeredEvent.Tag, Image: approvalTriggeredEvent.Image, Labels: approvalTriggeredEvent.Labels, Approval: keptnevents.ApprovalData{ Result: approvalResult, Status: "succeeded", }, } return eventToBeApproved.KeptnContext, eventToBeApproved.EventID, approvalFinishedEvent, nil } func approveOrDecline() bool { var approve bool keepAsking := true for keepAsking { logging.PrintLog("Do you want to (a)pprove or (d)ecline: ", logging.InfoLevel) reader := bufio.NewReader(os.Stdin) in, err := reader.ReadString('\n') if err != nil { logging.PrintLog("Invalid option. Please enter either 'a' to approve, or 'd' to decline", logging.InfoLevel) } in = strings.TrimSpace(in) if in != "a" && in != "d" { logging.PrintLog("Invalid option. Please enter either 'a' to approve, or 'd' to decline", logging.InfoLevel) } else { keepAsking = false } if in == "a" { approve = true } else if in == "d" { approve = false } } return approve } func selectApprovalOption(nrOfOptions int) (int, error) { var selectedOption int keepAsking := true for keepAsking { logging.PrintLog("Select the option to approve or decline: ", logging.InfoLevel) reader := bufio.NewReader(os.Stdin) in, err := reader.ReadString('\n') if err != nil { logging.PrintLog(fmt.Sprintf("Invalid option. Please enter a value between 1 and %d", nrOfOptions), logging.InfoLevel) } in = strings.TrimSpace(in) selectedOption, err = strconv.Atoi(in) if err != nil || selectedOption < 1 || selectedOption > nrOfOptions { logging.PrintLog(fmt.Sprintf("Invalid option. Please enter a value between 1 and %d", nrOfOptions), logging.InfoLevel) } else { keepAsking = false } } return selectedOption, nil } func printApprovalOptions(approvals []*apimodels.Approval, eventHandler *apiutils.EventHandler, approvalFinishedOptions sendApprovalFinishedStruct) { // initialize tabwriter w := new(tabwriter.Writer) // minwidth, tabwidth, padding, padchar, flags w.Init(os.Stdout, 8, 8, 0, '\t', 0) defer w.Flush() fmt.Fprintf(w, "\n %s\t%s\t%s\t", "OPTION", "VERSION", "EVALUATION") for index, approval := range approvals { score := getScoreForApprovalTriggeredEvent(eventHandler, approvalFinishedOptions, approval) appendOptionToWriter(w, index, approval, score) } fmt.Fprintf(w, "\n") } func appendOptionToWriter(w *tabwriter.Writer, index int, approval *apimodels.Approval, score string) { fmt.Fprintf(w, "\n (%d)\t%s\t%s\t", index+1, approval.Tag, score) } func getScoreForApprovalTriggeredEvent(eventHandler *apiutils.EventHandler, approvalFinishedOptions sendApprovalFinishedStruct, approval *apimodels.Approval) string { score := "n/a" evaluationDoneEvents, errorObj := eventHandler.GetEvents(&apiutils.EventFilter{ Project: *approvalFinishedOptions.Project, Stage: *approvalFinishedOptions.Stage, Service: *approvalFinishedOptions.Service, EventType: keptnevents.EvaluationDoneEventType, KeptnContext: approval.KeptnContext, }) if errorObj != nil { return score } if len(evaluationDoneEvents) == 0 { return score } evaluationDoneData := &keptnevents.EvaluationDoneEventData{} err := mapstructure.Decode(evaluationDoneEvents[0].Data, evaluationDoneData) if err != nil { return score } if evaluationDoneData.EvaluationDetails != nil { score = fmt.Sprintf("%f", evaluationDoneData.EvaluationDetails.Score) } return score } func getApprovalFinishedForID(eventHandler *apiutils.EventHandler, sendApprovalFinishedOptions sendApprovalFinishedStruct) (string, string, *keptnevents.ApprovalFinishedEventData, error) { events, errorObj := eventHandler.GetEvents(&apiutils.EventFilter{ Project: *sendApprovalFinishedOptions.Project, Stage: *sendApprovalFinishedOptions.Stage, EventType: keptnevents.ApprovalTriggeredEventType, EventID: *sendApprovalFinishedOptions.ID, }) if errorObj != nil { logging.PrintLog("Cannot retrieve approval.triggered event with ID "+*sendApprovalFinishedOptions.ID+": "+*errorObj.Message, logging.InfoLevel) return "", "", nil, errors.New(*errorObj.Message) } if len(events) == 0 { logging.PrintLog("No open approval.triggered event with the ID "+*sendApprovalFinishedOptions.ID+" has been found", logging.InfoLevel) return "", "", nil, nil } approvalTriggeredEvent := &keptnevents.ApprovalTriggeredEventData{} err := mapstructure.Decode(events[0].Data, approvalTriggeredEvent) if err != nil { logging.PrintLog("Cannot decode approval.triggered event: "+err.Error(), logging.InfoLevel) return "", "", nil, err } approvalFinishedEvent := &keptnevents.ApprovalFinishedEventData{ Project: approvalTriggeredEvent.Project, Service: approvalTriggeredEvent.Service, Stage: approvalTriggeredEvent.Stage, TestStrategy: approvalTriggeredEvent.TestStrategy, DeploymentStrategy: approvalTriggeredEvent.DeploymentStrategy, Tag: approvalTriggeredEvent.Tag, Image: approvalTriggeredEvent.Image, Labels: approvalTriggeredEvent.Labels, Approval: keptnevents.ApprovalData{ Result: "pass", Status: "succeeded", }, } return events[0].Shkeptncontext, events[0].ID, approvalFinishedEvent, nil } func init() { sendEventCmd.AddCommand(approvalFinishedCmd) sendApprovalFinishedOptions.Project = approvalFinishedCmd.Flags().StringP("project", "", "", "The project containing the service to be approved") approvalFinishedCmd.MarkFlagRequired("project") sendApprovalFinishedOptions.Stage = approvalFinishedCmd.Flags().StringP("stage", "", "", "The stage containing the service to be approved") approvalFinishedCmd.MarkFlagRequired("stage") sendApprovalFinishedOptions.Service = approvalFinishedCmd.Flags().StringP("service", "", "", "The service to be approved") sendApprovalFinishedOptions.ID = approvalFinishedCmd.Flags().StringP("id", "", "", "The ID of the approval.triggered event to be approved") // approvalFinishedCmd.MarkFlagRequired("id") }
[ "\"MOCK_SERVER\"" ]
[]
[ "MOCK_SERVER" ]
[]
["MOCK_SERVER"]
go
1
0
test/units/modules/cloud/amazon/test_ec2_vpc_vpn.py
# (c) 2017 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import pytest import os from units.utils.amazon_placebo_fixtures import placeboify, maybe_sleep from ansible.modules.cloud.amazon import ec2_vpc_vpn from ansible.module_utils._text import to_text from ansible.module_utils.ec2 import get_aws_connection_info, boto3_conn, boto3_tag_list_to_ansible_dict class FakeModule(object): def __init__(self, **kwargs): self.params = kwargs def fail_json(self, *args, **kwargs): self.exit_args = args self.exit_kwargs = kwargs raise Exception('FAIL') def exit_json(self, *args, **kwargs): self.exit_args = args self.exit_kwargs = kwargs def get_vgw(connection): # see if two vgw exist and return them if so vgw = connection.describe_vpn_gateways(Filters=[{'Name': 'tag:Ansible_VPN', 'Values': ['Test']}]) if len(vgw['VpnGateways']) >= 2: return [vgw['VpnGateways'][0]['VpnGatewayId'], vgw['VpnGateways'][1]['VpnGatewayId']] # otherwise create two and return them vgw_1 = connection.create_vpn_gateway(Type='ipsec.1') vgw_2 = connection.create_vpn_gateway(Type='ipsec.1') for resource in (vgw_1, vgw_2): connection.create_tags(Resources=[resource['VpnGateway']['VpnGatewayId']], Tags=[{'Key': 'Ansible_VPN', 'Value': 'Test'}]) return [vgw_1['VpnGateway']['VpnGatewayId'], vgw_2['VpnGateway']['VpnGatewayId']] def get_cgw(connection): # see if two cgw exist and return them if so cgw = connection.describe_customer_gateways(DryRun=False, Filters=[{'Name': 'state', 'Values': ['available']}, {'Name': 'tag:Name', 'Values': ['Ansible-CGW']}]) if len(cgw['CustomerGateways']) >= 2: return [cgw['CustomerGateways'][0]['CustomerGatewayId'], cgw['CustomerGateways'][1]['CustomerGatewayId']] # otherwise create and return them cgw_1 = connection.create_customer_gateway(DryRun=False, Type='ipsec.1', PublicIp='9.8.7.6', BgpAsn=65000) cgw_2 = connection.create_customer_gateway(DryRun=False, Type='ipsec.1', PublicIp='5.4.3.2', BgpAsn=65000) for resource in (cgw_1, cgw_2): connection.create_tags(Resources=[resource['CustomerGateway']['CustomerGatewayId']], Tags=[{'Key': 'Ansible-CGW', 'Value': 'Test'}]) return [cgw_1['CustomerGateway']['CustomerGatewayId'], cgw_2['CustomerGateway']['CustomerGatewayId']] def get_dependencies(): if os.getenv('PLACEBO_RECORD'): module = FakeModule(**{}) region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) vgw = get_vgw(connection) cgw = get_cgw(connection) else: vgw = ["vgw-35d70c2b", "vgw-32d70c2c"] cgw = ["cgw-6113c87f", "cgw-9e13c880"] return cgw, vgw def setup_mod_conn(placeboify, params): conn = placeboify.client('ec2') m = FakeModule(**params) return m, conn def make_params(cgw, vgw, tags=None, filters=None, routes=None): tags = {} if tags is None else tags filters = {} if filters is None else filters routes = [] if routes is None else routes return {'customer_gateway_id': cgw, 'static_only': True, 'vpn_gateway_id': vgw, 'connection_type': 'ipsec.1', 'purge_tags': True, 'tags': tags, 'filters': filters, 'routes': routes} def make_conn(placeboify, module, connection): customer_gateway_id = module.params['customer_gateway_id'] static_only = module.params['static_only'] vpn_gateway_id = module.params['vpn_gateway_id'] connection_type = module.params['connection_type'] check_mode = module.params['check_mode'] changed = True vpn = ec2_vpc_vpn.create_connection(connection, customer_gateway_id, static_only, vpn_gateway_id, connection_type) return changed, vpn def tear_down_conn(placeboify, connection, vpn_connection_id): ec2_vpc_vpn.delete_connection(connection, vpn_connection_id) def test_find_connection_vpc_conn_id(placeboify, maybe_sleep): # setup dependencies for 2 vpn connections dependencies = setup_req(placeboify, 2) dep1, dep2 = dependencies[0], dependencies[1] params1, vpn1, m1, conn1 = dep1['params'], dep1['vpn'], dep1['module'], dep1['connection'] params2, vpn2, m2, conn2 = dep2['params'], dep2['vpn'], dep2['module'], dep2['connection'] # find the connection with a vpn_connection_id and assert it is the expected one assert vpn1['VpnConnectionId'] == ec2_vpc_vpn.find_connection(conn1, params1, vpn1['VpnConnectionId'])['VpnConnectionId'] tear_down_conn(placeboify, conn1, vpn1['VpnConnectionId']) tear_down_conn(placeboify, conn2, vpn2['VpnConnectionId']) def test_find_connection_filters(placeboify, maybe_sleep): # setup dependencies for 2 vpn connections dependencies = setup_req(placeboify, 2) dep1, dep2 = dependencies[0], dependencies[1] params1, vpn1, m1, conn1 = dep1['params'], dep1['vpn'], dep1['module'], dep1['connection'] params2, vpn2, m2, conn2 = dep2['params'], dep2['vpn'], dep2['module'], dep2['connection'] # update to different tags params1.update(tags={'Wrong': 'Tag'}) params2.update(tags={'Correct': 'Tag'}) ec2_vpc_vpn.ensure_present(conn1, params1) ec2_vpc_vpn.ensure_present(conn2, params2) # create some new parameters for a filter params = {'filters': {'tags': {'Correct': 'Tag'}}} # find the connection that has the parameters above found = ec2_vpc_vpn.find_connection(conn1, params) # assert the correct connection was found assert found['VpnConnectionId'] == vpn2['VpnConnectionId'] # delete the connections tear_down_conn(placeboify, conn1, vpn1['VpnConnectionId']) tear_down_conn(placeboify, conn2, vpn2['VpnConnectionId']) def test_find_connection_insufficient_filters(placeboify, maybe_sleep): # get list of customer gateways and virtual private gateways cgw, vgw = get_dependencies() # create two connections with the same tags params = make_params(cgw[0], vgw[0], tags={'Correct': 'Tag'}) params2 = make_params(cgw[1], vgw[1], tags={'Correct': 'Tag'}) m, conn = setup_mod_conn(placeboify, params) m2, conn2 = setup_mod_conn(placeboify, params2) _, vpn1 = ec2_vpc_vpn.ensure_present(conn, m.params) _, vpn2 = ec2_vpc_vpn.ensure_present(conn2, m2.params) # reset the parameters so only filtering by tags will occur m.params = {'filters': {'tags': {'Correct': 'Tag'}}} # assert that multiple matching connections have been found with pytest.raises(Exception) as error_message: ec2_vpc_vpn.find_connection(conn, m.params) assert error_message == "More than one matching VPN connection was found.To modify or delete a VPN please specify vpn_connection_id or add filters." # delete the connections tear_down_conn(placeboify, conn, vpn1['VpnConnectionId']) tear_down_conn(placeboify, conn, vpn2['VpnConnectionId']) def test_find_connection_nonexistent(placeboify, maybe_sleep): # create parameters but don't create a connection with them params = {'filters': {'tags': {'Correct': 'Tag'}}} m, conn = setup_mod_conn(placeboify, params) # try to find a connection with matching parameters and assert None are found assert ec2_vpc_vpn.find_connection(conn, m.params) is None def test_create_connection(placeboify, maybe_sleep): # get list of customer gateways and virtual private gateways cgw, vgw = get_dependencies() # create a connection params = make_params(cgw[0], vgw[0]) m, conn = setup_mod_conn(placeboify, params) changed, vpn = ec2_vpc_vpn.ensure_present(conn, m.params) # assert that changed is true and that there is a connection id assert changed is True assert 'VpnConnectionId' in vpn # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def test_create_connection_that_exists(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # try to recreate the same connection changed, vpn2 = ec2_vpc_vpn.ensure_present(conn, params) # nothing should have changed assert changed is False assert vpn['VpnConnectionId'] == vpn2['VpnConnectionId'] # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def test_modify_deleted_connection(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # delete it tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) # try to update the deleted connection m.params.update(vpn_connection_id=vpn['VpnConnectionId']) with pytest.raises(Exception) as error_message: ec2_vpc_vpn.ensure_present(conn, m.params) assert error_message == "There is no VPN connection available or pending with that id. Did you delete it?" def test_delete_connection(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # delete it changed, vpn = ec2_vpc_vpn.ensure_absent(conn, m.params) assert changed is True assert vpn == {} def test_delete_nonexistent_connection(placeboify, maybe_sleep): # create parameters and ensure any connection matching (None) is deleted params = {'filters': {'tags': {'ThisConnection': 'DoesntExist'}}} m, conn = setup_mod_conn(placeboify, params) changed, vpn = ec2_vpc_vpn.ensure_absent(conn, m.params) assert changed is False assert vpn == {} def test_check_for_update_tags(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # add and remove a number of tags m.params['tags'] = {'One': 'one', 'Two': 'two'} ec2_vpc_vpn.ensure_present(conn, m.params) m.params['tags'] = {'Two': 'two', 'Three': 'three', 'Four': 'four'} changes = ec2_vpc_vpn.check_for_update(conn, m.params, vpn['VpnConnectionId']) flat_dict_changes = boto3_tag_list_to_ansible_dict(changes['tags_to_add']) correct_changes = boto3_tag_list_to_ansible_dict([{'Key': 'Three', 'Value': 'three'}, {'Key': 'Four', 'Value': 'four'}]) assert flat_dict_changes == correct_changes assert changes['tags_to_remove'] == ['One'] # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def test_check_for_update_nonmodifiable_attr(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] current_vgw = params['vpn_gateway_id'] # update a parameter that isn't modifiable m.params.update(vpn_gateway_id="invalidchange") err = 'You cannot modify vpn_gateway_id, the current value of which is {0}. Modifiable VPN connection attributes are tags.'.format(current_vgw) with pytest.raises(Exception) as error_message: ec2_vpc_vpn.check_for_update(m, conn, vpn['VpnConnectionId']) assert error_message == err # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def test_add_tags(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # add a tag to the connection ec2_vpc_vpn.add_tags(conn, vpn['VpnConnectionId'], add=[{'Key': 'Ansible-Test', 'Value': 'VPN'}]) # assert tag is there current_vpn = ec2_vpc_vpn.find_connection(conn, params) assert current_vpn['Tags'] == [{'Key': 'Ansible-Test', 'Value': 'VPN'}] # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def test_remove_tags(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # remove a tag from the connection ec2_vpc_vpn.remove_tags(conn, vpn['VpnConnectionId'], remove=['Ansible-Test']) # assert the tag is gone current_vpn = ec2_vpc_vpn.find_connection(conn, params) assert 'Tags' not in current_vpn # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def test_add_routes(placeboify, maybe_sleep): # setup dependencies for 1 vpn connection dependencies = setup_req(placeboify, 1) params, vpn, m, conn = dependencies['params'], dependencies['vpn'], dependencies['module'], dependencies['connection'] # create connection with a route ec2_vpc_vpn.add_routes(conn, vpn['VpnConnectionId'], ['195.168.2.0/24', '196.168.2.0/24']) # assert both routes are there current_vpn = ec2_vpc_vpn.find_connection(conn, params) assert set(each['DestinationCidrBlock'] for each in current_vpn['Routes']) == set(['195.168.2.0/24', '196.168.2.0/24']) # delete connection tear_down_conn(placeboify, conn, vpn['VpnConnectionId']) def setup_req(placeboify, number_of_results=1): ''' returns dependencies for VPN connections ''' assert number_of_results in (1, 2) results = [] cgw, vgw = get_dependencies() for each in range(0, number_of_results): params = make_params(cgw[each], vgw[each]) m, conn = setup_mod_conn(placeboify, params) _, vpn = ec2_vpc_vpn.ensure_present(conn, params) results.append({'module': m, 'connection': conn, 'vpn': vpn, 'params': params}) if number_of_results == 1: return results[0] else: return results[0], results[1]
[]
[]
[ "PLACEBO_RECORD" ]
[]
["PLACEBO_RECORD"]
python
1
0
cmd/nginx-ingress/main.go
package main import ( "context" "flag" "fmt" "net" "net/http" "os" "os/signal" "regexp" "strings" "syscall" "time" "github.com/golang/glog" "github.com/nginxinc/kubernetes-ingress/internal/configs" "github.com/nginxinc/kubernetes-ingress/internal/configs/version1" "github.com/nginxinc/kubernetes-ingress/internal/configs/version2" "github.com/nginxinc/kubernetes-ingress/internal/k8s" "github.com/nginxinc/kubernetes-ingress/internal/k8s/secrets" "github.com/nginxinc/kubernetes-ingress/internal/metrics" "github.com/nginxinc/kubernetes-ingress/internal/metrics/collectors" "github.com/nginxinc/kubernetes-ingress/internal/nginx" cr_validation "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/validation" k8s_nginx "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned" conf_scheme "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned/scheme" "github.com/nginxinc/nginx-plus-go-client/client" nginxCollector "github.com/nginxinc/nginx-prometheus-exporter/collector" "github.com/prometheus/client_golang/prometheus" api_v1 "k8s.io/api/core/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation" util_version "k8s.io/apimachinery/pkg/util/version" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" ) var ( // Set during build version string gitCommit string healthStatus = flag.Bool("health-status", false, `Add a location based on the value of health-status-uri to the default server. The location responds with the 200 status code for any request. Useful for external health-checking of the Ingress controller`) healthStatusURI = flag.String("health-status-uri", "/nginx-health", `Sets the URI of health status location in the default server. Requires -health-status`) proxyURL = flag.String("proxy", "", `Use a proxy server to connect to Kubernetes API started by "kubectl proxy" command. For testing purposes only. The Ingress controller does not start NGINX and does not write any generated NGINX configuration files to disk`) watchNamespace = flag.String("watch-namespace", api_v1.NamespaceAll, `Namespace to watch for Ingress resources. By default the Ingress controller watches all namespaces`) nginxConfigMaps = flag.String("nginx-configmaps", "", `A ConfigMap resource for customizing NGINX configuration. If a ConfigMap is set, but the Ingress controller is not able to fetch it from Kubernetes API, the Ingress controller will fail to start. Format: <namespace>/<name>`) nginxPlus = flag.Bool("nginx-plus", false, "Enable support for NGINX Plus") appProtect = flag.Bool("enable-app-protect", false, "Enable support for NGINX App Protect. Requires -nginx-plus.") ingressClass = flag.String("ingress-class", "nginx", `A class of the Ingress controller. For Kubernetes >= 1.18, a corresponding IngressClass resource with the name equal to the class must be deployed. Otherwise, the Ingress Controller will fail to start. The Ingress controller only processes resources that belong to its class - i.e. have the "ingressClassName" field resource equal to the class. For Kubernetes < 1.18, the Ingress Controller only processes resources that belong to its class - i.e have the annotation "kubernetes.io/ingress.class" equal to the class. Additionally, the Ingress Controller processes resources that do not have the class set, which can be disabled by setting the "-use-ingress-class-only" flag The Ingress Controller processes all the VirtualServer/VirtualServerRoute resources that do not have the "ingressClassName" field for all versions of kubernetes.`) useIngressClassOnly = flag.Bool("use-ingress-class-only", false, `For kubernetes versions >= 1.18 this flag will be IGNORED. Ignore Ingress resources without the "kubernetes.io/ingress.class" annotation`) defaultServerSecret = flag.String("default-server-tls-secret", "", `A Secret with a TLS certificate and key for TLS termination of the default server. Format: <namespace>/<name>. If not set, certificate and key in the file "/etc/nginx/secrets/default" are used. If a secret is set, but the Ingress controller is not able to fetch it from Kubernetes API or a secret is not set and the file "/etc/nginx/secrets/default" does not exist, the Ingress controller will fail to start`) versionFlag = flag.Bool("version", false, "Print the version and git-commit hash and exit") mainTemplatePath = flag.String("main-template-path", "", `Path to the main NGINX configuration template. (default for NGINX "nginx.tmpl"; default for NGINX Plus "nginx-plus.tmpl")`) ingressTemplatePath = flag.String("ingress-template-path", "", `Path to the ingress NGINX configuration template for an ingress resource. (default for NGINX "nginx.ingress.tmpl"; default for NGINX Plus "nginx-plus.ingress.tmpl")`) virtualServerTemplatePath = flag.String("virtualserver-template-path", "", `Path to the VirtualServer NGINX configuration template for a VirtualServer resource. (default for NGINX "nginx.virtualserver.tmpl"; default for NGINX Plus "nginx-plus.virtualserver.tmpl")`) transportServerTemplatePath = flag.String("transportserver-template-path", "", `Path to the TransportServer NGINX configuration template for a TransportServer resource. (default for NGINX "nginx.transportserver.tmpl"; default for NGINX Plus "nginx-plus.transportserver.tmpl")`) externalService = flag.String("external-service", "", `Specifies the name of the service with the type LoadBalancer through which the Ingress controller pods are exposed externally. The external address of the service is used when reporting the status of Ingress, VirtualServer and VirtualServerRoute resources. For Ingress resources only: Requires -report-ingress-status.`) ingressLink = flag.String("ingresslink", "", `Specifies the name of the IngressLink resource, which exposes the Ingress Controller pods via a BIG-IP system. The IP of the BIG-IP system is used when reporting the status of Ingress, VirtualServer and VirtualServerRoute resources. For Ingress resources only: Requires -report-ingress-status.`) reportIngressStatus = flag.Bool("report-ingress-status", false, "Updates the address field in the status of Ingress resources. Requires the -external-service or -ingresslink flag, or the 'external-status-address' key in the ConfigMap.") leaderElectionEnabled = flag.Bool("enable-leader-election", true, "Enable Leader election to avoid multiple replicas of the controller reporting the status of Ingress, VirtualServer and VirtualServerRoute resources -- only one replica will report status (default true). See -report-ingress-status flag.") leaderElectionLockName = flag.String("leader-election-lock-name", "nginx-ingress-leader-election", `Specifies the name of the ConfigMap, within the same namespace as the controller, used as the lock for leader election. Requires -enable-leader-election.`) nginxStatusAllowCIDRs = flag.String("nginx-status-allow-cidrs", "127.0.0.1", `Add IPv4 IP/CIDR blocks to the allow list for NGINX stub_status or the NGINX Plus API. Separate multiple IP/CIDR by commas.`) nginxStatusPort = flag.Int("nginx-status-port", 8080, "Set the port where the NGINX stub_status or the NGINX Plus API is exposed. [1024 - 65535]") nginxStatus = flag.Bool("nginx-status", true, "Enable the NGINX stub_status, or the NGINX Plus API.") nginxDebug = flag.Bool("nginx-debug", false, "Enable debugging for NGINX. Uses the nginx-debug binary. Requires 'error-log-level: debug' in the ConfigMap.") nginxReloadTimeout = flag.Int("nginx-reload-timeout", 0, `The timeout in milliseconds which the Ingress Controller will wait for a successful NGINX reload after a change or at the initial start. The default is 4000 (or 20000 if -enable-app-protect is true). If set to 0, the default value will be used`) wildcardTLSSecret = flag.String("wildcard-tls-secret", "", `A Secret with a TLS certificate and key for TLS termination of every Ingress host for which TLS termination is enabled but the Secret is not specified. Format: <namespace>/<name>. If the argument is not set, for such Ingress hosts NGINX will break any attempt to establish a TLS connection. If the argument is set, but the Ingress controller is not able to fetch the Secret from Kubernetes API, the Ingress controller will fail to start.`) enablePrometheusMetrics = flag.Bool("enable-prometheus-metrics", false, "Enable exposing NGINX or NGINX Plus metrics in the Prometheus format") prometheusMetricsListenPort = flag.Int("prometheus-metrics-listen-port", 9113, "Set the port where the Prometheus metrics are exposed. [1024 - 65535]") enableCustomResources = flag.Bool("enable-custom-resources", true, "Enable custom resources") enablePreviewPolicies = flag.Bool("enable-preview-policies", false, "Enable preview policies") enableSnippets = flag.Bool("enable-snippets", false, "Enable custom NGINX configuration snippets in VirtualServer and VirtualServerRoute resources.") globalConfiguration = flag.String("global-configuration", "", `A GlobalConfiguration resource for global configuration of the Ingress Controller. Requires -enable-custom-resources. If the flag is set, but the Ingress controller is not able to fetch the corresponding resource from Kubernetes API, the Ingress Controller will fail to start. Format: <namespace>/<name>`) enableTLSPassthrough = flag.Bool("enable-tls-passthrough", false, "Enable TLS Passthrough on port 443. Requires -enable-custom-resources") spireAgentAddress = flag.String("spire-agent-address", "", `Specifies the address of the running Spire agent. Requires -nginx-plus and is for use with NGINX Service Mesh only. If the flag is set, but the Ingress Controller is not able to connect with the Spire Agent, the Ingress Controller will fail to start.`) enableInternalRoutes = flag.Bool("enable-internal-routes", false, `Enable support for internal routes with NGINX Service Mesh. Requires -spire-agent-address and -nginx-plus. Is for use with NGINX Service Mesh only.`) readyStatus = flag.Bool("ready-status", true, "Enables the readiness endpoint '/nginx-ready'. The endpoint returns a success code when NGINX has loaded all the config after the startup") readyStatusPort = flag.Int("ready-status-port", 8081, "Set the port where the readiness endpoint is exposed. [1024 - 65535]") enableLatencyMetrics = flag.Bool("enable-latency-metrics", false, "Enable collection of latency metrics for upstreams. Requires -enable-prometheus-metrics") ) func main() { flag.Parse() err := flag.Lookup("logtostderr").Value.Set("true") if err != nil { glog.Fatalf("Error setting logtostderr to true: %v", err) } if *versionFlag { fmt.Printf("Version=%v GitCommit=%v\n", version, gitCommit) os.Exit(0) } healthStatusURIValidationError := validateLocation(*healthStatusURI) if healthStatusURIValidationError != nil { glog.Fatalf("Invalid value for health-status-uri: %v", healthStatusURIValidationError) } statusLockNameValidationError := validateResourceName(*leaderElectionLockName) if statusLockNameValidationError != nil { glog.Fatalf("Invalid value for leader-election-lock-name: %v", statusLockNameValidationError) } statusPortValidationError := validatePort(*nginxStatusPort) if statusPortValidationError != nil { glog.Fatalf("Invalid value for nginx-status-port: %v", statusPortValidationError) } metricsPortValidationError := validatePort(*prometheusMetricsListenPort) if metricsPortValidationError != nil { glog.Fatalf("Invalid value for prometheus-metrics-listen-port: %v", metricsPortValidationError) } readyStatusPortValidationError := validatePort(*readyStatusPort) if readyStatusPortValidationError != nil { glog.Fatalf("Invalid value for ready-status-port: %v", readyStatusPortValidationError) } allowedCIDRs, err := parseNginxStatusAllowCIDRs(*nginxStatusAllowCIDRs) if err != nil { glog.Fatalf(`Invalid value for nginx-status-allow-cidrs: %v`, err) } if *enableTLSPassthrough && !*enableCustomResources { glog.Fatal("enable-tls-passthrough flag requires -enable-custom-resources") } if *appProtect && !*nginxPlus { glog.Fatal("NGINX App Protect support is for NGINX Plus only") } if *spireAgentAddress != "" && !*nginxPlus { glog.Fatal("spire-agent-address support is for NGINX Plus only") } if *enableInternalRoutes && *spireAgentAddress == "" { glog.Fatal("enable-internal-routes flag requires spire-agent-address") } if *enableLatencyMetrics && !*enablePrometheusMetrics { glog.Warning("enable-latency-metrics flag requires enable-prometheus-metrics, latency metrics will not be collected") *enableLatencyMetrics = false } if *ingressLink != "" && *externalService != "" { glog.Fatal("ingresslink and external-service cannot both be set") } glog.Infof("Starting NGINX Ingress controller Version=%v GitCommit=%v\n", version, gitCommit) var config *rest.Config if *proxyURL != "" { config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig( &clientcmd.ClientConfigLoadingRules{}, &clientcmd.ConfigOverrides{ ClusterInfo: clientcmdapi.Cluster{ Server: *proxyURL, }, }).ClientConfig() if err != nil { glog.Fatalf("error creating client configuration: %v", err) } } else { if config, err = rest.InClusterConfig(); err != nil { glog.Fatalf("error creating client configuration: %v", err) } } kubeClient, err := kubernetes.NewForConfig(config) if err != nil { glog.Fatalf("Failed to create client: %v.", err) } k8sVersion, err := k8s.GetK8sVersion(kubeClient) if err != nil { glog.Fatalf("error retrieving k8s version: %v", err) } minK8sVersion := minVersion("1.14.0") if !k8sVersion.AtLeast(minK8sVersion) { glog.Fatalf("Versions of Kubernetes < %v are not supported, please refer to the documentation for details on supported versions.", minK8sVersion) } // Ingress V1 is only available from k8s > 1.18 ingressV1Version := minVersion("1.18.0") if k8sVersion.AtLeast(ingressV1Version) { *useIngressClassOnly = true glog.Warningln("The '-use-ingress-class-only' flag will be deprecated and has no effect on versions of kubernetes >= 1.18.0. Processing ONLY resources that have the 'ingressClassName' field in Ingress equal to the class.") ingressClassRes, err := kubeClient.NetworkingV1beta1().IngressClasses().Get(context.TODO(), *ingressClass, meta_v1.GetOptions{}) if err != nil { glog.Fatalf("Error when getting IngressClass %v: %v", *ingressClass, err) } if ingressClassRes.Spec.Controller != k8s.IngressControllerName { glog.Fatalf("IngressClass with name %v has an invalid Spec.Controller %v", ingressClassRes.Name, ingressClassRes.Spec.Controller) } } var dynClient dynamic.Interface if *appProtect || *ingressLink != "" { dynClient, err = dynamic.NewForConfig(config) if err != nil { glog.Fatalf("Failed to create dynamic client: %v.", err) } } var confClient k8s_nginx.Interface if *enableCustomResources { confClient, err = k8s_nginx.NewForConfig(config) if err != nil { glog.Fatalf("Failed to create a conf client: %v", err) } // required for emitting Events for VirtualServer err = conf_scheme.AddToScheme(scheme.Scheme) if err != nil { glog.Fatalf("Failed to add configuration types to the scheme: %v", err) } } nginxConfTemplatePath := "nginx.tmpl" nginxIngressTemplatePath := "nginx.ingress.tmpl" nginxVirtualServerTemplatePath := "nginx.virtualserver.tmpl" nginxTransportServerTemplatePath := "nginx.transportserver.tmpl" if *nginxPlus { nginxConfTemplatePath = "nginx-plus.tmpl" nginxIngressTemplatePath = "nginx-plus.ingress.tmpl" nginxVirtualServerTemplatePath = "nginx-plus.virtualserver.tmpl" nginxTransportServerTemplatePath = "nginx-plus.transportserver.tmpl" } if *mainTemplatePath != "" { nginxConfTemplatePath = *mainTemplatePath } if *ingressTemplatePath != "" { nginxIngressTemplatePath = *ingressTemplatePath } if *virtualServerTemplatePath != "" { nginxVirtualServerTemplatePath = *virtualServerTemplatePath } if *transportServerTemplatePath != "" { nginxTransportServerTemplatePath = *transportServerTemplatePath } nginxBinaryPath := "/usr/sbin/nginx" if *nginxDebug { nginxBinaryPath = "/usr/sbin/nginx-debug" } templateExecutor, err := version1.NewTemplateExecutor(nginxConfTemplatePath, nginxIngressTemplatePath) if err != nil { glog.Fatalf("Error creating TemplateExecutor: %v", err) } templateExecutorV2, err := version2.NewTemplateExecutor(nginxVirtualServerTemplatePath, nginxTransportServerTemplatePath) if err != nil { glog.Fatalf("Error creating TemplateExecutorV2: %v", err) } var registry *prometheus.Registry var managerCollector collectors.ManagerCollector var controllerCollector collectors.ControllerCollector var latencyCollector collectors.LatencyCollector constLabels := map[string]string{"class": *ingressClass} managerCollector = collectors.NewManagerFakeCollector() controllerCollector = collectors.NewControllerFakeCollector() latencyCollector = collectors.NewLatencyFakeCollector() if *enablePrometheusMetrics { registry = prometheus.NewRegistry() managerCollector = collectors.NewLocalManagerMetricsCollector(constLabels) controllerCollector = collectors.NewControllerMetricsCollector(*enableCustomResources, constLabels) processCollector := collectors.NewNginxProcessesMetricsCollector(constLabels) workQueueCollector := collectors.NewWorkQueueMetricsCollector(constLabels) err = managerCollector.Register(registry) if err != nil { glog.Errorf("Error registering Manager Prometheus metrics: %v", err) } err = controllerCollector.Register(registry) if err != nil { glog.Errorf("Error registering Controller Prometheus metrics: %v", err) } err = processCollector.Register(registry) if err != nil { glog.Errorf("Error registering NginxProcess Prometheus metrics: %v", err) } err = workQueueCollector.Register(registry) if err != nil { glog.Errorf("Error registering WorkQueue Prometheus metrics: %v", err) } } useFakeNginxManager := *proxyURL != "" var nginxManager nginx.Manager if useFakeNginxManager { nginxManager = nginx.NewFakeManager("/etc/nginx") } else { nginxManager = nginx.NewLocalManager("/etc/nginx/", nginxBinaryPath, managerCollector, parseReloadTimeout(*appProtect, *nginxReloadTimeout)) } var aPPluginDone chan error var aPAgentDone chan error if *appProtect { aPPluginDone = make(chan error, 1) aPAgentDone = make(chan error, 1) nginxManager.AppProtectAgentStart(aPAgentDone, *nginxDebug) nginxManager.AppProtectPluginStart(aPPluginDone) } if *defaultServerSecret != "" { secret, err := getAndValidateSecret(kubeClient, *defaultServerSecret) if err != nil { glog.Fatalf("Error trying to get the default server TLS secret %v: %v", *defaultServerSecret, err) } bytes := configs.GenerateCertAndKeyFileContent(secret) nginxManager.CreateSecret(configs.DefaultServerSecretName, bytes, nginx.TLSSecretFileMode) } else { _, err = os.Stat("/etc/nginx/secrets/default") if os.IsNotExist(err) { glog.Fatalf("A TLS cert and key for the default server is not found") } } if *wildcardTLSSecret != "" { secret, err := getAndValidateSecret(kubeClient, *wildcardTLSSecret) if err != nil { glog.Fatalf("Error trying to get the wildcard TLS secret %v: %v", *wildcardTLSSecret, err) } bytes := configs.GenerateCertAndKeyFileContent(secret) nginxManager.CreateSecret(configs.WildcardSecretName, bytes, nginx.TLSSecretFileMode) } globalConfigurationValidator := createGlobalConfigurationValidator() globalCfgParams := configs.NewDefaultGlobalConfigParams() if *enableTLSPassthrough { globalCfgParams = configs.NewGlobalConfigParamsWithTLSPassthrough() } if *globalConfiguration != "" { ns, name, err := k8s.ParseNamespaceName(*globalConfiguration) if err != nil { glog.Fatalf("Error parsing the global-configuration argument: %v", err) } if !*enableCustomResources { glog.Fatal("global-configuration flag requires -enable-custom-resources") } gc, err := confClient.K8sV1alpha1().GlobalConfigurations(ns).Get(context.TODO(), name, meta_v1.GetOptions{}) if err != nil { glog.Fatalf("Error when getting %s: %v", *globalConfiguration, err) } err = globalConfigurationValidator.ValidateGlobalConfiguration(gc) if err != nil { glog.Fatalf("GlobalConfiguration %s is invalid: %v", *globalConfiguration, err) } globalCfgParams = configs.ParseGlobalConfiguration(gc, *enableTLSPassthrough) } cfgParams := configs.NewDefaultConfigParams() if *nginxConfigMaps != "" { ns, name, err := k8s.ParseNamespaceName(*nginxConfigMaps) if err != nil { glog.Fatalf("Error parsing the nginx-configmaps argument: %v", err) } cfm, err := kubeClient.CoreV1().ConfigMaps(ns).Get(context.TODO(), name, meta_v1.GetOptions{}) if err != nil { glog.Fatalf("Error when getting %v: %v", *nginxConfigMaps, err) } cfgParams = configs.ParseConfigMap(cfm, *nginxPlus, *appProtect) if cfgParams.MainServerSSLDHParamFileContent != nil { fileName, err := nginxManager.CreateDHParam(*cfgParams.MainServerSSLDHParamFileContent) if err != nil { glog.Fatalf("Configmap %s/%s: Could not update dhparams: %v", ns, name, err) } else { cfgParams.MainServerSSLDHParam = fileName } } if cfgParams.MainTemplate != nil { err = templateExecutor.UpdateMainTemplate(cfgParams.MainTemplate) if err != nil { glog.Fatalf("Error updating NGINX main template: %v", err) } } if cfgParams.IngressTemplate != nil { err = templateExecutor.UpdateIngressTemplate(cfgParams.IngressTemplate) if err != nil { glog.Fatalf("Error updating ingress template: %v", err) } } } staticCfgParams := &configs.StaticConfigParams{ HealthStatus: *healthStatus, HealthStatusURI: *healthStatusURI, NginxStatus: *nginxStatus, NginxStatusAllowCIDRs: allowedCIDRs, NginxStatusPort: *nginxStatusPort, StubStatusOverUnixSocketForOSS: *enablePrometheusMetrics, TLSPassthrough: *enableTLSPassthrough, EnableSnippets: *enableSnippets, NginxServiceMesh: *spireAgentAddress != "", MainAppProtectLoadModule: *appProtect, EnableLatencyMetrics: *enableLatencyMetrics, EnablePreviewPolicies: *enablePreviewPolicies, } ngxConfig := configs.GenerateNginxMainConfig(staticCfgParams, cfgParams) content, err := templateExecutor.ExecuteMainConfigTemplate(ngxConfig) if err != nil { glog.Fatalf("Error generating NGINX main config: %v", err) } nginxManager.CreateMainConfig(content) nginxManager.UpdateConfigVersionFile(ngxConfig.OpenTracingLoadModule) nginxManager.SetOpenTracing(ngxConfig.OpenTracingLoadModule) if ngxConfig.OpenTracingLoadModule { err := nginxManager.CreateOpenTracingTracerConfig(cfgParams.MainOpenTracingTracerConfig) if err != nil { glog.Fatalf("Error creating OpenTracing tracer config file: %v", err) } } if *enableTLSPassthrough { var emptyFile []byte nginxManager.CreateTLSPassthroughHostsConfig(emptyFile) } nginxDone := make(chan error, 1) nginxManager.Start(nginxDone) var plusClient *client.NginxClient if *nginxPlus && !useFakeNginxManager { httpClient := getSocketClient("/var/lib/nginx/nginx-plus-api.sock") plusClient, err = client.NewNginxClient(httpClient, "http://nginx-plus-api/api") if err != nil { glog.Fatalf("Failed to create NginxClient for Plus: %v", err) } nginxManager.SetPlusClients(plusClient, httpClient) } var plusCollector *nginxCollector.NginxPlusCollector var syslogListener metrics.SyslogListener syslogListener = metrics.NewSyslogFakeServer() if *enablePrometheusMetrics { upstreamServerVariableLabels := []string{"service", "resource_type", "resource_name", "resource_namespace"} upstreamServerPeerVariableLabelNames := []string{"pod_name"} if staticCfgParams.NginxServiceMesh { upstreamServerPeerVariableLabelNames = append(upstreamServerPeerVariableLabelNames, "pod_owner") } if *nginxPlus { streamUpstreamServerVariableLabels := []string{"service", "resource_type", "resource_name", "resource_namespace"} streamUpstreamServerPeerVariableLabelNames := []string{"pod_name"} serverZoneVariableLabels := []string{"resource_type", "resource_name", "resource_namespace"} streamServerZoneVariableLabels := []string{"resource_type", "resource_name", "resource_namespace"} variableLabelNames := nginxCollector.NewVariableLabelNames(upstreamServerVariableLabels, serverZoneVariableLabels, upstreamServerPeerVariableLabelNames, streamUpstreamServerVariableLabels, streamServerZoneVariableLabels, streamUpstreamServerPeerVariableLabelNames) plusCollector = nginxCollector.NewNginxPlusCollector(plusClient, "nginx_ingress_nginxplus", variableLabelNames, constLabels) go metrics.RunPrometheusListenerForNginxPlus(*prometheusMetricsListenPort, plusCollector, registry) } else { httpClient := getSocketClient("/var/lib/nginx/nginx-status.sock") client, err := metrics.NewNginxMetricsClient(httpClient) if err != nil { glog.Fatalf("Error creating the Nginx client for Prometheus metrics: %v", err) } go metrics.RunPrometheusListenerForNginx(*prometheusMetricsListenPort, client, registry, constLabels) } if *enableLatencyMetrics { latencyCollector = collectors.NewLatencyMetricsCollector(constLabels, upstreamServerVariableLabels, upstreamServerPeerVariableLabelNames) if err := latencyCollector.Register(registry); err != nil { glog.Errorf("Error registering Latency Prometheus metrics: %v", err) } syslogListener = metrics.NewLatencyMetricsListener("/var/lib/nginx/nginx-syslog.sock", latencyCollector) go syslogListener.Run() } } isWildcardEnabled := *wildcardTLSSecret != "" cnf := configs.NewConfigurator(nginxManager, staticCfgParams, cfgParams, globalCfgParams, templateExecutor, templateExecutorV2, *nginxPlus, isWildcardEnabled, plusCollector, *enablePrometheusMetrics, latencyCollector, *enableLatencyMetrics) controllerNamespace := os.Getenv("POD_NAMESPACE") transportServerValidator := cr_validation.NewTransportServerValidator(*enableTLSPassthrough) virtualServerValidator := cr_validation.NewVirtualServerValidator(*nginxPlus) lbcInput := k8s.NewLoadBalancerControllerInput{ KubeClient: kubeClient, ConfClient: confClient, DynClient: dynClient, ResyncPeriod: 30 * time.Second, Namespace: *watchNamespace, NginxConfigurator: cnf, DefaultServerSecret: *defaultServerSecret, AppProtectEnabled: *appProtect, IsNginxPlus: *nginxPlus, IngressClass: *ingressClass, UseIngressClassOnly: *useIngressClassOnly, ExternalServiceName: *externalService, IngressLink: *ingressLink, ControllerNamespace: controllerNamespace, ReportIngressStatus: *reportIngressStatus, IsLeaderElectionEnabled: *leaderElectionEnabled, LeaderElectionLockName: *leaderElectionLockName, WildcardTLSSecret: *wildcardTLSSecret, ConfigMaps: *nginxConfigMaps, GlobalConfiguration: *globalConfiguration, AreCustomResourcesEnabled: *enableCustomResources, EnablePreviewPolicies: *enablePreviewPolicies, MetricsCollector: controllerCollector, GlobalConfigurationValidator: globalConfigurationValidator, TransportServerValidator: transportServerValidator, VirtualServerValidator: virtualServerValidator, SpireAgentAddress: *spireAgentAddress, InternalRoutesEnabled: *enableInternalRoutes, IsPrometheusEnabled: *enablePrometheusMetrics, IsLatencyMetricsEnabled: *enableLatencyMetrics, } lbc := k8s.NewLoadBalancerController(lbcInput) if *readyStatus { go func() { port := fmt.Sprintf(":%v", *readyStatusPort) s := http.NewServeMux() s.HandleFunc("/nginx-ready", ready(lbc)) glog.Fatal(http.ListenAndServe(port, s)) }() } if *appProtect { go handleTerminationWithAppProtect(lbc, nginxManager, syslogListener, nginxDone, aPAgentDone, aPPluginDone) } else { go handleTermination(lbc, nginxManager, syslogListener, nginxDone) } lbc.Run() for { glog.Info("Waiting for the controller to exit...") time.Sleep(30 * time.Second) } } func createGlobalConfigurationValidator() *cr_validation.GlobalConfigurationValidator { forbiddenListenerPorts := map[int]bool{ 80: true, 443: true, } if *nginxStatus { forbiddenListenerPorts[*nginxStatusPort] = true } if *enablePrometheusMetrics { forbiddenListenerPorts[*prometheusMetricsListenPort] = true } return cr_validation.NewGlobalConfigurationValidator(forbiddenListenerPorts) } func handleTermination(lbc *k8s.LoadBalancerController, nginxManager nginx.Manager, listener metrics.SyslogListener, nginxDone chan error) { signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGTERM) exitStatus := 0 exited := false select { case err := <-nginxDone: if err != nil { glog.Errorf("nginx command exited with an error: %v", err) exitStatus = 1 } else { glog.Info("nginx command exited successfully") } exited = true case <-signalChan: glog.Info("Received SIGTERM, shutting down") } glog.Info("Shutting down the controller") lbc.Stop() if !exited { glog.Info("Shutting down NGINX") nginxManager.Quit() <-nginxDone } listener.Stop() glog.Infof("Exiting with a status: %v", exitStatus) os.Exit(exitStatus) } // getSocketClient gets an http.Client with the a unix socket transport. func getSocketClient(sockPath string) *http.Client { return &http.Client{ Transport: &http.Transport{ DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { return net.Dial("unix", sockPath) }, }, } } // validateResourceName validates the name of a resource func validateResourceName(lock string) error { allErrs := validation.IsDNS1123Subdomain(lock) if len(allErrs) > 0 { return fmt.Errorf("invalid resource name %v: %v", lock, allErrs) } return nil } // validatePort makes sure a given port is inside the valid port range for its usage func validatePort(port int) error { if port < 1024 || port > 65535 { return fmt.Errorf("port outside of valid port range [1024 - 65535]: %v", port) } return nil } // parseNginxStatusAllowCIDRs converts a comma separated CIDR/IP address string into an array of CIDR/IP addresses. // It returns an array of the valid CIDR/IP addresses or an error if given an invalid address. func parseNginxStatusAllowCIDRs(input string) (cidrs []string, err error) { cidrsArray := strings.Split(input, ",") for _, cidr := range cidrsArray { trimmedCidr := strings.TrimSpace(cidr) err := validateCIDRorIP(trimmedCidr) if err != nil { return cidrs, err } cidrs = append(cidrs, trimmedCidr) } return cidrs, nil } // validateCIDRorIP makes sure a given string is either a valid CIDR block or IP address. // It an error if it is not valid. func validateCIDRorIP(cidr string) error { if cidr == "" { return fmt.Errorf("invalid CIDR address: an empty string is an invalid CIDR block or IP address") } _, _, err := net.ParseCIDR(cidr) if err == nil { return nil } ip := net.ParseIP(cidr) if ip == nil { return fmt.Errorf("invalid IP address: %v", cidr) } return nil } // getAndValidateSecret gets and validates a secret. func getAndValidateSecret(kubeClient *kubernetes.Clientset, secretNsName string) (secret *api_v1.Secret, err error) { ns, name, err := k8s.ParseNamespaceName(secretNsName) if err != nil { return nil, fmt.Errorf("could not parse the %v argument: %v", secretNsName, err) } secret, err = kubeClient.CoreV1().Secrets(ns).Get(context.TODO(), name, meta_v1.GetOptions{}) if err != nil { return nil, fmt.Errorf("could not get %v: %v", secretNsName, err) } err = secrets.ValidateTLSSecret(secret) if err != nil { return nil, fmt.Errorf("%v is invalid: %v", secretNsName, err) } return secret, nil } const ( locationFmt = `/[^\s{};]*` locationErrMsg = "must start with / and must not include any whitespace character, `{`, `}` or `;`" ) var locationRegexp = regexp.MustCompile("^" + locationFmt + "$") func validateLocation(location string) error { if location == "" || location == "/" { return fmt.Errorf("invalid location format: '%v' is an invalid location", location) } if !locationRegexp.MatchString(location) { msg := validation.RegexError(locationErrMsg, locationFmt, "/path", "/path/subpath-123") return fmt.Errorf("invalid location format: %v", msg) } return nil } func handleTerminationWithAppProtect(lbc *k8s.LoadBalancerController, nginxManager nginx.Manager, listener metrics.SyslogListener, nginxDone, agentDone, pluginDone chan error) { signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGTERM) select { case err := <-nginxDone: glog.Fatalf("nginx command exited unexpectedly with status: %v", err) case err := <-pluginDone: glog.Fatalf("AppProtectPlugin command exited unexpectedly with status: %v", err) case err := <-agentDone: glog.Fatalf("AppProtectAgent command exited unexpectedly with status: %v", err) case <-signalChan: glog.Infof("Received SIGTERM, shutting down") lbc.Stop() nginxManager.Quit() <-nginxDone nginxManager.AppProtectPluginQuit() <-pluginDone nginxManager.AppProtectAgentQuit() <-agentDone listener.Stop() } glog.Info("Exiting successfully") os.Exit(0) } func parseReloadTimeout(appProtectEnabled bool, timeout int) time.Duration { const defaultTimeout = 4000 * time.Millisecond const defaultTimeoutAppProtect = 20000 * time.Millisecond if timeout != 0 { return time.Duration(timeout) * time.Millisecond } if appProtectEnabled { return defaultTimeoutAppProtect } return defaultTimeout } func ready(lbc *k8s.LoadBalancerController) http.HandlerFunc { return func(w http.ResponseWriter, _ *http.Request) { if !lbc.IsNginxReady() { http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) return } w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "Ready") } } func minVersion(min string) (v *util_version.Version) { minVer, err := util_version.ParseGeneric(min) if err != nil { glog.Fatalf("unexpected error parsing minimum supported version: %v", err) } return minVer }
[ "\"POD_NAMESPACE\"" ]
[]
[ "POD_NAMESPACE" ]
[]
["POD_NAMESPACE"]
go
1
0
fire/helptext_test.py
# Copyright (C) 2018 Google Inc. # # 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. """Tests for the helptext module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import textwrap from fire import formatting from fire import helptext from fire import test_components as tc from fire import testutils from fire import trace import six class HelpTest(testutils.BaseTestCase): def setUp(self): super(HelpTest, self).setUp() os.environ['ANSI_COLORS_DISABLED'] = '1' def testHelpTextNoDefaults(self): component = tc.NoDefaults help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='NoDefaults')) self.assertIn('NAME\n NoDefaults', help_screen) self.assertIn('SYNOPSIS\n NoDefaults', help_screen) self.assertNotIn('DESCRIPTION', help_screen) self.assertNotIn('NOTES', help_screen) def testHelpTextNoDefaultsObject(self): component = tc.NoDefaults() help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='NoDefaults')) self.assertIn('NAME\n NoDefaults', help_screen) self.assertIn('SYNOPSIS\n NoDefaults COMMAND', help_screen) self.assertNotIn('DESCRIPTION', help_screen) self.assertIn('COMMANDS\n COMMAND is one of the following:', help_screen) self.assertIn('double', help_screen) self.assertIn('triple', help_screen) self.assertNotIn('NOTES', help_screen) def testHelpTextFunction(self): component = tc.NoDefaults().double help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='double')) self.assertIn('NAME\n double', help_screen) self.assertIn('SYNOPSIS\n double COUNT', help_screen) self.assertNotIn('DESCRIPTION', help_screen) self.assertIn('POSITIONAL ARGUMENTS\n COUNT', help_screen) self.assertIn( 'NOTES\n You can also use flags syntax for POSITIONAL ARGUMENTS', help_screen) def testHelpTextFunctionWithDefaults(self): component = tc.WithDefaults().triple help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='triple')) self.assertIn('NAME\n triple', help_screen) self.assertIn('SYNOPSIS\n triple <flags>', help_screen) self.assertNotIn('DESCRIPTION', help_screen) self.assertIn('FLAGS\n --count=COUNT\n Default: 0', help_screen) self.assertNotIn('NOTES', help_screen) def testHelpTextFunctionWithLongDefaults(self): component = tc.WithDefaults().text help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='text')) self.assertIn('NAME\n text', help_screen) self.assertIn('SYNOPSIS\n text <flags>', help_screen) self.assertNotIn('DESCRIPTION', help_screen) self.assertIn( 'FLAGS\n --string=STRING\n' ' Default: \'0001020304050607080910' '1112131415161718192021222324252627282...', help_screen) self.assertNotIn('NOTES', help_screen) def testHelpTextFunctionWithKwargs(self): component = tc.fn_with_kwarg help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='text')) self.assertIn('NAME\n text', help_screen) self.assertIn('SYNOPSIS\n text ARG1 ARG2 <flags>', help_screen) self.assertIn('DESCRIPTION\n Function with kwarg', help_screen) self.assertIn( 'FLAGS\n --arg3\n Description of arg3.\n ' 'Additional undocumented flags may also be accepted.', help_screen) def testHelpTextFunctionWithKwargsAndDefaults(self): component = tc.fn_with_kwarg_and_defaults help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='text')) self.assertIn('NAME\n text', help_screen) self.assertIn('SYNOPSIS\n text ARG1 ARG2 <flags>', help_screen) self.assertIn('DESCRIPTION\n Function with kwarg', help_screen) self.assertIn( 'FLAGS\n --opt=OPT\n Default: True\n' ' The following flags are also accepted.' '\n --arg3\n Description of arg3.\n ' 'Additional undocumented flags may also be accepted.', help_screen) @testutils.skipIf( sys.version_info[0:2] < (3, 5), 'Python < 3.5 does not support type hints.') def testHelpTextFunctionWithDefaultsAndTypes(self): component = ( tc.py3.WithDefaultsAndTypes().double) # pytype: disable=module-attr help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='double')) self.assertIn('NAME\n double', help_screen) self.assertIn('SYNOPSIS\n double <flags>', help_screen) self.assertIn('DESCRIPTION', help_screen) self.assertIn( 'FLAGS\n --count=COUNT\n Type: float\n Default: 0', help_screen) self.assertNotIn('NOTES', help_screen) @testutils.skipIf( sys.version_info[0:2] < (3, 5), 'Python < 3.5 does not support type hints.') def testHelpTextFunctionWithTypesAndDefaultNone(self): component = ( tc.py3.WithDefaultsAndTypes().get_int) # pytype: disable=module-attr help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='get_int')) self.assertIn('NAME\n get_int', help_screen) self.assertIn('SYNOPSIS\n get_int <flags>', help_screen) self.assertNotIn('DESCRIPTION', help_screen) self.assertIn( 'FLAGS\n --value=VALUE\n' ' Type: Optional[int]\n Default: None', help_screen) self.assertNotIn('NOTES', help_screen) @testutils.skipIf( sys.version_info[0:2] < (3, 5), 'Python < 3.5 does not support type hints.') def testHelpTextFunctionWithTypes(self): component = tc.py3.WithTypes().double # pytype: disable=module-attr help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='double')) self.assertIn('NAME\n double', help_screen) self.assertIn('SYNOPSIS\n double COUNT', help_screen) self.assertIn('DESCRIPTION', help_screen) self.assertIn( 'POSITIONAL ARGUMENTS\n COUNT\n Type: float', help_screen) self.assertIn( 'NOTES\n You can also use flags syntax for POSITIONAL ARGUMENTS', help_screen) @testutils.skipIf( sys.version_info[0:2] < (3, 5), 'Python < 3.5 does not support type hints.') def testHelpTextFunctionWithLongTypes(self): component = tc.py3.WithTypes().long_type # pytype: disable=module-attr help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, name='long_type')) self.assertIn('NAME\n long_type', help_screen) self.assertIn('SYNOPSIS\n long_type LONG_OBJ', help_screen) self.assertNotIn('DESCRIPTION', help_screen) # TODO(dbieber): Assert type is displayed correctly. Type displayed # differently in Travis vs in Google. # self.assertIn( # 'POSITIONAL ARGUMENTS\n LONG_OBJ\n' # ' Type: typing.Tuple[typing.Tuple[' # 'typing.Tuple[typing.Tuple[typing.Tupl...', # help_screen) self.assertIn( 'NOTES\n You can also use flags syntax for POSITIONAL ARGUMENTS', help_screen) def testHelpTextFunctionWithBuiltin(self): component = 'test'.upper help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'upper')) self.assertIn('NAME\n upper', help_screen) self.assertIn('SYNOPSIS\n upper', help_screen) # We don't check description content here since the content is python # version dependent. self.assertIn('DESCRIPTION\n', help_screen) self.assertNotIn('NOTES', help_screen) def testHelpTextFunctionIntType(self): component = int help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'int')) self.assertIn('NAME\n int', help_screen) self.assertIn('SYNOPSIS\n int', help_screen) # We don't check description content here since the content is python # version dependent. self.assertIn('DESCRIPTION\n', help_screen) def testHelpTextEmptyList(self): component = [] help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'list')) self.assertIn('NAME\n list', help_screen) self.assertIn('SYNOPSIS\n list COMMAND', help_screen) # TODO(zuhaochen): Change assertion after custom description is # implemented for list type. self.assertNotIn('DESCRIPTION', help_screen) # We don't check the listed commands either since the list API could # potentially change between Python versions. self.assertIn('COMMANDS\n COMMAND is one of the following:\n', help_screen) def testHelpTextShortList(self): component = [10] help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'list')) self.assertIn('NAME\n list', help_screen) self.assertIn('SYNOPSIS\n list COMMAND', help_screen) # TODO(zuhaochen): Change assertion after custom description is # implemented for list type. self.assertNotIn('DESCRIPTION', help_screen) # We don't check the listed commands comprehensively since the list API # could potentially change between Python versions. Check a few # functions(command) that we're confident likely remain available. self.assertIn('COMMANDS\n COMMAND is one of the following:\n', help_screen) self.assertIn(' append\n', help_screen) def testHelpTextInt(self): component = 7 help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, '7')) self.assertIn('NAME\n 7', help_screen) self.assertIn('SYNOPSIS\n 7 COMMAND | VALUE', help_screen) # TODO(zuhaochen): Change assertion after implementing custom # description for int. self.assertNotIn('DESCRIPTION', help_screen) self.assertIn('COMMANDS\n COMMAND is one of the following:\n', help_screen) self.assertIn('VALUES\n VALUE is one of the following:\n', help_screen) def testHelpTextNoInit(self): component = tc.OldStyleEmpty help_screen = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'OldStyleEmpty')) self.assertIn('NAME\n OldStyleEmpty', help_screen) self.assertIn('SYNOPSIS\n OldStyleEmpty', help_screen) @testutils.skipIf( six.PY2, 'Python 2 does not support keyword-only arguments.') def testHelpTextKeywordOnlyArgumentsWithDefault(self): component = tc.py3.KeywordOnly.with_default # pytype: disable=module-attr output = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'with_default')) self.assertIn('NAME\n with_default', output) self.assertIn('FLAGS\n --x=X', output) @testutils.skipIf( six.PY2, 'Python 2 does not support keyword-only arguments.') def testHelpTextKeywordOnlyArgumentsWithoutDefault(self): component = tc.py3.KeywordOnly.double # pytype: disable=module-attr output = helptext.HelpText( component=component, trace=trace.FireTrace(component, 'double')) self.assertIn('NAME\n double', output) self.assertIn('FLAGS\n --count=COUNT (required)', output) def testHelpScreen(self): component = tc.ClassWithDocstring() t = trace.FireTrace(component, name='ClassWithDocstring') help_output = helptext.HelpText(component, t) expected_output = """ NAME ClassWithDocstring - Test class for testing help text output. SYNOPSIS ClassWithDocstring COMMAND | VALUE DESCRIPTION This is some detail description of this test class. COMMANDS COMMAND is one of the following: print_msg Prints a message. VALUES VALUE is one of the following: message The default message to print.""" self.assertEqual(textwrap.dedent(expected_output).strip(), help_output.strip()) def testHelpScreenForFunctionDocstringWithLineBreak(self): component = tc.ClassWithMultilineDocstring.example_generator t = trace.FireTrace(component, name='example_generator') help_output = helptext.HelpText(component, t) expected_output = """ NAME example_generator - Generators have a ``Yields`` section instead of a ``Returns`` section. SYNOPSIS example_generator N DESCRIPTION Generators have a ``Yields`` section instead of a ``Returns`` section. POSITIONAL ARGUMENTS N The upper limit of the range to generate, from 0 to `n` - 1. NOTES You can also use flags syntax for POSITIONAL ARGUMENTS""" self.assertEqual(textwrap.dedent(expected_output).strip(), help_output.strip()) def testHelpScreenForFunctionFunctionWithDefaultArgs(self): component = tc.WithDefaults().double t = trace.FireTrace(component, name='double') help_output = helptext.HelpText(component, t) expected_output = """ NAME double - Returns the input multiplied by 2. SYNOPSIS double <flags> DESCRIPTION Returns the input multiplied by 2. FLAGS --count=COUNT Default: 0 Input number that you want to double.""" self.assertEqual(textwrap.dedent(expected_output).strip(), help_output.strip()) def testHelpTextUnderlineFlag(self): component = tc.WithDefaults().triple t = trace.FireTrace(component, name='triple') help_screen = helptext.HelpText(component, t) self.assertIn(formatting.Bold('NAME') + '\n triple', help_screen) self.assertIn( formatting.Bold('SYNOPSIS') + '\n triple <flags>', help_screen) self.assertIn( formatting.Bold('FLAGS') + '\n --' + formatting.Underline('count'), help_screen) def testHelpTextBoldCommandName(self): component = tc.ClassWithDocstring() t = trace.FireTrace(component, name='ClassWithDocstring') help_screen = helptext.HelpText(component, t) self.assertIn( formatting.Bold('NAME') + '\n ClassWithDocstring', help_screen) self.assertIn(formatting.Bold('COMMANDS') + '\n', help_screen) self.assertIn( formatting.BoldUnderline('COMMAND') + ' is one of the following:\n', help_screen) self.assertIn(formatting.Bold('print_msg') + '\n', help_screen) def testHelpTextObjectWithGroupAndValues(self): component = tc.TypedProperties() t = trace.FireTrace(component, name='TypedProperties') help_screen = helptext.HelpText( component=component, trace=t, verbose=True) print(help_screen) self.assertIn('GROUPS', help_screen) self.assertIn('GROUP is one of the following:', help_screen) self.assertIn( 'charlie\n Class with functions that have default arguments.', help_screen) self.assertIn('VALUES', help_screen) self.assertIn('VALUE is one of the following:', help_screen) self.assertIn('alpha', help_screen) def testHelpTextNameSectionCommandWithSeparator(self): component = 9 t = trace.FireTrace(component, name='int', separator='-') t.AddSeparator() help_screen = helptext.HelpText(component=component, trace=t, verbose=False) self.assertIn('int -', help_screen) self.assertNotIn('int - -', help_screen) def testHelpTextNameSectionCommandWithSeparatorVerbose(self): component = tc.WithDefaults().double t = trace.FireTrace(component, name='double', separator='-') t.AddSeparator() help_screen = helptext.HelpText(component=component, trace=t, verbose=True) self.assertIn('double -', help_screen) self.assertIn('double - -', help_screen) class UsageTest(testutils.BaseTestCase): def testUsageOutput(self): component = tc.NoDefaults() t = trace.FireTrace(component, name='NoDefaults') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: NoDefaults <command> available commands: double | triple For detailed information on this command, run: NoDefaults --help""" self.assertEqual( usage_output, textwrap.dedent(expected_output).lstrip('\n')) def testUsageOutputVerbose(self): component = tc.NoDefaults() t = trace.FireTrace(component, name='NoDefaults') usage_output = helptext.UsageText(component, trace=t, verbose=True) expected_output = """ Usage: NoDefaults <command> available commands: double | triple For detailed information on this command, run: NoDefaults --help""" self.assertEqual( usage_output, textwrap.dedent(expected_output).lstrip('\n')) def testUsageOutputMethod(self): component = tc.NoDefaults().double t = trace.FireTrace(component, name='NoDefaults') t.AddAccessedProperty(component, 'double', ['double'], None, None) usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: NoDefaults double COUNT For detailed information on this command, run: NoDefaults double --help""" self.assertEqual( usage_output, textwrap.dedent(expected_output).lstrip('\n')) def testUsageOutputFunctionWithHelp(self): component = tc.function_with_help t = trace.FireTrace(component, name='function_with_help') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: function_with_help <flags> optional flags: --help For detailed information on this command, run: function_with_help -- --help""" self.assertEqual( usage_output, textwrap.dedent(expected_output).lstrip('\n')) def testUsageOutputFunctionWithDocstring(self): component = tc.multiplier_with_docstring t = trace.FireTrace(component, name='multiplier_with_docstring') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: multiplier_with_docstring NUM <flags> optional flags: --rate For detailed information on this command, run: multiplier_with_docstring --help""" self.assertEqual( textwrap.dedent(expected_output).lstrip('\n'), usage_output) @testutils.skipIf( six.PY2, 'Python 2 does not support required name-only arguments.') def testUsageOutputFunctionMixedDefaults(self): component = tc.py3.HelpTextComponent().identity t = trace.FireTrace(component, name='FunctionMixedDefaults') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: FunctionMixedDefaults <flags> optional flags: --beta required flags: --alpha For detailed information on this command, run: FunctionMixedDefaults --help""" expected_output = textwrap.dedent(expected_output).lstrip('\n') self.assertEqual(expected_output, usage_output) def testUsageOutputCallable(self): # This is both a group and a command. component = tc.CallableWithKeywordArgument() t = trace.FireTrace(component, name='CallableWithKeywordArgument', separator='@') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: CallableWithKeywordArgument <command> | <flags> available commands: print_msg flags are accepted For detailed information on this command, run: CallableWithKeywordArgument -- --help""" self.assertEqual( textwrap.dedent(expected_output).lstrip('\n'), usage_output) def testUsageOutputConstructorWithParameter(self): component = tc.InstanceVars t = trace.FireTrace(component, name='InstanceVars') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = """ Usage: InstanceVars --arg1=ARG1 --arg2=ARG2 For detailed information on this command, run: InstanceVars --help""" self.assertEqual( textwrap.dedent(expected_output).lstrip('\n'), usage_output) def testUsageOutputConstructorWithParameterVerbose(self): component = tc.InstanceVars t = trace.FireTrace(component, name='InstanceVars') usage_output = helptext.UsageText(component, trace=t, verbose=True) expected_output = """ Usage: InstanceVars <command> | --arg1=ARG1 --arg2=ARG2 available commands: run For detailed information on this command, run: InstanceVars --help""" self.assertEqual( textwrap.dedent(expected_output).lstrip('\n'), usage_output) def testUsageOutputEmptyDict(self): component = {} t = trace.FireTrace(component, name='EmptyDict') usage_output = helptext.UsageText(component, trace=t, verbose=True) expected_output = """ Usage: EmptyDict For detailed information on this command, run: EmptyDict --help""" self.assertEqual( textwrap.dedent(expected_output).lstrip('\n'), usage_output) def testUsageOutputNone(self): component = None t = trace.FireTrace(component, name='None') usage_output = helptext.UsageText(component, trace=t, verbose=True) expected_output = """ Usage: None For detailed information on this command, run: None --help""" self.assertEqual( textwrap.dedent(expected_output).lstrip('\n'), usage_output) def testInitRequiresFlagSyntaxSubclassNamedTuple(self): component = tc.SubPoint t = trace.FireTrace(component, name='SubPoint') usage_output = helptext.UsageText(component, trace=t, verbose=False) expected_output = 'Usage: SubPoint --x=X --y=Y' self.assertIn(expected_output, usage_output) if __name__ == '__main__': testutils.main()
[]
[]
[ "ANSI_COLORS_DISABLED" ]
[]
["ANSI_COLORS_DISABLED"]
python
1
0
cmd/main.go
package main import ( "io/ioutil" "log" "os" "os/signal" "syscall" "time" "github.com/deividfortuna/sharesies" "github.com/go-playground/validator/v10" "github.com/robfig/cron/v3" "gopkg.in/yaml.v2" shresiesbot "github.com/deividfortuna/sharesies-bot" ) const defaultTimeZone = "Pacific/Auckland" func main() { tz := os.Getenv("TZ") if tz == "" { tz = defaultTimeZone } timezone, _ := time.LoadLocation(tz) scheduler := cron.New( cron.WithLocation(timezone), cron.WithLogger( cron.VerbosePrintfLogger(log.New(os.Stdout, "Scheduler: ", log.LstdFlags)))) exchange, err := sharesies.New(nil) if err != nil { log.Fatal(err) } filepath := os.Getenv("CONFIG_FILE") if filepath == "" { filepath = "config/auto_invest.yml" } config, err := loadConfig(filepath) if err != nil { log.Fatal(err) } bot := shresiesbot.New(scheduler, exchange, config) err = bot.Run() if err != nil { log.Fatal(err) } scheduler.Start() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) <-c log.Println("Gracefully shutting down...") log.Println("Running cleanup tasks...") scheduler.Stop() log.Println("Successful shutdown.") } func loadConfig(filePath string) (*shresiesbot.AutoInvest, error) { v := &shresiesbot.AutoInvest{} f, err := ioutil.ReadFile(filePath) if err != nil { return nil, err } err = yaml.Unmarshal(f, v) if err != nil { return nil, err } validate := validator.New() err = validate.Struct(v) if err != nil { return nil, err } return v, nil }
[ "\"TZ\"", "\"CONFIG_FILE\"" ]
[]
[ "TZ", "CONFIG_FILE" ]
[]
["TZ", "CONFIG_FILE"]
go
2
0
tests/common/test_run/conv_filter_ad_run.py
# Copyright 2019 Huawei Technologies Co., Ltd # # 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. import numpy as np from akg.utils import kernel_exec as utils from akg.ops.nn import conv_filter_ad from tests.common.tensorio import compare_tensor from tests.common.gen_random import random_gaussian import os from akg.utils.kernel_exec import gen_kernel_name from tests.common.base import get_rtol_atol def conv_backprop_filter_naive(x, w, y, pad_, stride_): N, C, H, W = x.shape _, _, OH, OW = y.shape CO, CI, KH, KW = w.shape pad_top, pad_bottom, pad_left, pad_right = pad_ stride_h, stride_w = stride_ x_pad = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=0) x_img2col = np.full((N, C, KH, KW, OH, OW), 0, np.float32) for nn in range(N): for nc in range(C): for nh in range(KH): for nw in range(KW): for nho in range(OH): for nwo in range(OW): x_img2col[nn, nc, nh, nw, nho, nwo] = x_pad[nn, nc, nho * stride_h + nh, nwo * stride_w + nw] dw = np.zeros_like(w) for nn in range(CO): for nc in range(CI): for nh in range(KH): for nw in range(KW): dw[nn, nc, nh, nw] += np.sum(y[:, nn, :, :] * x_img2col[:, nc, nh, nw, :, :], axis=(0, 1, 2)) N, C, H, W = dw.shape dw = dw.reshape(N, C // 16, 16, H, W).transpose(1, 3, 4, 0, 2).copy() dw = dw.reshape(C // 16 * H * W, N // 16, 16, 16) return dw def gen_data_dw(x_shape, w_shape, pad_, stride_, dilation_, expect_file, attrs=None): block_size = 16 print("Data gen ...") fp32_mad = False if (fp32_mad): mmad_dtype = np.float32 else: mmad_dtype = np.float16 x = random_gaussian(x_shape, miu=0.5, sigma=0.01).astype(mmad_dtype) w = random_gaussian(w_shape, miu=1, sigma=0.1).astype(mmad_dtype) pad_top, pad_bottom, pad_left, pad_right = pad_ stride_h, stride_w = stride_ dilation_h, dilation_w = dilation_ Ho = (x_shape[2] + pad_top + pad_bottom - ((w_shape[2] - 1) * dilation_h + 1)) // stride_h + 1 Wo = (x_shape[3] + pad_left + pad_right - ((w_shape[3] - 1) * dilation_w + 1)) // stride_w + 1 out_shape = (x_shape[0], w_shape[0], Ho, Wo) y = random_gaussian(out_shape, miu=1, sigma=0.1).astype(mmad_dtype) N, C, H, W = w_shape dw_shape = (C // block_size * H * W, N // block_size, block_size, block_size) flag_w = os.environ.get("WRITE_TO_DISK", "No") if (flag_w == "No") and (os.path.exists(expect_file) == True): # read expect from file dw = np.fromfile(expect_file, np.float32).reshape(dw_shape) else: # compute expect data: dw = conv_backprop_filter_naive(x.astype(np.float32), w.astype(np.float32), y.astype(np.float32), pad_, stride_) if flag_w == "Yes": # write expect to file with open(expect_file, "w+") as file: dw.tofile(file) file.close() # reshape C0 = block_size ON, OC, OH, OW = out_shape WN, WC, WH, WW = w_shape FN, FC, FH, FW = x_shape x = x.reshape(FN, FC // C0, C0, FH, FW).transpose(0, 1, 3, 4, 2).copy() y = y.reshape(ON, OC // C0, C0, OH, OW).transpose(0, 1, 3, 4, 2).copy() return y, x, dw def compare_4D(out_data, expect): data_len = expect.size actual = out_data N, C1, H, W = out_data.shape error = 0 count = 0 lastErr = -2 continueErr = 0 maxContinue = -1 maxEnd = 0 partial_debug = 0 for n in range(N): for c1 in range(C1): for h in range(H): for w in range(W): a = actual[n, c1, h, w] b = expect[n, c1, h, w] if (abs(a - b) > abs(b) * 5e-03): if (partial_debug and (a == 0.0)): continue error += 1 if lastErr + 1 == count: continueErr += 1 else: if continueErr > maxContinue: maxContinue = continueErr maxEnd = lastErr continueErr = 1 lastErr = count count += 1 if continueErr > maxContinue: maxContinue = continueErr maxEnd = lastErr print("error num: %d/%d (%.2f%%)" % (error, count, 100.0 * error / count)) print("longest error range: [%d, %d]" % (maxEnd - maxContinue + 1, maxEnd)) if maxContinue >= 16: assert_res = False else: assert_res = True return assert_res def conv_filter_ad_run(fmap_shape, filter_shape, pad_, stride_, dilation_, attrs=None): block_size = 16 conv_dtype = 'float16' in_n, in_c, in_h, in_w = fmap_shape cout, cin, w_h, w_w = filter_shape assert(in_c == cin) in_c = (in_c + block_size - 1) // block_size * block_size cout = (cout + block_size - 1) // block_size * block_size pad_top, pad_bottom, pad_left, pad_right = pad_ stride_h, stride_w = stride_ out_n = in_n out_c = cout out_h = (in_h + pad_top + pad_bottom - w_h) // stride_h + 1 out_w = (in_w + pad_left + pad_right - w_w) // stride_w + 1 x_shape = (in_n, in_c, in_h, in_w) w_shape = (cout, in_c, w_h, w_w) x_5D_shape = (in_n, in_c // block_size, in_h, in_w, block_size) y_5D_shape = (out_n, out_c // block_size, out_h, out_w, block_size) forward_input_output_shapes = [y_5D_shape, x_5D_shape] dw_input_shapes = [y_5D_shape, x_5D_shape] input_file = os.environ.get("RANDOM_DATA_DISK_PATH", "") expect_file = input_file + "/" + gen_kernel_name([dw_input_shapes], [conv_dtype], op_attrs=[fmap_shape, filter_shape, pad_, stride_, dilation_], kernel_name='conv_filter_ad', attrs=attrs) + ".bin" print("gen_data begin.") dy_data, dx_data, expect = gen_data_dw(x_shape, w_shape, pad_, stride_, dilation_, expect_file, attrs=attrs) print("gen_data finished.") out_data = np.full(expect.shape, 0, 'float32') np_input = (dy_data, dx_data) flag_w = os.environ.get("WRITE_TO_DISK", "No") if flag_w == "Yes": return np_input, out_data, expect, True mod = utils.op_build_test(conv_filter_ad.conv_filter_ad, [dw_input_shapes], [conv_dtype], op_attrs=[fmap_shape, filter_shape, pad_, stride_, dilation_], kernel_name='conv_filter_ad', attrs=attrs, dump_code = True) args = (dy_data, dx_data, out_data) out_data = utils.mod_launch(mod, args, expect=expect) rtol, atol = get_rtol_atol("conv_filter_ad", conv_dtype) assert_res = compare_tensor(out_data, expect, rtol=rtol, atol=atol, equal_nan=True) return np_input, out_data, expect, assert_res
[]
[]
[ "WRITE_TO_DISK", "RANDOM_DATA_DISK_PATH" ]
[]
["WRITE_TO_DISK", "RANDOM_DATA_DISK_PATH"]
python
2
0
fhir/resources/DSTU2/tests/test_person.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 1.0.2.7202 on 2019-05-14. # 2019, SMART Health IT. import io import json import os import unittest from . import person from .fhirdate import FHIRDate class PersonTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get("FHIR_UNITTEST_DATADIR") or "" with io.open(os.path.join(datadir, filename), "r", encoding="utf-8") as handle: js = json.load(handle) self.assertEqual("Person", js["resourceType"]) return person.Person(js) def testPerson1(self): inst = self.instantiate_from("person-example.json") self.assertIsNotNone(inst, "Must have instantiated a Person instance") self.implPerson1(inst) js = inst.as_json() self.assertEqual("Person", js["resourceType"]) inst2 = person.Person(js) self.implPerson1(inst2) def implPerson1(self, inst): self.assertTrue(inst.active) self.assertEqual(inst.address[0].city, "PleasantVille") self.assertEqual(inst.address[0].line[0], "534 Erewhon St") self.assertEqual(inst.address[0].postalCode, "3999") self.assertEqual(inst.address[0].state, "Vic") self.assertEqual(inst.address[0].use, "home") self.assertEqual(inst.birthDate.date, FHIRDate("1974-12-25").date) self.assertEqual(inst.birthDate.as_json(), "1974-12-25") self.assertEqual(inst.gender, "male") self.assertEqual(inst.id, "example") self.assertEqual( inst.identifier[0].period.start.date, FHIRDate("2001-05-06").date ) self.assertEqual(inst.identifier[0].period.start.as_json(), "2001-05-06") self.assertEqual(inst.identifier[0].system, "urn:oid:1.2.36.146.595.217.0.1") self.assertEqual(inst.identifier[0].type.coding[0].code, "MR") self.assertEqual( inst.identifier[0].type.coding[0].system, "http://hl7.org/fhir/v2/0203" ) self.assertEqual(inst.identifier[0].use, "usual") self.assertEqual(inst.identifier[0].value, "12345") self.assertEqual(inst.name[0].family[0], "Chalmers") self.assertEqual(inst.name[0].given[0], "Peter") self.assertEqual(inst.name[0].given[1], "James") self.assertEqual(inst.name[0].use, "official") self.assertEqual(inst.name[1].given[0], "Jim") self.assertEqual(inst.name[1].use, "usual") self.assertEqual(inst.telecom[0].use, "home") self.assertEqual(inst.telecom[1].system, "phone") self.assertEqual(inst.telecom[1].use, "work") self.assertEqual(inst.telecom[1].value, "(03) 5555 6473") self.assertEqual(inst.text.status, "generated") def testPerson2(self): inst = self.instantiate_from("person-example-f002-ariadne.json") self.assertIsNotNone(inst, "Must have instantiated a Person instance") self.implPerson2(inst) js = inst.as_json() self.assertEqual("Person", js["resourceType"]) inst2 = person.Person(js) self.implPerson2(inst2) def implPerson2(self, inst): self.assertTrue(inst.active) self.assertEqual(inst.birthDate.date, FHIRDate("1963").date) self.assertEqual(inst.birthDate.as_json(), "1963") self.assertEqual(inst.gender, "female") self.assertEqual(inst.id, "f002") self.assertEqual(inst.name[0].text, "Ariadne Bor-Jansma") self.assertEqual(inst.name[0].use, "usual") self.assertEqual(inst.photo.contentType, "image/jpeg") self.assertEqual(inst.telecom[0].system, "phone") self.assertEqual(inst.telecom[0].use, "home") self.assertEqual(inst.telecom[0].value, "+31201234567") self.assertEqual(inst.text.status, "generated")
[]
[]
[ "FHIR_UNITTEST_DATADIR" ]
[]
["FHIR_UNITTEST_DATADIR"]
python
1
0
flipgram/wsgi.py
""" WSGI config for flipgram project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "flipgram.settings") application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
src/test/java/org/verdictdb/coordinator/RedshiftUniformScramblingCoordinatorTest.java
package org.verdictdb.coordinator; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.verdictdb.commons.DatabaseConnectionHelpers; import org.verdictdb.connection.DbmsConnection; import org.verdictdb.connection.DbmsQueryResult; import org.verdictdb.connection.JdbcConnection; import org.verdictdb.exception.VerdictDBDbmsException; import org.verdictdb.exception.VerdictDBException; public class RedshiftUniformScramblingCoordinatorTest { static Connection redshiftConn; static DbmsConnection dbmsConn; private static Statement stmt; private static final String REDSHIFT_HOST; private static final String REDSHIFT_DATABASE = "dev"; private static final String REDSHIFT_SCHEMA = "uniform_scrambling_test_" + RandomStringUtils.randomAlphanumeric(8).toLowerCase(); private static final String REDSHIFT_USER; private static final String REDSHIFT_PASSWORD; static { REDSHIFT_HOST = System.getenv("VERDICTDB_TEST_REDSHIFT_ENDPOINT"); REDSHIFT_USER = System.getenv("VERDICTDB_TEST_REDSHIFT_USER"); REDSHIFT_PASSWORD = System.getenv("VERDICTDB_TEST_REDSHIFT_PASSWORD"); // System.out.println(REDSHIFT_HOST); // System.out.println(REDSHIFT_USER); // System.out.println(REDSHIFT_PASSWORD); } @BeforeClass public static void setupRedshiftDatabase() throws SQLException, VerdictDBDbmsException, IOException { String connectionString = String.format("jdbc:redshift://%s/%s", REDSHIFT_HOST, REDSHIFT_DATABASE); redshiftConn = DatabaseConnectionHelpers.setupRedshift( connectionString, REDSHIFT_USER, REDSHIFT_PASSWORD, REDSHIFT_SCHEMA); stmt = redshiftConn.createStatement(); } @Test public void sanityCheck() throws VerdictDBDbmsException { JdbcConnection conn = JdbcConnection.create(redshiftConn); // conn.setOutputDebugMessage(true); DbmsQueryResult result = conn.execute(String.format("select * from \"%s\".\"lineitem\"", REDSHIFT_SCHEMA)); int rowCount = 0; while (result.next()) { rowCount++; } assertEquals(1000, rowCount); } @Test public void testScramblingCoordinatorLineitem() throws VerdictDBException { testScramblingCoordinator("lineitem"); } @Test public void testScramblingCoordinatorOrders() throws VerdictDBException { testScramblingCoordinator("orders"); } public void testScramblingCoordinator(String tablename) throws VerdictDBException { JdbcConnection conn = JdbcConnection.create(redshiftConn); conn.setOutputDebugMessage(true); String scrambleSchema = REDSHIFT_SCHEMA; String scratchpadSchema = REDSHIFT_SCHEMA; long blockSize = 100; ScramblingCoordinator scrambler = new ScramblingCoordinator(conn, scrambleSchema, scratchpadSchema, blockSize); // perform scrambling String originalSchema = REDSHIFT_SCHEMA; String originalTable = tablename; String scrambledTable = tablename + "_scrambled"; conn.execute(String.format("drop table if exists %s.%s", REDSHIFT_SCHEMA, scrambledTable)); scrambler.scramble(originalSchema, originalTable, originalSchema, scrambledTable, "uniform"); // tests List<Pair<String, String>> originalColumns = conn.getColumns(REDSHIFT_SCHEMA, originalTable); List<Pair<String, String>> columns = conn.getColumns(REDSHIFT_SCHEMA, scrambledTable); // prints added for debugging for (int i = 0; i < originalColumns.size(); i++) { System.out.println(originalColumns.get(i).getLeft() + " : " + columns.get(i).getLeft()); } assertEquals(originalColumns.size() + 2, columns.size()); for (int i = 0; i < originalColumns.size(); i++) { assertEquals(originalColumns.get(i).getLeft(), columns.get(i).getLeft()); assertEquals(originalColumns.get(i).getRight(), columns.get(i).getRight()); } List<String> partitions = conn.getPartitionColumns(REDSHIFT_SCHEMA, scrambledTable); assertEquals(Arrays.asList("verdictdbblock"), partitions); DbmsQueryResult result1 = conn.execute(String.format("select count(*) from %s.%s", REDSHIFT_SCHEMA, originalTable)); DbmsQueryResult result2 = conn.execute(String.format("select count(*) from %s.%s", REDSHIFT_SCHEMA, scrambledTable)); result1.next(); result2.next(); assertEquals(result1.getInt(0), result2.getInt(0)); DbmsQueryResult result = conn.execute( String.format( "select min(verdictdbblock), max(verdictdbblock) from %s.%s", REDSHIFT_SCHEMA, scrambledTable)); result.next(); assertEquals(0, result.getInt(0)); assertEquals((int) Math.ceil(result2.getInt(0) / (float) blockSize) - 1, result.getInt(1)); } @AfterClass public static void tearDown() throws SQLException { stmt.execute(String.format("drop schema if exists \"%s\" CASCADE", REDSHIFT_SCHEMA)); } }
[ "\"VERDICTDB_TEST_REDSHIFT_ENDPOINT\"", "\"VERDICTDB_TEST_REDSHIFT_USER\"", "\"VERDICTDB_TEST_REDSHIFT_PASSWORD\"" ]
[]
[ "VERDICTDB_TEST_REDSHIFT_ENDPOINT", "VERDICTDB_TEST_REDSHIFT_PASSWORD", "VERDICTDB_TEST_REDSHIFT_USER" ]
[]
["VERDICTDB_TEST_REDSHIFT_ENDPOINT", "VERDICTDB_TEST_REDSHIFT_PASSWORD", "VERDICTDB_TEST_REDSHIFT_USER"]
java
3
0
internal/codegen/golang/mysql_type.go
package golang import ( "log" "github.com/kyleconroy/sqlc/internal/compiler" "github.com/kyleconroy/sqlc/internal/config" "github.com/kyleconroy/sqlc/internal/debug" "github.com/kyleconroy/sqlc/internal/sql/catalog" ) func mysqlType(r *compiler.Result, col *compiler.Column, settings config.CombinedSettings) string { columnType := col.DataType notNull := col.NotNull || col.IsArray switch columnType { case "varchar", "text", "char", "tinytext", "mediumtext", "longtext": if notNull { return "string" } return "sql.NullString" case "tinyint": if col.Length != nil && *col.Length == 1 { if notNull { return "bool" } return "sql.NullBool" } else { if notNull { return "int32" } return "sql.NullInt32" } case "int", "integer", "smallint", "mediumint", "year": if notNull { return "int32" } return "sql.NullInt32" case "bigint": if notNull { return "int64" } return "sql.NullInt64" case "blob", "binary", "varbinary", "tinyblob", "mediumblob", "longblob": return "[]byte" case "double", "double precision", "real": if notNull { return "float64" } return "sql.NullFloat64" case "decimal", "dec", "fixed": if notNull { return "string" } return "sql.NullString" case "enum": // TODO: Proper Enum support return "string" case "date", "timestamp", "datetime", "time": if notNull { return "time.Time" } return "sql.NullTime" case "boolean", "bool": if notNull { return "bool" } return "sql.NullBool" case "json": return "json.RawMessage" case "any": return "interface{}" default: for _, schema := range r.Catalog.Schemas { for _, typ := range schema.Types { switch t := typ.(type) { case *catalog.Enum: if t.Name == columnType { if schema.Name == r.Catalog.DefaultSchema { return StructName(t.Name, settings) } return StructName(schema.Name+"_"+t.Name, settings) } } } } if debug.Active { log.Printf("Unknown MySQL type: %s\n", columnType) } return "interface{}" } }
[]
[]
[]
[]
[]
go
null
null
null
schoolID01/wsgi.py
""" WSGI config for schoolID01 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'schoolID01.settings') application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
error_reporting/tests/system/gapic/v1beta1/test_system_report_errors_service_v1beta1.py
# Copyright 2018 Google LLC # # 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 # # https://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 os import time from google.cloud import errorreporting_v1beta1 from google.cloud.errorreporting_v1beta1.proto import common_pb2 from google.cloud.errorreporting_v1beta1.proto import report_errors_service_pb2 class TestSystemReportErrorsService(object): def test_report_error_event(self): project_id = os.environ['PROJECT_ID'] client = errorreporting_v1beta1.ReportErrorsServiceClient() project_name = client.project_path(project_id) message = '[MESSAGE]' service = '[SERVICE]' service_context = {'service': service} file_path = 'path/to/file.lang' line_number = 42 function_name = 'meaningOfLife' report_location = { 'file_path': file_path, 'line_number': line_number, 'function_name': function_name } context = {'report_location': report_location} event = { 'message': message, 'service_context': service_context, 'context': context } response = client.report_error_event(project_name, event)
[]
[]
[ "PROJECT_ID" ]
[]
["PROJECT_ID"]
python
1
0
internal/application/http/rest/api.go
package rest import ( "github.com/gobuz/publicspam/internal/domain/port/service" "github.com/gin-gonic/gin" "os" ) // API will be a factory for all implementation of the Dependencies type API struct { *gin.Engine Identifier string PhoneService service.Phone } // Init init the api that wrap gin gonic with project func Init(identifier string, phone service.Phone) (*API, error) { api := &API{ Identifier:identifier, Engine: gin.New(), PhoneService: phone, } if os.Getenv("GO_DEBUG") == "true"{ api.Use(gin.Logger()) } else { gin.SetMode(gin.ReleaseMode) } return api, nil }
[ "\"GO_DEBUG\"" ]
[]
[ "GO_DEBUG" ]
[]
["GO_DEBUG"]
go
1
0
chatApp/asgi.py
import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatApp.settings") channel_layer = get_channel_layer()
[]
[]
[]
[]
[]
python
0
0
upgrade.go
// Copyright (c) 2013-2014 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package main import ( "io" "os" "path/filepath" ) // dirEmpty returns whether or not the specified directory path is empty. func dirEmpty(dirPath string) (bool, error) { f, err := os.Open(dirPath) if err != nil { return false, err } defer f.Close() // Read the names of a max of one entry from the directory. When the // directory is empty, an io.EOF error will be returned, so allow it. names, err := f.Readdirnames(1) if err != nil && err != io.EOF { return false, err } return len(names) == 0, nil } // oldBtcdHomeDir returns the OS specific home directory macd used prior to // version 0.3.3. This has since been replaced with macutil.AppDataDir, but // this function is still provided for the automatic upgrade path. func oldBtcdHomeDir() string { // Search for Windows APPDATA first. This won't exist on POSIX OSes. appData := os.Getenv("APPDATA") if appData != "" { return filepath.Join(appData, "macd") } // Fall back to standard HOME directory that works for most POSIX OSes. home := os.Getenv("HOME") if home != "" { return filepath.Join(home, ".macd") } // In the worst case, use the current directory. return "." } // upgradeDBPathNet moves the database for a specific network from its // location prior to macd version 0.2.0 and uses heuristics to ascertain the old // database type to rename to the new format. func upgradeDBPathNet(oldDbPath, netName string) error { // Prior to version 0.2.0, the database was named the same thing for // both sqlite and leveldb. Use heuristics to figure out the type // of the database and move it to the new path and name introduced with // version 0.2.0 accordingly. fi, err := os.Stat(oldDbPath) if err == nil { oldDbType := "sqlite" if fi.IsDir() { oldDbType = "leveldb" } // The new database name is based on the database type and // resides in a directory named after the network type. newDbRoot := filepath.Join(filepath.Dir(cfg.DataDir), netName) newDbName := blockDbNamePrefix + "_" + oldDbType if oldDbType == "sqlite" { newDbName = newDbName + ".db" } newDbPath := filepath.Join(newDbRoot, newDbName) // Create the new path if needed. err = os.MkdirAll(newDbRoot, 0700) if err != nil { return err } // Move and rename the old database. err := os.Rename(oldDbPath, newDbPath) if err != nil { return err } } return nil } // upgradeDBPaths moves the databases from their locations prior to macd // version 0.2.0 to their new locations. func upgradeDBPaths() error { // Prior to version 0.2.0, the databases were in the "db" directory and // their names were suffixed by "testnet" and "regtest" for their // respective networks. Check for the old database and update it to the // new path introduced with version 0.2.0 accordingly. oldDbRoot := filepath.Join(oldBtcdHomeDir(), "db") upgradeDBPathNet(filepath.Join(oldDbRoot, "macd.db"), "mainnet") upgradeDBPathNet(filepath.Join(oldDbRoot, "macd_testnet.db"), "testnet") upgradeDBPathNet(filepath.Join(oldDbRoot, "macd_regtest.db"), "regtest") // Remove the old db directory. return os.RemoveAll(oldDbRoot) } // upgradeDataPaths moves the application data from its location prior to macd // version 0.3.3 to its new location. func upgradeDataPaths() error { // No need to migrate if the old and new home paths are the same. oldHomePath := oldBtcdHomeDir() newHomePath := defaultHomeDir if oldHomePath == newHomePath { return nil } // Only migrate if the old path exists and the new one doesn't. if fileExists(oldHomePath) && !fileExists(newHomePath) { // Create the new path. macdLog.Infof("Migrating application home path from '%s' to '%s'", oldHomePath, newHomePath) err := os.MkdirAll(newHomePath, 0700) if err != nil { return err } // Move old macd.conf into new location if needed. oldConfPath := filepath.Join(oldHomePath, defaultConfigFilename) newConfPath := filepath.Join(newHomePath, defaultConfigFilename) if fileExists(oldConfPath) && !fileExists(newConfPath) { err := os.Rename(oldConfPath, newConfPath) if err != nil { return err } } // Move old data directory into new location if needed. oldDataPath := filepath.Join(oldHomePath, defaultDataDirname) newDataPath := filepath.Join(newHomePath, defaultDataDirname) if fileExists(oldDataPath) && !fileExists(newDataPath) { err := os.Rename(oldDataPath, newDataPath) if err != nil { return err } } // Remove the old home if it is empty or show a warning if not. ohpEmpty, err := dirEmpty(oldHomePath) if err != nil { return err } if ohpEmpty { err := os.Remove(oldHomePath) if err != nil { return err } } else { macdLog.Warnf("Not removing '%s' since it contains files "+ "not created by this application. You may "+ "want to manually move them or delete them.", oldHomePath) } } return nil } // doUpgrades performs upgrades to macd as new versions require it. func doUpgrades() error { err := upgradeDBPaths() if err != nil { return err } return upgradeDataPaths() }
[ "\"APPDATA\"", "\"HOME\"" ]
[]
[ "APPDATA", "HOME" ]
[]
["APPDATA", "HOME"]
go
2
0
clientAPI.py
# Copyright 2015 IBM Corp. All Rights Reserved. # # 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 # # https://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 os import requests from flask import Flask, jsonify, request from itsdangerous import TimedJSONWebSignatureSerializer, BadSignature, SignatureExpired import couchdb import config from config import db_name import twitter_helper app = Flask(__name__) # cl_username = '91819ede-4166-4871-bdb4-c58ee8e44e2c-bluemix' # cl_password = "77f3fee25e14cd0c13c8ec0cf6d9b8aa364ef63c53dd5d3c257570916855a553" def get_db(table): couch = couchdb.Server(config.db_url) couch.resource.credentials = (config.db_username, config.db_password) print(config.db_username, config.db_password) db = couch[table] return db @app.route('/dbquery/<query>') def query_db(query): # Select db that has this query db = get_db(db_name) map_fun = '''function(doc) { if (doc.email == query) emit(doc.name, null); } ''' for id in db: doc = db[id] info = {key: doc[key] for key in doc} print(id, info) return str(db.name) @app.route('/') def Welcome(): return app.send_static_file('index.html') @app.route('/api/register') def Register(): message = { 'success': False, } db = get_db(db_name) username = request.args.get('username') password = request.args.get('password') email = request.args.get('email') print(db.get(username)) if db.get(username): message["message"]="username already exists" return jsonify(results=message) doc_id, doc_rev = db.save({'_id':username,'email':email,'password':password}) message["success"] = True return jsonify(results=message) @app.route('/api/login') def Login(): message = { 'success': False, 'message': 'Username and password combination do not match' } query_username = request.args.get('username') query_password = request.args.get('password') db = get_db(db_name) if db.get(query_username) and db[query_username]["password"] == query_password: message['success'] = True message['message'] = "" message['token'] = get_auth_token() db.save({'token': message['token']}) return jsonify(message) return jsonify(message) @app.route('/api/twitter/<username>') def getTwitter(username): """ Test function to see if scraping is working. Get twitter JSON from api :param username: :return: """ message = { 'success': False, 'message': 'Not an active username or twitter account' } db = get_db(db_name) if db.get(username): handle = db[username]['twitter'] data = twitter_helper.process_tweets(handle) message['success'] = True return data @app.route('/api/personality/<username>') def inject_personality(username): """ Injects Big Five personality traits into the database by scraping their twitter data and using IBM's Personality Insights to calculate the traits. :param username: :return: """ from personality_insights import send_pi_request, extract_personality message = { 'success': False, 'message': 'Error: Personality not injected into {}. User may not exist or extraction failed'.format(username) } db = get_db(db_name) doc = db.get(username) if doc: # Extract personality dictionary handle = db[username]['twitter'] pi_data = send_pi_request(handle) personality = extract_personality(pi_data) # Why isn't this working? Need to insert doc['personality'] = personality db.save(doc) message['success'] = True message['message'] = 'Personality: {}'.format(personality) return jsonify(message) return jsonify(message) @app.route('/api/token') def get_auth_token(): token = generate_auth_token() return jsonify({ 'token': token.decode('ascii') }) @app.route('/api/myprofile') def MyProfile(): profiledata = { 'success': False, 'message': 'unimplemented' } return jsonify(results=profiledata) @app.route('/api/editprofile') def EditProfile(): editmessage = { 'success': False, 'message': 'unimplemented' } return jsonify(results=editmessage) @app.route('/api/register') def Search(): searchresults = { 'success': False, 'message': 'unimplemented', 'list': [ {'name': 'John', 'age': 28}, {'name': 'Bill', 'val': 26} ] } return jsonify(results=searchresults) @app.route('/api/viewprofile/<id>') def ViewProfile(): profiledata = { 'success': False, 'message': 'unimplemented' } return jsonify(results=profiledata) @app.route('/api/getfriends') def GetFriends(): friendlist = { 'success': False, 'message': 'unimplemented' } return jsonify(results=friendlist) @app.route('/api/resquestfriend/<id>') def RequestFriend(): friendrequest = { 'success': False, 'message': 'unimplemented' } return jsonify(results=friendrequest) ############################## # static methods ############################## def generate_auth_token(self, expiration = 600): s = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in = expiration) return s.dumps({ 'id': self.id }) ############################## # main ############################## port = os.getenv('PORT', '5000') if __name__ == "__main__": app.run(host='0.0.0.0', port=int(port))
[]
[]
[ "PORT" ]
[]
["PORT"]
python
1
0
core/core.go
/* Package core implements the IpfsNode object and related methods. Packages underneath core/ provide a (relatively) stable, low-level API to carry out most IPFS-related tasks. For more details on the other interfaces and how core/... fits into the bigger IPFS picture, see: $ godoc github.com/ipfs/go-ipfs */ package core import ( "bytes" "context" "errors" "fmt" "io" "io/ioutil" "net" "os" "strings" "time" bserv "github.com/ipfs/go-ipfs/blockservice" exchange "github.com/ipfs/go-ipfs/exchange" bitswap "github.com/ipfs/go-ipfs/exchange/bitswap" bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network" rp "github.com/ipfs/go-ipfs/exchange/reprovide" filestore "github.com/ipfs/go-ipfs/filestore" mount "github.com/ipfs/go-ipfs/fuse/mount" merkledag "github.com/ipfs/go-ipfs/merkledag" mfs "github.com/ipfs/go-ipfs/mfs" namesys "github.com/ipfs/go-ipfs/namesys" ipnsrp "github.com/ipfs/go-ipfs/namesys/republisher" p2p "github.com/ipfs/go-ipfs/p2p" "github.com/ipfs/go-ipfs/path/resolver" pin "github.com/ipfs/go-ipfs/pin" repo "github.com/ipfs/go-ipfs/repo" config "github.com/ipfs/go-ipfs/repo/config" ft "github.com/ipfs/go-ipfs/unixfs" addrutil "gx/ipfs/QmNSWW3Sb4eju4o2djPQ1L1c2Zj9XN9sMYJL8r1cbxdc6b/go-addr-util" yamux "gx/ipfs/QmNWCEvi7bPRcvqAV8AKLGVNoQdArWi7NJayka2SM4XtRe/go-smux-yamux" discovery "gx/ipfs/QmNh1kGFFdsPu79KNSaL4NUKUPb4Eiz4KHdMtFY6664RDp/go-libp2p/p2p/discovery" p2pbhost "gx/ipfs/QmNh1kGFFdsPu79KNSaL4NUKUPb4Eiz4KHdMtFY6664RDp/go-libp2p/p2p/host/basic" rhost "gx/ipfs/QmNh1kGFFdsPu79KNSaL4NUKUPb4Eiz4KHdMtFY6664RDp/go-libp2p/p2p/host/routed" identify "gx/ipfs/QmNh1kGFFdsPu79KNSaL4NUKUPb4Eiz4KHdMtFY6664RDp/go-libp2p/p2p/protocol/identify" ping "gx/ipfs/QmNh1kGFFdsPu79KNSaL4NUKUPb4Eiz4KHdMtFY6664RDp/go-libp2p/p2p/protocol/ping" u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util" p2phost "gx/ipfs/QmNmJZL7FQySMtE2BQuLMuZg2EB2CLEunJJUSVSc9YnnbV/go-libp2p-host" logging "gx/ipfs/QmRb5jh8z2E8hMGN2tkvs1yHynUanqnZ3UeKwgN1i9P1F8/go-log" goprocess "gx/ipfs/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP/goprocess" floodsub "gx/ipfs/QmSFihvoND3eDaAYRCeLgLPt62yCPgMZs1NSZmKFEtJQQw/go-libp2p-floodsub" mamask "gx/ipfs/QmSMZwvs3n4GBikZ7hKzT17c3bk65FmyZo2JqtJ16swqCv/multiaddr-filter" swarm "gx/ipfs/QmSwZMWwFZSUpe5muU2xgTUwppH24KfMwdPXiwbEp2c6G5/go-libp2p-swarm" routing "gx/ipfs/QmTiWLZ6Fo5j4KcTVutZJ5KWRRJrbxzmxA4td8NfEdrPh7/go-libp2p-routing" circuit "gx/ipfs/QmVTnHzuyECV9JzbXXfZRj1pKtgknp1esamUb2EH33mJkA/go-libp2p-circuit" mssmux "gx/ipfs/QmVniQJkdzLZaZwzwMdd3dJTvWiJ1DQEkreVy6hs6h7Vk5/go-smux-multistream" ma "gx/ipfs/QmWWQ2Txc2c6tqjsBpzg5Ar652cHPGNsQQp2SejkNmkUMb/go-multiaddr" ds "gx/ipfs/QmXRKBQA4wXP7xWbFiZsR1GP4HV6wMDQ1aWFxZZ4uBcPX9/go-datastore" pstore "gx/ipfs/QmXauCuJzmzapetmC6W4TuDJLL1yFFrVzSHoWv8YdbmnxH/go-libp2p-peerstore" nilrouting "gx/ipfs/QmXtoXbu9ReyV6Q4kDQ5CF9wXQNDY1PdHc4HhfxRR5AHB3/go-ipfs-routing/none" offroute "gx/ipfs/QmXtoXbu9ReyV6Q4kDQ5CF9wXQNDY1PdHc4HhfxRR5AHB3/go-ipfs-routing/offline" dht "gx/ipfs/QmY1y2M1aCcVhy8UuTbZJBvuFbegZm47f9cDAdgxiehQfx/go-libp2p-kad-dht" smux "gx/ipfs/QmY9JXR3FupnYAYJWK9aMr9bCpqWKcToQ1tz8DVGTrHpHw/go-stream-muxer" connmgr "gx/ipfs/QmZ1R2LxRZTUaeuMFEtQigzHfFCv3hLYBi5316aZ7YUeyf/go-libp2p-connmgr" ipnet "gx/ipfs/QmZPrWxuM8GHr4cGKbyF5CCT11sFUP9hgqpeUHALvx2nUr/go-libp2p-interface-pnet" peer "gx/ipfs/QmZoWKhxUmZ2seW4BzX6fJkNR8hh9PsGModr7q171yq2SS/go-libp2p-peer" bstore "gx/ipfs/QmaG4DZ4JaqEfvPWt5nPPgoTzhc1tr1T3f4Nu9Jpdm8ymY/go-ipfs-blockstore" ic "gx/ipfs/QmaPbCnUMBohSGo3KnxEa2bHqyJVVeEEcwtqJAYxerieBo/go-libp2p-crypto" ifconnmgr "gx/ipfs/Qmax8X1Kfahf5WfSB68EWDG3d3qyS3Sqs1v412fjPTfRwx/go-libp2p-interface-connmgr" mplex "gx/ipfs/Qmc14vuKyGqX27RvBhekYytxSFJpaEgQVuVJgKSm69MEix/go-smux-multiplex" cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid" metrics "gx/ipfs/QmdeBtQGXjSt7cb97nx9JyLHHv5va2LyEAue7Q5tDFzpLy/go-libp2p-metrics" ipld "gx/ipfs/Qme5bWv7wtjUNGsK2BNGVUFPKiuxWrsqrtvYwCLRw8YFES/go-ipld-format" pnet "gx/ipfs/QmenK8PgcpM2KYzEKnGx1LyN1QXawswM2F6HktCbWKuC1b/go-libp2p-pnet" mafilter "gx/ipfs/Qmf2UAmRwDG4TvnkQpHZWPAzw7rpCYVhxmRXmYxXr5LD1g/go-maddr-filter" ) const IpnsValidatorTag = "ipns" const kReprovideFrequency = time.Hour * 12 const discoveryConnTimeout = time.Second * 30 var log = logging.Logger("core") type mode int const ( // zero value is not a valid mode, must be explicitly set localMode mode = iota offlineMode onlineMode ) func init() { identify.ClientVersion = "go-ipfs/" + config.CurrentVersionNumber + "/" + config.CurrentCommit } // IpfsNode is IPFS Core module. It represents an IPFS instance. type IpfsNode struct { // Self Identity peer.ID // the local node's identity Repo repo.Repo // Local node Pinning pin.Pinner // the pinning manager Mounts Mounts // current mount state, if any. PrivateKey ic.PrivKey // the local node's private Key PNetFingerprint []byte // fingerprint of private network // Services Peerstore pstore.Peerstore // storage for other Peer instances Blockstore bstore.GCBlockstore // the block store (lower level) Filestore *filestore.Filestore // the filestore blockstore BaseBlocks bstore.Blockstore // the raw blockstore, no filestore wrapping GCLocker bstore.GCLocker // the locker used to protect the blockstore during gc Blocks bserv.BlockService // the block service, get/add blocks. DAG ipld.DAGService // the merkle dag service, get/add objects. Resolver *resolver.Resolver // the path resolution system Reporter metrics.Reporter Discovery discovery.Service FilesRoot *mfs.Root // Online PeerHost p2phost.Host // the network host (server+client) Bootstrapper io.Closer // the periodic bootstrapper Routing routing.IpfsRouting // the routing system. recommend ipfs-dht Exchange exchange.Interface // the block exchange + strategy (bitswap) Namesys namesys.NameSystem // the name system, resolves paths to hashes Ping *ping.PingService Reprovider *rp.Reprovider // the value reprovider system IpnsRepub *ipnsrp.Republisher Floodsub *floodsub.PubSub P2P *p2p.P2P proc goprocess.Process ctx context.Context mode mode localModeSet bool } // Mounts defines what the node's mount state is. This should // perhaps be moved to the daemon or mount. It's here because // it needs to be accessible across daemon requests. type Mounts struct { Ipfs mount.Mount Ipns mount.Mount } func (n *IpfsNode) startOnlineServices(ctx context.Context, routingOption RoutingOption, hostOption HostOption, do DiscoveryOption, pubsub, ipnsps, mplex bool) error { if n.PeerHost != nil { // already online. return errors.New("node already online") } // load private key if err := n.LoadPrivateKey(); err != nil { return err } // get undialable addrs from config cfg, err := n.Repo.Config() if err != nil { return err } var addrfilter []*net.IPNet for _, s := range cfg.Swarm.AddrFilters { f, err := mamask.NewMask(s) if err != nil { return fmt.Errorf("incorrectly formatted address filter in config: %s", s) } addrfilter = append(addrfilter, f) } if !cfg.Swarm.DisableBandwidthMetrics { // Set reporter n.Reporter = metrics.NewBandwidthCounter() } tpt := makeSmuxTransport(mplex) swarmkey, err := n.Repo.SwarmKey() if err != nil { return err } var protec ipnet.Protector if swarmkey != nil { protec, err = pnet.NewProtector(bytes.NewReader(swarmkey)) if err != nil { return err } n.PNetFingerprint = protec.Fingerprint() go func() { t := time.NewTicker(30 * time.Second) <-t.C // swallow one tick for { select { case <-t.C: if ph := n.PeerHost; ph != nil { if len(ph.Network().Peers()) == 0 { log.Warning("We are in private network and have no peers.") log.Warning("This might be configuration mistake.") } } case <-n.Process().Closing(): t.Stop() return } } }() } addrsFactory, err := makeAddrsFactory(cfg.Addresses) if err != nil { return err } connmgr, err := constructConnMgr(cfg.Swarm.ConnMgr) if err != nil { return err } hostopts := &ConstructPeerHostOpts{ AddrsFactory: addrsFactory, DisableNatPortMap: cfg.Swarm.DisableNatPortMap, DisableRelay: cfg.Swarm.DisableRelay, EnableRelayHop: cfg.Swarm.EnableRelayHop, ConnectionManager: connmgr, } peerhost, err := hostOption(ctx, n.Identity, n.Peerstore, n.Reporter, addrfilter, tpt, protec, hostopts) if err != nil { return err } if err := n.startOnlineServicesWithHost(ctx, peerhost, routingOption); err != nil { return err } // Ok, now we're ready to listen. if err := startListening(ctx, n.PeerHost, cfg); err != nil { return err } if pubsub || ipnsps { service, err := floodsub.NewFloodSub(ctx, peerhost) if err != nil { return err } n.Floodsub = service } if ipnsps { err = namesys.AddPubsubNameSystem(ctx, n.Namesys, n.PeerHost, n.Routing, n.Repo.Datastore(), n.Floodsub) if err != nil { return err } } n.P2P = p2p.NewP2P(n.Identity, n.PeerHost, n.Peerstore) // setup local discovery if do != nil { service, err := do(ctx, n.PeerHost) if err != nil { log.Error("mdns error: ", err) } else { service.RegisterNotifee(n) n.Discovery = service } } return n.Bootstrap(DefaultBootstrapConfig) } func constructConnMgr(cfg config.ConnMgr) (ifconnmgr.ConnManager, error) { switch cfg.Type { case "": // 'default' value is the basic connection manager return connmgr.NewConnManager(config.DefaultConnMgrLowWater, config.DefaultConnMgrHighWater, config.DefaultConnMgrGracePeriod), nil case "none": return nil, nil case "basic": grace, err := time.ParseDuration(cfg.GracePeriod) if err != nil { return nil, fmt.Errorf("parsing Swarm.ConnMgr.GracePeriod: %s", err) } return connmgr.NewConnManager(cfg.LowWater, cfg.HighWater, grace), nil default: return nil, fmt.Errorf("unrecognized ConnMgr.Type: %q", cfg.Type) } } func (n *IpfsNode) startLateOnlineServices(ctx context.Context) error { cfg, err := n.Repo.Config() if err != nil { return err } var keyProvider rp.KeyChanFunc switch cfg.Reprovider.Strategy { case "all": fallthrough case "": keyProvider = rp.NewBlockstoreProvider(n.Blockstore) case "roots": keyProvider = rp.NewPinnedProvider(n.Pinning, n.DAG, true) case "pinned": keyProvider = rp.NewPinnedProvider(n.Pinning, n.DAG, false) default: return fmt.Errorf("unknown reprovider strategy '%s'", cfg.Reprovider.Strategy) } n.Reprovider = rp.NewReprovider(ctx, n.Routing, keyProvider) reproviderInterval := kReprovideFrequency if cfg.Reprovider.Interval != "" { dur, err := time.ParseDuration(cfg.Reprovider.Interval) if err != nil { return err } reproviderInterval = dur } go n.Reprovider.Run(reproviderInterval) return nil } func makeAddrsFactory(cfg config.Addresses) (p2pbhost.AddrsFactory, error) { var annAddrs []ma.Multiaddr for _, addr := range cfg.Announce { maddr, err := ma.NewMultiaddr(addr) if err != nil { return nil, err } annAddrs = append(annAddrs, maddr) } filters := mafilter.NewFilters() noAnnAddrs := map[string]bool{} for _, addr := range cfg.NoAnnounce { f, err := mamask.NewMask(addr) if err == nil { filters.AddDialFilter(f) continue } maddr, err := ma.NewMultiaddr(addr) if err != nil { return nil, err } noAnnAddrs[maddr.String()] = true } return func(allAddrs []ma.Multiaddr) []ma.Multiaddr { var addrs []ma.Multiaddr if len(annAddrs) > 0 { addrs = annAddrs } else { addrs = allAddrs } var out []ma.Multiaddr for _, maddr := range addrs { // check for exact matches ok, _ := noAnnAddrs[maddr.String()] // check for /ipcidr matches if !ok && !filters.AddrBlocked(maddr) { out = append(out, maddr) } } return out }, nil } func makeSmuxTransport(mplexExp bool) smux.Transport { mstpt := mssmux.NewBlankTransport() ymxtpt := &yamux.Transport{ AcceptBacklog: 512, ConnectionWriteTimeout: time.Second * 10, KeepAliveInterval: time.Second * 30, EnableKeepAlive: true, MaxStreamWindowSize: uint32(1024 * 512), LogOutput: ioutil.Discard, } if os.Getenv("YAMUX_DEBUG") != "" { ymxtpt.LogOutput = os.Stderr } mstpt.AddTransport("/yamux/1.0.0", ymxtpt) if mplexExp { mstpt.AddTransport("/mplex/6.7.0", mplex.DefaultTransport) } // Allow muxer preference order overriding if prefs := os.Getenv("LIBP2P_MUX_PREFS"); prefs != "" { mstpt.OrderPreference = strings.Fields(prefs) } return mstpt } func setupDiscoveryOption(d config.Discovery) DiscoveryOption { if d.MDNS.Enabled { return func(ctx context.Context, h p2phost.Host) (discovery.Service, error) { if d.MDNS.Interval == 0 { d.MDNS.Interval = 5 } return discovery.NewMdnsService(ctx, h, time.Duration(d.MDNS.Interval)*time.Second, discovery.ServiceTag) } } return nil } // HandlePeerFound attempts to connect to peer from `PeerInfo`, if it fails // logs a warning log. func (n *IpfsNode) HandlePeerFound(p pstore.PeerInfo) { log.Warning("trying peer info: ", p) ctx, cancel := context.WithTimeout(n.Context(), discoveryConnTimeout) defer cancel() if err := n.PeerHost.Connect(ctx, p); err != nil { log.Warning("Failed to connect to peer found by discovery: ", err) } } // startOnlineServicesWithHost is the set of services which need to be // initialized with the host and _before_ we start listening. func (n *IpfsNode) startOnlineServicesWithHost(ctx context.Context, host p2phost.Host, routingOption RoutingOption) error { // setup diagnostics service n.Ping = ping.NewPingService(host) // setup routing service r, err := routingOption(ctx, host, n.Repo.Datastore()) if err != nil { return err } n.Routing = r // Wrap standard peer host with routing system to allow unknown peer lookups n.PeerHost = rhost.Wrap(host, n.Routing) // setup exchange service const alwaysSendToPeer = true // use YesManStrategy bitswapNetwork := bsnet.NewFromIpfsHost(n.PeerHost, n.Routing) n.Exchange = bitswap.New(ctx, n.Identity, bitswapNetwork, n.Blockstore, alwaysSendToPeer) size, err := n.getCacheSize() if err != nil { return err } // setup name system n.Namesys = namesys.NewNameSystem(n.Routing, n.Repo.Datastore(), size) // setup ipns republishing return n.setupIpnsRepublisher() } // getCacheSize returns cache life and cache size func (n *IpfsNode) getCacheSize() (int, error) { cfg, err := n.Repo.Config() if err != nil { return 0, err } cs := cfg.Ipns.ResolveCacheSize if cs == 0 { cs = 128 } if cs < 0 { return 0, fmt.Errorf("cannot specify negative resolve cache size") } return cs, nil } func (n *IpfsNode) setupIpnsRepublisher() error { cfg, err := n.Repo.Config() if err != nil { return err } n.IpnsRepub = ipnsrp.NewRepublisher(n.Routing, n.Repo.Datastore(), n.PrivateKey, n.Repo.Keystore()) if cfg.Ipns.RepublishPeriod != "" { d, err := time.ParseDuration(cfg.Ipns.RepublishPeriod) if err != nil { return fmt.Errorf("failure to parse config setting IPNS.RepublishPeriod: %s", err) } if !u.Debug && (d < time.Minute || d > (time.Hour*24)) { return fmt.Errorf("config setting IPNS.RepublishPeriod is not between 1min and 1day: %s", d) } n.IpnsRepub.Interval = d } if cfg.Ipns.RecordLifetime != "" { d, err := time.ParseDuration(cfg.Ipns.RepublishPeriod) if err != nil { return fmt.Errorf("failure to parse config setting IPNS.RecordLifetime: %s", err) } n.IpnsRepub.RecordLifetime = d } n.Process().Go(n.IpnsRepub.Run) return nil } // Process returns the Process object func (n *IpfsNode) Process() goprocess.Process { return n.proc } // Close calls Close() on the Process object func (n *IpfsNode) Close() error { return n.proc.Close() } // Context returns the IpfsNode context func (n *IpfsNode) Context() context.Context { if n.ctx == nil { n.ctx = context.TODO() } return n.ctx } // teardown closes owned children. If any errors occur, this function returns // the first error. func (n *IpfsNode) teardown() error { log.Debug("core is shutting down...") // owned objects are closed in this teardown to ensure that they're closed // regardless of which constructor was used to add them to the node. var closers []io.Closer // NOTE: The order that objects are added(closed) matters, if an object // needs to use another during its shutdown/cleanup process, it should be // closed before that other object if n.FilesRoot != nil { closers = append(closers, n.FilesRoot) } if n.Exchange != nil { closers = append(closers, n.Exchange) } if n.Mounts.Ipfs != nil && !n.Mounts.Ipfs.IsActive() { closers = append(closers, mount.Closer(n.Mounts.Ipfs)) } if n.Mounts.Ipns != nil && !n.Mounts.Ipns.IsActive() { closers = append(closers, mount.Closer(n.Mounts.Ipns)) } if dht, ok := n.Routing.(*dht.IpfsDHT); ok { closers = append(closers, dht.Process()) } if n.Blocks != nil { closers = append(closers, n.Blocks) } if n.Bootstrapper != nil { closers = append(closers, n.Bootstrapper) } if n.PeerHost != nil { closers = append(closers, n.PeerHost) } // Repo closed last, most things need to preserve state here closers = append(closers, n.Repo) var errs []error for _, closer := range closers { if err := closer.Close(); err != nil { errs = append(errs, err) } } if len(errs) > 0 { return errs[0] } return nil } // OnlineMode returns whether or not the IpfsNode is in OnlineMode. func (n *IpfsNode) OnlineMode() bool { switch n.mode { case onlineMode: return true default: return false } } // SetLocal will set the IpfsNode to local mode func (n *IpfsNode) SetLocal(isLocal bool) { if isLocal { n.mode = localMode } n.localModeSet = true } // LocalMode returns whether or not the IpfsNode is in LocalMode func (n *IpfsNode) LocalMode() bool { if !n.localModeSet { // programmer error should not happen panic("local mode not set") } switch n.mode { case localMode: return true default: return false } } // Bootstrap will set and call the IpfsNodes bootstrap function. func (n *IpfsNode) Bootstrap(cfg BootstrapConfig) error { // TODO what should return value be when in offlineMode? if n.Routing == nil { return nil } if n.Bootstrapper != nil { n.Bootstrapper.Close() // stop previous bootstrap process. } // if the caller did not specify a bootstrap peer function, get the // freshest bootstrap peers from config. this responds to live changes. if cfg.BootstrapPeers == nil { cfg.BootstrapPeers = func() []pstore.PeerInfo { ps, err := n.loadBootstrapPeers() if err != nil { log.Warning("failed to parse bootstrap peers from config") return nil } return ps } } var err error n.Bootstrapper, err = Bootstrap(n, cfg) return err } func (n *IpfsNode) loadID() error { if n.Identity != "" { return errors.New("identity already loaded") } cfg, err := n.Repo.Config() if err != nil { return err } cid := cfg.Identity.PeerID if cid == "" { return errors.New("identity was not set in config (was 'ipfs init' run?)") } if len(cid) == 0 { return errors.New("no peer ID in config! (was 'ipfs init' run?)") } id, err := peer.IDB58Decode(cid) if err != nil { return fmt.Errorf("peer ID invalid: %s", err) } n.Identity = id return nil } // GetKey will return a key from the Keystore with name `name`. func (n *IpfsNode) GetKey(name string) (ic.PrivKey, error) { if name == "self" { return n.PrivateKey, nil } else { return n.Repo.Keystore().Get(name) } } func (n *IpfsNode) LoadPrivateKey() error { if n.Identity == "" || n.Peerstore == nil { return errors.New("loaded private key out of order.") } if n.PrivateKey != nil { return errors.New("private key already loaded") } cfg, err := n.Repo.Config() if err != nil { return err } sk, err := loadPrivateKey(&cfg.Identity, n.Identity) if err != nil { return err } n.PrivateKey = sk n.Peerstore.AddPrivKey(n.Identity, n.PrivateKey) n.Peerstore.AddPubKey(n.Identity, sk.GetPublic()) return nil } func (n *IpfsNode) loadBootstrapPeers() ([]pstore.PeerInfo, error) { cfg, err := n.Repo.Config() if err != nil { return nil, err } parsed, err := cfg.BootstrapPeers() if err != nil { return nil, err } return toPeerInfos(parsed), nil } func (n *IpfsNode) loadFilesRoot() error { dsk := ds.NewKey("/local/filesroot") pf := func(ctx context.Context, c *cid.Cid) error { return n.Repo.Datastore().Put(dsk, c.Bytes()) } var nd *merkledag.ProtoNode val, err := n.Repo.Datastore().Get(dsk) switch { case err == ds.ErrNotFound || val == nil: nd = ft.EmptyDirNode() err := n.DAG.Add(n.Context(), nd) if err != nil { return fmt.Errorf("failure writing to dagstore: %s", err) } case err == nil: c, err := cid.Cast(val.([]byte)) if err != nil { return err } rnd, err := n.DAG.Get(n.Context(), c) if err != nil { return fmt.Errorf("error loading filesroot from DAG: %s", err) } pbnd, ok := rnd.(*merkledag.ProtoNode) if !ok { return merkledag.ErrNotProtobuf } nd = pbnd default: return err } mr, err := mfs.NewRoot(n.Context(), n.DAG, nd, pf) if err != nil { return err } n.FilesRoot = mr return nil } // SetupOfflineRouting loads the local nodes private key and // uses it to instantiate a routing system in offline mode. // This is primarily used for offline ipns modifications. func (n *IpfsNode) SetupOfflineRouting() error { if n.Routing != nil { // Routing was already set up return nil } err := n.LoadPrivateKey() if err != nil { return err } n.Routing = offroute.NewOfflineRouter(n.Repo.Datastore(), n.PrivateKey) size, err := n.getCacheSize() if err != nil { return err } n.Namesys = namesys.NewNameSystem(n.Routing, n.Repo.Datastore(), size) return nil } func loadPrivateKey(cfg *config.Identity, id peer.ID) (ic.PrivKey, error) { sk, err := cfg.DecodePrivateKey("passphrase todo!") if err != nil { return nil, err } id2, err := peer.IDFromPrivateKey(sk) if err != nil { return nil, err } if id2 != id { return nil, fmt.Errorf("private key in config does not match id: %s != %s", id, id2) } return sk, nil } func listenAddresses(cfg *config.Config) ([]ma.Multiaddr, error) { var listen []ma.Multiaddr for _, addr := range cfg.Addresses.Swarm { maddr, err := ma.NewMultiaddr(addr) if err != nil { return nil, fmt.Errorf("Failure to parse config.Addresses.Swarm: %s", cfg.Addresses.Swarm) } listen = append(listen, maddr) } return listen, nil } type ConstructPeerHostOpts struct { AddrsFactory p2pbhost.AddrsFactory DisableNatPortMap bool DisableRelay bool EnableRelayHop bool ConnectionManager ifconnmgr.ConnManager } type HostOption func(ctx context.Context, id peer.ID, ps pstore.Peerstore, bwr metrics.Reporter, fs []*net.IPNet, tpt smux.Transport, protc ipnet.Protector, opts *ConstructPeerHostOpts) (p2phost.Host, error) var DefaultHostOption HostOption = constructPeerHost // isolates the complex initialization steps func constructPeerHost(ctx context.Context, id peer.ID, ps pstore.Peerstore, bwr metrics.Reporter, fs []*net.IPNet, tpt smux.Transport, protec ipnet.Protector, opts *ConstructPeerHostOpts) (p2phost.Host, error) { // no addresses to begin with. we'll start later. swrm, err := swarm.NewSwarmWithProtector(ctx, nil, id, ps, protec, tpt, bwr) if err != nil { return nil, err } network := (*swarm.Network)(swrm) for _, f := range fs { network.Swarm().Filters.AddDialFilter(f) } hostOpts := []interface{}{bwr} if !opts.DisableNatPortMap { hostOpts = append(hostOpts, p2pbhost.NATPortMap) } if opts.ConnectionManager != nil { hostOpts = append(hostOpts, opts.ConnectionManager) } addrsFactory := opts.AddrsFactory if !opts.DisableRelay { if addrsFactory != nil { addrsFactory = composeAddrsFactory(addrsFactory, filterRelayAddrs) } else { addrsFactory = filterRelayAddrs } } if addrsFactory != nil { hostOpts = append(hostOpts, addrsFactory) } host := p2pbhost.New(network, hostOpts...) if !opts.DisableRelay { var relayOpts []circuit.RelayOpt if opts.EnableRelayHop { relayOpts = append(relayOpts, circuit.OptHop) } err := circuit.AddRelayTransport(ctx, host, relayOpts...) if err != nil { host.Close() return nil, err } } return host, nil } func filterRelayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr { var raddrs []ma.Multiaddr for _, addr := range addrs { _, err := addr.ValueForProtocol(circuit.P_CIRCUIT) if err == nil { continue } raddrs = append(raddrs, addr) } return raddrs } func composeAddrsFactory(f, g p2pbhost.AddrsFactory) p2pbhost.AddrsFactory { return func(addrs []ma.Multiaddr) []ma.Multiaddr { return f(g(addrs)) } } // startListening on the network addresses func startListening(ctx context.Context, host p2phost.Host, cfg *config.Config) error { listenAddrs, err := listenAddresses(cfg) if err != nil { return err } // make sure we error out if our config does not have addresses we can use log.Debugf("Config.Addresses.Swarm:%s", listenAddrs) filteredAddrs := addrutil.FilterUsableAddrs(listenAddrs) log.Debugf("Config.Addresses.Swarm:%s (filtered)", filteredAddrs) if len(filteredAddrs) < 1 { return fmt.Errorf("addresses in config not usable: %s", listenAddrs) } // Actually start listening: if err := host.Network().Listen(filteredAddrs...); err != nil { return err } // list out our addresses addrs, err := host.Network().InterfaceListenAddresses() if err != nil { return err } log.Infof("Swarm listening at: %s", addrs) return nil } func constructDHTRouting(ctx context.Context, host p2phost.Host, dstore ds.Batching) (routing.IpfsRouting, error) { dhtRouting := dht.NewDHT(ctx, host, dstore) dhtRouting.Validator[IpnsValidatorTag] = namesys.NewIpnsRecordValidator(host.Peerstore()) dhtRouting.Selector[IpnsValidatorTag] = namesys.IpnsSelectorFunc return dhtRouting, nil } func constructClientDHTRouting(ctx context.Context, host p2phost.Host, dstore ds.Batching) (routing.IpfsRouting, error) { dhtRouting := dht.NewDHTClient(ctx, host, dstore) dhtRouting.Validator[IpnsValidatorTag] = namesys.NewIpnsRecordValidator(host.Peerstore()) dhtRouting.Selector[IpnsValidatorTag] = namesys.IpnsSelectorFunc return dhtRouting, nil } type RoutingOption func(context.Context, p2phost.Host, ds.Batching) (routing.IpfsRouting, error) type DiscoveryOption func(context.Context, p2phost.Host) (discovery.Service, error) var DHTOption RoutingOption = constructDHTRouting var DHTClientOption RoutingOption = constructClientDHTRouting var NilRouterOption RoutingOption = nilrouting.ConstructNilRouting
[ "\"YAMUX_DEBUG\"", "\"LIBP2P_MUX_PREFS\"" ]
[]
[ "YAMUX_DEBUG", "LIBP2P_MUX_PREFS" ]
[]
["YAMUX_DEBUG", "LIBP2P_MUX_PREFS"]
go
2
0
org.openbel.framework.common/src/main/java/org/openbel/framework/common/cfg/Configuration.java
/** * Copyright (C) 2012-2013 Selventa, Inc. * * This file is part of the OpenBEL Framework. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The OpenBEL Framework is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the OpenBEL Framework. If not, see <http://www.gnu.org/licenses/>. * * Additional Terms under LGPL v3: * * This license does not authorize you and you are prohibited from using the * name, trademarks, service marks, logos or similar indicia of Selventa, Inc., * or, in the discretion of other licensors or authors of the program, the * name, trademarks, service marks, logos or similar indicia of such authors or * licensors, in any marketing or advertising materials relating to your * distribution of the program or any covered product. This restriction does * not waive or limit your obligation to keep intact all copyright notices set * forth in the program as delivered to you. * * If you distribute the program in whole or in part, or any modified version * of the program, and you assume contractual liability to the recipient with * respect to the program or modified version, then you will indemnify the * authors and licensors of the program for any liabilities that these * contractual assumptions directly impose on those licensors and authors. */ package org.openbel.framework.common.cfg; import static java.lang.System.getProperty; import static java.lang.System.getenv; import static org.openbel.framework.common.BELUtilities.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.openbel.framework.common.BELUtilities; import org.openbel.framework.common.MapFunction; import org.openbel.framework.common.PathConstants; /** * This class encapsulates a map-based <i>configuration</i>. * <p> * This class contains a set of variables that will be automatically expanded if * found as a value within a configuration file. * </p> * <p> * <dl> * <dt><tt>{tmp}</tt></dt> * <dd>Expanded to the system temporary directory. * <dt><tt>{home}</tt></dt> * <dd>Expanded to the user's home directory. * <dt><tt>{name}</tt></dt> * <dd>Expanded to the user's name.</dd> * <dt><tt>{dir}</tt></dt> * <dd>Expanded to the current working directory.</dd> * <dt><tt>{belframework_home}</tt></dt> * <dd>Expanded to the {@code BELFRAMEWORK_HOME} environment variable</tt></dt> * </dl> * </p> */ public abstract class Configuration { /** * The comment prefix, {@value #COMMENT}. Lines beginning with this string * will be ignored. */ public static final String COMMENT = "#"; /** * The delimiter, {@value #NAME_VALUE_DELIMITER}. Name-value pairs are * separated in configuration files by this string. */ public static final String NAME_VALUE_DELIMITER = "="; /** * The name-value configuration map, in expanded form. */ private Map<String, String> cfgMap; /** * Boolean {@code true} if defaults are used, {@code false} otherwise. The * defaults provide a way for subclasses to use a predefined set of defaults * in the event no configuration can be provided. */ protected final boolean defaults; /** * Creates a configuration instance derived from the supplied file. If the * file is not {@link BELUtilities#readable(File) readable}, * {@link #initializeDefaults()} will be called on {@link #init()}. * * @param file File to use as configuration; may be null in which case * {@link #defaults} are used * @throws IOException Thrown if an I/O error occurs */ protected Configuration(final File file) throws IOException { if (readable(file)) { cfgMap = new HashMap<String, String>(); read(file); defaults = false; return; } cfgMap = null; defaults = true; } /** * Creates a configuration instance derived from the supplied map. If the * map is null, {@link #initializeDefaults()} will be called on * {@link #init()}. * * @param map Map to use as configuration; may be null in which case * {@link #defaults} are used */ protected Configuration(final Map<String, String> map) { if (noNulls(map)) { cfgMap = new HashMap<String, String>(); read(map); defaults = false; return; } cfgMap = null; defaults = true; } /** * Creates a configuration instance using {@link #defaults}. This will * result in {@link #initializeDefaults()} being called on {@link #init()}. */ protected Configuration() { cfgMap = null; defaults = true; } /** * Initializes the configuration instance. The * {@link Configuration#processSetting(String, String) processSetting} * method will be invoked for each setting, or {@link #initializeDefaults() * initializeDefaults} if defaults are being used. */ protected void init() { if (defaults) { initializeDefaults(); return; } mapfx(cfgMap, new MapFunction<String, String>() { @Override public void apply(String name, String value) { processSetting(name, value); } }); readComplete(); } /** * Process a name-value setting during reading {@link #configurationFile} by * * @param name Non-null name * @param value Non-null value */ protected abstract void processSetting(String name, String value); /** * Called at the end of {@link #read()}. */ protected abstract void readComplete(); /** * Initializes the configuration to default settings. */ protected abstract void initializeDefaults(); /** * Returns the name-value default settings. * * @return Name-value mappings */ protected abstract Map<String, String> defaults(); /** * Returns the default configuration provided by {@link #defaults()}. * * @return Non-null string */ protected String defaultConfiguration() { final StringBuilder bldr = new StringBuilder(); for (final Entry<String, String> entry : defaults().entrySet()) { final String name = entry.getKey(); final String value = entry.getValue(); bldr.append(name); bldr.append(" "); bldr.append(NAME_VALUE_DELIMITER); bldr.append(" "); bldr.append(value); bldr.append("\n"); } return bldr.toString(); } /* * Reads a file populating a map for a call to read(Map) below. * * @throws IOException Thrown if an I/O error occurs */ private void read(final File f) throws IOException { final FileReader fr = new FileReader(f); final BufferedReader br = new BufferedReader(fr); String input = null; while ((input = br.readLine()) != null) { // Trim whitespace. input = input.trim(); // Skip comments if (input.startsWith(COMMENT)) continue; final int idx = input.indexOf(NAME_VALUE_DELIMITER); if (idx == -1) continue; String name, value; try { name = input.substring(0, idx); value = input.substring(idx + 1); } catch (IndexOutOfBoundsException e) { continue; } name = name.trim(); value = value.trim(); cfgMap.put(name, valueSubstitution(value)); } br.close(); } /* * Reads the configuration map of name/value strings, invoking the process * setting callback. */ private void read(final Map<String, String> map) { String name, value; for (final Entry<String, String> entry : entries(map)) { name = entry.getKey(); value = entry.getValue(); cfgMap.put(name, valueSubstitution(value)); } } /** * Performs substitution against the configuration {@code value} for the * system's temporary directory, user's home directory, user's name, or * user's current working directory. * * @param value Non-null string * @return String resulting from value replacement */ public static String valueSubstitution(final String value) { final String tmpProp = "java.io.tmpdir"; final String tmpVar = "{tmp}"; final String tmpRE = "{tmp}"; final String homeProp = "user.home"; final String homeVar = "{home}"; final String homeRE = "{home}"; final String nameProp = "user.name"; final String nameVar = "{name}"; final String nameRE = "{name}"; final String cwdProp = "user.dir"; final String cwdVar = "{dir}"; final String cwdRE = "{dir}"; final String bfHomeEnv = PathConstants.BELFRAMEWORK_HOME_ENV_VAR; final String bfHomeVar = "{belframework_home}"; final String bfHomeRE = "{belframework_home}"; String ret = value; if (value.contains(tmpVar)) { ret = ret.replace(tmpRE, getProperty(tmpProp)); } if (value.contains(homeVar)) { ret = ret.replace(homeRE, getProperty(homeProp)); } if (value.contains(nameVar)) { ret = ret.replace(nameRE, getProperty(nameProp)); } if (value.contains(cwdVar)) { ret = ret.replace(cwdRE, getProperty(cwdProp)); } if (value.contains(bfHomeVar)) { String bfHome = getenv(bfHomeEnv); if (bfHome == null) { bfHome = ""; //belframework home is not set. Use empty string. } ret = ret.replace(bfHomeRE, bfHome); } return ret; } }
[]
[]
[]
[]
[]
java
0
0
mne/coreg.py
# -*- coding: utf-8 -*- """Coregistration between different coordinate frames.""" # Authors: Christian Brodbeck <[email protected]> # # License: BSD-3-Clause import configparser import fnmatch from glob import glob, iglob import os import os.path as op import stat import sys import re import shutil from functools import reduce import numpy as np from .io import read_fiducials, write_fiducials, read_info from .io.constants import FIFF from .io.meas_info import Info from .io._digitization import _get_data_as_dict_from_dig # keep get_mni_fiducials for backward compat (no burden to keep in this # namespace, too) from ._freesurfer import (_read_mri_info, get_mni_fiducials, # noqa: F401 estimate_head_mri_t) # noqa: F401 from .label import read_label, Label from .source_space import (add_source_space_distances, read_source_spaces, # noqa: E501,F401 write_source_spaces) from .surface import (read_surface, write_surface, _normalize_vectors, complete_surface_info, decimate_surface, _DistanceQuery) from .bem import read_bem_surfaces, write_bem_surfaces from .transforms import (rotation, rotation3d, scaling, translation, Transform, _read_fs_xfm, _write_fs_xfm, invert_transform, combine_transforms, _quat_to_euler, _fit_matched_points, apply_trans, rot_to_quat, _angle_between_quats) from .channels import make_dig_montage from .utils import (get_config, get_subjects_dir, logger, pformat, verbose, warn, has_nibabel, fill_doc, _validate_type, _check_subject, _check_option) from .viz._3d import _fiducial_coords # some path templates trans_fname = os.path.join('{raw_dir}', '{subject}-trans.fif') subject_dirname = os.path.join('{subjects_dir}', '{subject}') bem_dirname = os.path.join(subject_dirname, 'bem') mri_dirname = os.path.join(subject_dirname, 'mri') mri_transforms_dirname = os.path.join(subject_dirname, 'mri', 'transforms') surf_dirname = os.path.join(subject_dirname, 'surf') bem_fname = os.path.join(bem_dirname, "{subject}-{name}.fif") head_bem_fname = pformat(bem_fname, name='head') fid_fname = pformat(bem_fname, name='fiducials') fid_fname_general = os.path.join(bem_dirname, "{head}-fiducials.fif") src_fname = os.path.join(bem_dirname, '{subject}-{spacing}-src.fif') _head_fnames = (os.path.join(bem_dirname, 'outer_skin.surf'), head_bem_fname) _high_res_head_fnames = (os.path.join(bem_dirname, '{subject}-head-dense.fif'), os.path.join(surf_dirname, 'lh.seghead'), os.path.join(surf_dirname, 'lh.smseghead')) def _map_fid_name_to_idx(name: str) -> int: """Map a fiducial name to its index in the DigMontage.""" name = name.lower() if name == 'lpa': return 0 elif name == 'nasion': return 1 else: assert name == 'rpa' return 2 def _make_writable(fname): """Make a file writable.""" os.chmod(fname, stat.S_IMODE(os.lstat(fname)[stat.ST_MODE]) | 128) # write def _make_writable_recursive(path): """Recursively set writable.""" if sys.platform.startswith('win'): return # can't safely set perms for root, dirs, files in os.walk(path, topdown=False): for f in dirs + files: _make_writable(os.path.join(root, f)) def _find_head_bem(subject, subjects_dir, high_res=False): """Find a high resolution head.""" # XXX this should be refactored with mne.surface.get_head_surf ... fnames = _high_res_head_fnames if high_res else _head_fnames for fname in fnames: path = fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): return path @fill_doc def coregister_fiducials(info, fiducials, tol=0.01): """Create a head-MRI transform by aligning 3 fiducial points. Parameters ---------- %(info_not_none)s fiducials : str | list of dict Fiducials in MRI coordinate space (either path to a ``*-fiducials.fif`` file or list of fiducials as returned by :func:`read_fiducials`. Returns ------- trans : Transform The device-MRI transform. .. note:: The :class:`mne.Info` object fiducials must be in the head coordinate space. """ if isinstance(info, str): info = read_info(info) if isinstance(fiducials, str): fiducials, coord_frame_to = read_fiducials(fiducials) else: coord_frame_to = FIFF.FIFFV_COORD_MRI frames_from = {d['coord_frame'] for d in info['dig']} if len(frames_from) > 1: raise ValueError("info contains fiducials from different coordinate " "frames") else: coord_frame_from = frames_from.pop() coords_from = _fiducial_coords(info['dig']) coords_to = _fiducial_coords(fiducials, coord_frame_to) trans = fit_matched_points(coords_from, coords_to, tol=tol) return Transform(coord_frame_from, coord_frame_to, trans) @verbose def create_default_subject(fs_home=None, update=False, subjects_dir=None, verbose=None): """Create an average brain subject for subjects without structural MRI. Create a copy of fsaverage from the Freesurfer directory in subjects_dir and add auxiliary files from the mne package. Parameters ---------- fs_home : None | str The freesurfer home directory (only needed if FREESURFER_HOME is not specified as environment variable). update : bool In cases where a copy of the fsaverage brain already exists in the subjects_dir, this option allows to only copy files that don't already exist in the fsaverage directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (os.environ['SUBJECTS_DIR']) as destination for the new subject. %(verbose)s Notes ----- When no structural MRI is available for a subject, an average brain can be substituted. Freesurfer comes with such an average brain model, and MNE comes with some auxiliary files which make coregistration easier. :py:func:`create_default_subject` copies the relevant files from Freesurfer into the current subjects_dir, and also adds the auxiliary files provided by MNE. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if fs_home is None: fs_home = get_config('FREESURFER_HOME', fs_home) if fs_home is None: raise ValueError( "FREESURFER_HOME environment variable not found. Please " "specify the fs_home parameter in your call to " "create_default_subject().") # make sure freesurfer files exist fs_src = os.path.join(fs_home, 'subjects', 'fsaverage') if not os.path.exists(fs_src): raise IOError('fsaverage not found at %r. Is fs_home specified ' 'correctly?' % fs_src) for name in ('label', 'mri', 'surf'): dirname = os.path.join(fs_src, name) if not os.path.isdir(dirname): raise IOError("Freesurfer fsaverage seems to be incomplete: No " "directory named %s found in %s" % (name, fs_src)) # make sure destination does not already exist dest = os.path.join(subjects_dir, 'fsaverage') if dest == fs_src: raise IOError( "Your subjects_dir points to the freesurfer subjects_dir (%r). " "The default subject can not be created in the freesurfer " "installation directory; please specify a different " "subjects_dir." % subjects_dir) elif (not update) and os.path.exists(dest): raise IOError( "Can not create fsaverage because %r already exists in " "subjects_dir %r. Delete or rename the existing fsaverage " "subject folder." % ('fsaverage', subjects_dir)) # copy fsaverage from freesurfer logger.info("Copying fsaverage subject from freesurfer directory...") if (not update) or not os.path.exists(dest): shutil.copytree(fs_src, dest) _make_writable_recursive(dest) # copy files from mne source_fname = os.path.join(os.path.dirname(__file__), 'data', 'fsaverage', 'fsaverage-%s.fif') dest_bem = os.path.join(dest, 'bem') if not os.path.exists(dest_bem): os.mkdir(dest_bem) logger.info("Copying auxiliary fsaverage files from mne...") dest_fname = os.path.join(dest_bem, 'fsaverage-%s.fif') _make_writable_recursive(dest_bem) for name in ('fiducials', 'head', 'inner_skull-bem', 'trans'): if not os.path.exists(dest_fname % name): shutil.copy(source_fname % name, dest_bem) def _decimate_points(pts, res=10): """Decimate the number of points using a voxel grid. Create a voxel grid with a specified resolution and retain at most one point per voxel. For each voxel, the point closest to its center is retained. Parameters ---------- pts : array, shape (n_points, 3) The points making up the head shape. res : scalar The resolution of the voxel space (side length of each voxel). Returns ------- pts : array, shape = (n_points, 3) The decimated points. """ from scipy.spatial.distance import cdist pts = np.asarray(pts) # find the bin edges for the voxel space xmin, ymin, zmin = pts.min(0) - res / 2. xmax, ymax, zmax = pts.max(0) + res xax = np.arange(xmin, xmax, res) yax = np.arange(ymin, ymax, res) zax = np.arange(zmin, zmax, res) # find voxels containing one or more point H, _ = np.histogramdd(pts, bins=(xax, yax, zax), normed=False) X, Y, Z = pts.T xbins, ybins, zbins = np.nonzero(H) x = xax[xbins] y = yax[ybins] z = zax[zbins] mids = np.c_[x, y, z] + res / 2. # each point belongs to at most one voxel center, so figure those out # (cKDTree faster than BallTree for these small problems) tree = _DistanceQuery(mids, method='cKDTree') _, mid_idx = tree.query(pts) # then figure out which to actually use based on proximity # (take advantage of sorting the mid_idx to get our mapping of # pts to nearest voxel midpoint) sort_idx = np.argsort(mid_idx) bounds = np.cumsum( np.concatenate([[0], np.bincount(mid_idx, minlength=len(mids))])) assert len(bounds) == len(mids) + 1 out = list() for mi, mid in enumerate(mids): # Now we do this: # # use_pts = pts[mid_idx == mi] # # But it's faster for many points than making a big boolean indexer # over and over (esp. since each point can only belong to a single # voxel). use_pts = pts[sort_idx[bounds[mi]:bounds[mi + 1]]] if not len(use_pts): out.append([np.inf] * 3) else: out.append( use_pts[np.argmin(cdist(use_pts, mid[np.newaxis])[:, 0])]) out = np.array(out, float).reshape(-1, 3) out = out[np.abs(out - mids).max(axis=1) < res / 2.] # """ return out def _trans_from_params(param_info, params): """Convert transformation parameters into a transformation matrix. Parameters ---------- param_info : tuple, len = 3 Tuple describing the parameters in x (do_translate, do_rotate, do_scale). params : tuple The transformation parameters. Returns ------- trans : array, shape = (4, 4) Transformation matrix. """ do_rotate, do_translate, do_scale = param_info i = 0 trans = [] if do_rotate: x, y, z = params[:3] trans.append(rotation(x, y, z)) i += 3 if do_translate: x, y, z = params[i:i + 3] trans.insert(0, translation(x, y, z)) i += 3 if do_scale == 1: s = params[i] trans.append(scaling(s, s, s)) elif do_scale == 3: x, y, z = params[i:i + 3] trans.append(scaling(x, y, z)) trans = reduce(np.dot, trans) return trans _ALLOW_ANALITICAL = True # XXX this function should be moved out of coreg as used elsewhere def fit_matched_points(src_pts, tgt_pts, rotate=True, translate=True, scale=False, tol=None, x0=None, out='trans', weights=None): """Find a transform between matched sets of points. This minimizes the squared distance between two matching sets of points. Uses :func:`scipy.optimize.leastsq` to find a transformation involving a combination of rotation, translation, and scaling (in that order). Parameters ---------- src_pts : array, shape = (n, 3) Points to which the transform should be applied. tgt_pts : array, shape = (n, 3) Points to which src_pts should be fitted. Each point in tgt_pts should correspond to the point in src_pts with the same index. rotate : bool Allow rotation of the ``src_pts``. translate : bool Allow translation of the ``src_pts``. scale : bool Number of scaling parameters. With False, points are not scaled. With True, points are scaled by the same factor along all axes. tol : scalar | None The error tolerance. If the distance between any of the matched points exceeds this value in the solution, a RuntimeError is raised. With None, no error check is performed. x0 : None | tuple Initial values for the fit parameters. out : 'params' | 'trans' In what format to return the estimate: 'params' returns a tuple with the fit parameters; 'trans' returns a transformation matrix of shape (4, 4). Returns ------- trans : array, shape (4, 4) Transformation that, if applied to src_pts, minimizes the squared distance to tgt_pts. Only returned if out=='trans'. params : array, shape (n_params, ) A single tuple containing the rotation, translation, and scaling parameters in that order (as applicable). """ src_pts = np.atleast_2d(src_pts) tgt_pts = np.atleast_2d(tgt_pts) if src_pts.shape != tgt_pts.shape: raise ValueError("src_pts and tgt_pts must have same shape (got " "{}, {})".format(src_pts.shape, tgt_pts.shape)) if weights is not None: weights = np.asarray(weights, src_pts.dtype) if weights.ndim != 1 or weights.size not in (src_pts.shape[0], 1): raise ValueError("weights (shape=%s) must be None or have shape " "(%s,)" % (weights.shape, src_pts.shape[0],)) weights = weights[:, np.newaxis] param_info = (bool(rotate), bool(translate), int(scale)) del rotate, translate, scale # very common use case, rigid transformation (maybe with one scale factor, # with or without weighted errors) if param_info in ((True, True, 0), (True, True, 1)) and _ALLOW_ANALITICAL: src_pts = np.asarray(src_pts, float) tgt_pts = np.asarray(tgt_pts, float) if weights is not None: weights = np.asarray(weights, float) x, s = _fit_matched_points( src_pts, tgt_pts, weights, bool(param_info[2])) x[:3] = _quat_to_euler(x[:3]) x = np.concatenate((x, [s])) if param_info[2] else x else: x = _generic_fit(src_pts, tgt_pts, param_info, weights, x0) # re-create the final transformation matrix if (tol is not None) or (out == 'trans'): trans = _trans_from_params(param_info, x) # assess the error of the solution if tol is not None: src_pts = np.hstack((src_pts, np.ones((len(src_pts), 1)))) est_pts = np.dot(src_pts, trans.T)[:, :3] err = np.sqrt(np.sum((est_pts - tgt_pts) ** 2, axis=1)) if np.any(err > tol): raise RuntimeError("Error exceeds tolerance. Error = %r" % err) if out == 'params': return x elif out == 'trans': return trans else: raise ValueError("Invalid out parameter: %r. Needs to be 'params' or " "'trans'." % out) def _generic_fit(src_pts, tgt_pts, param_info, weights, x0): from scipy.optimize import leastsq if param_info[1]: # translate src_pts = np.hstack((src_pts, np.ones((len(src_pts), 1)))) if param_info == (True, False, 0): def error(x): rx, ry, rz = x trans = rotation3d(rx, ry, rz) est = np.dot(src_pts, trans.T) d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0) elif param_info == (True, True, 0): def error(x): rx, ry, rz, tx, ty, tz = x trans = np.dot(translation(tx, ty, tz), rotation(rx, ry, rz)) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0) elif param_info == (True, True, 1): def error(x): rx, ry, rz, tx, ty, tz, s = x trans = reduce(np.dot, (translation(tx, ty, tz), rotation(rx, ry, rz), scaling(s, s, s))) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0, 1) elif param_info == (True, True, 3): def error(x): rx, ry, rz, tx, ty, tz, sx, sy, sz = x trans = reduce(np.dot, (translation(tx, ty, tz), rotation(rx, ry, rz), scaling(sx, sy, sz))) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0, 1, 1, 1) else: raise NotImplementedError( "The specified parameter combination is not implemented: " "rotate=%r, translate=%r, scale=%r" % param_info) x, _, _, _, _ = leastsq(error, x0, full_output=True) return x def _find_label_paths(subject='fsaverage', pattern=None, subjects_dir=None): """Find paths to label files in a subject's label directory. Parameters ---------- subject : str Name of the mri subject. pattern : str | None Pattern for finding the labels relative to the label directory in the MRI subject directory (e.g., "aparc/*.label" will find all labels in the "subject/label/aparc" directory). With None, find all labels. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (sys.environ['SUBJECTS_DIR']) Returns ------- paths : list List of paths relative to the subject's label directory """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) subject_dir = os.path.join(subjects_dir, subject) lbl_dir = os.path.join(subject_dir, 'label') if pattern is None: paths = [] for dirpath, _, filenames in os.walk(lbl_dir): rel_dir = os.path.relpath(dirpath, lbl_dir) for filename in fnmatch.filter(filenames, '*.label'): path = os.path.join(rel_dir, filename) paths.append(path) else: paths = [os.path.relpath(path, lbl_dir) for path in iglob(pattern)] return paths def _find_mri_paths(subject, skip_fiducials, subjects_dir): """Find all files of an mri relevant for source transformation. Parameters ---------- subject : str Name of the mri subject. skip_fiducials : bool Do not scale the MRI fiducials. If False, an IOError will be raised if no fiducials file can be found. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (sys.environ['SUBJECTS_DIR']) Returns ------- paths : dict Dictionary whose keys are relevant file type names (str), and whose values are lists of paths. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) paths = {} # directories to create paths['dirs'] = [bem_dirname, surf_dirname] # surf/ files paths['surf'] = [] surf_fname = os.path.join(surf_dirname, '{name}') surf_names = ('inflated', 'white', 'orig', 'orig_avg', 'inflated_avg', 'inflated_pre', 'pial', 'pial_avg', 'smoothwm', 'white_avg', 'seghead', 'smseghead') if os.getenv('_MNE_FEW_SURFACES', '') == 'true': # for testing surf_names = surf_names[:4] for surf_name in surf_names: for hemi in ('lh.', 'rh.'): name = hemi + surf_name path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=name) if os.path.exists(path): paths['surf'].append(pformat(surf_fname, name=name)) surf_fname = os.path.join(bem_dirname, '{name}') surf_names = ('inner_skull.surf', 'outer_skull.surf', 'outer_skin.surf') for surf_name in surf_names: path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=surf_name) if os.path.exists(path): paths['surf'].append(pformat(surf_fname, name=surf_name)) del surf_names, surf_name, path, hemi # BEM files paths['bem'] = bem = [] path = head_bem_fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): bem.append('head') bem_pattern = pformat(bem_fname, subjects_dir=subjects_dir, subject=subject, name='*-bem') re_pattern = pformat(bem_fname, subjects_dir=subjects_dir, subject=subject, name='(.+)').replace('\\', '\\\\') for path in iglob(bem_pattern): match = re.match(re_pattern, path) name = match.group(1) bem.append(name) del bem, path, bem_pattern, re_pattern # fiducials if skip_fiducials: paths['fid'] = [] else: paths['fid'] = _find_fiducials_files(subject, subjects_dir) # check that we found at least one if len(paths['fid']) == 0: raise IOError("No fiducials file found for %s. The fiducials " "file should be named " "{subject}/bem/{subject}-fiducials.fif. In " "order to scale an MRI without fiducials set " "skip_fiducials=True." % subject) # duplicate files (curvature and some surfaces) paths['duplicate'] = [] path = os.path.join(surf_dirname, '{name}') surf_fname = os.path.join(surf_dirname, '{name}') surf_dup_names = ('curv', 'sphere', 'sphere.reg', 'sphere.reg.avg') for surf_dup_name in surf_dup_names: for hemi in ('lh.', 'rh.'): name = hemi + surf_dup_name path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=name) if os.path.exists(path): paths['duplicate'].append(pformat(surf_fname, name=name)) del surf_dup_name, name, path, hemi # transform files (talairach) paths['transforms'] = [] transform_fname = os.path.join(mri_transforms_dirname, 'talairach.xfm') path = transform_fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): paths['transforms'].append(transform_fname) del transform_fname, path # find source space files paths['src'] = src = [] bem_dir = bem_dirname.format(subjects_dir=subjects_dir, subject=subject) fnames = fnmatch.filter(os.listdir(bem_dir), '*-src.fif') prefix = subject + '-' for fname in fnames: if fname.startswith(prefix): fname = "{subject}-%s" % fname[len(prefix):] path = os.path.join(bem_dirname, fname) src.append(path) # find MRIs mri_dir = mri_dirname.format(subjects_dir=subjects_dir, subject=subject) fnames = fnmatch.filter(os.listdir(mri_dir), '*.mgz') paths['mri'] = [os.path.join(mri_dir, f) for f in fnames] return paths def _find_fiducials_files(subject, subjects_dir): """Find fiducial files.""" fid = [] # standard fiducials if os.path.exists(fid_fname.format(subjects_dir=subjects_dir, subject=subject)): fid.append(fid_fname) # fiducials with subject name pattern = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='*') regex = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='(.+)').replace('\\', '\\\\') for path in iglob(pattern): match = re.match(regex, path) head = match.group(1).replace(subject, '{subject}') fid.append(pformat(fid_fname_general, head=head)) return fid def _is_mri_subject(subject, subjects_dir=None): """Check whether a directory in subjects_dir is an mri subject directory. Parameters ---------- subject : str Name of the potential subject/directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- is_mri_subject : bool Whether ``subject`` is an mri subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) return bool(_find_head_bem(subject, subjects_dir) or _find_head_bem(subject, subjects_dir, high_res=True)) def _is_scaled_mri_subject(subject, subjects_dir=None): """Check whether a directory in subjects_dir is a scaled mri subject. Parameters ---------- subject : str Name of the potential subject/directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- is_scaled_mri_subject : bool Whether ``subject`` is a scaled mri subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if not _is_mri_subject(subject, subjects_dir): return False fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg') return os.path.exists(fname) def _mri_subject_has_bem(subject, subjects_dir=None): """Check whether an mri subject has a file matching the bem pattern. Parameters ---------- subject : str Name of the subject. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- has_bem_file : bool Whether ``subject`` has a bem file. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) pattern = bem_fname.format(subjects_dir=subjects_dir, subject=subject, name='*-bem') fnames = glob(pattern) return bool(len(fnames)) def read_mri_cfg(subject, subjects_dir=None): """Read information from the cfg file of a scaled MRI brain. Parameters ---------- subject : str Name of the scaled MRI subject. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- cfg : dict Dictionary with entries from the MRI's cfg file. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg') if not os.path.exists(fname): raise IOError("%r does not seem to be a scaled mri subject: %r does " "not exist." % (subject, fname)) logger.info("Reading MRI cfg file %s" % fname) config = configparser.RawConfigParser() config.read(fname) n_params = config.getint("MRI Scaling", 'n_params') if n_params == 1: scale = config.getfloat("MRI Scaling", 'scale') elif n_params == 3: scale_str = config.get("MRI Scaling", 'scale') scale = np.array([float(s) for s in scale_str.split()]) else: raise ValueError("Invalid n_params value in MRI cfg: %i" % n_params) out = {'subject_from': config.get("MRI Scaling", 'subject_from'), 'n_params': n_params, 'scale': scale} return out def _write_mri_config(fname, subject_from, subject_to, scale): """Write the cfg file describing a scaled MRI subject. Parameters ---------- fname : str Target file. subject_from : str Name of the source MRI subject. subject_to : str Name of the scaled MRI subject. scale : float | array_like, shape = (3,) The scaling parameter. """ scale = np.asarray(scale) if np.isscalar(scale) or scale.shape == (): n_params = 1 else: n_params = 3 config = configparser.RawConfigParser() config.add_section("MRI Scaling") config.set("MRI Scaling", 'subject_from', subject_from) config.set("MRI Scaling", 'subject_to', subject_to) config.set("MRI Scaling", 'n_params', str(n_params)) if n_params == 1: config.set("MRI Scaling", 'scale', str(scale)) else: config.set("MRI Scaling", 'scale', ' '.join([str(s) for s in scale])) config.set("MRI Scaling", 'version', '1') with open(fname, 'w') as fid: config.write(fid) def _scale_params(subject_to, subject_from, scale, subjects_dir): """Assemble parameters for scaling. Returns ------- subjects_dir : str Subjects directory. subject_from : str Name of the source subject. scale : array Scaling factor, either shape=() for uniform scaling or shape=(3,) for non-uniform scaling. uniform : bool Whether scaling is uniform. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if (subject_from is None) != (scale is None): raise TypeError("Need to provide either both subject_from and scale " "parameters, or neither.") if subject_from is None: cfg = read_mri_cfg(subject_to, subjects_dir) subject_from = cfg['subject_from'] n_params = cfg['n_params'] assert n_params in (1, 3) scale = cfg['scale'] scale = np.atleast_1d(scale) if scale.ndim != 1 or scale.shape[0] not in (1, 3): raise ValueError("Invalid shape for scale parameer. Need scalar " "or array of length 3. Got shape %s." % (scale.shape,)) n_params = len(scale) return subjects_dir, subject_from, scale, n_params == 1 @verbose def scale_bem(subject_to, bem_name, subject_from=None, scale=None, subjects_dir=None, *, on_defects='raise', verbose=None): """Scale a bem file. Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination mri subject). bem_name : str Name of the bem file. For example, to scale ``fsaverage-inner_skull-bem.fif``, the bem_name would be "inner_skull-bem". subject_from : None | str The subject from which to read the source space. If None, subject_from is read from subject_to's config file. scale : None | float | array, shape = (3,) Scaling factor. Has to be specified if subjects_from is specified, otherwise it is read from subject_to's config file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. %(on_defects)s .. versionadded:: 1.0 %(verbose)s """ subjects_dir, subject_from, scale, uniform = \ _scale_params(subject_to, subject_from, scale, subjects_dir) src = bem_fname.format(subjects_dir=subjects_dir, subject=subject_from, name=bem_name) dst = bem_fname.format(subjects_dir=subjects_dir, subject=subject_to, name=bem_name) if os.path.exists(dst): raise IOError("File already exists: %s" % dst) surfs = read_bem_surfaces(src, on_defects=on_defects) for surf in surfs: surf['rr'] *= scale if not uniform: assert len(surf['nn']) > 0 surf['nn'] /= scale _normalize_vectors(surf['nn']) write_bem_surfaces(dst, surfs) def scale_labels(subject_to, pattern=None, overwrite=False, subject_from=None, scale=None, subjects_dir=None): r"""Scale labels to match a brain that was previously created by scaling. Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination brain). pattern : str | None Pattern for finding the labels relative to the label directory in the MRI subject directory (e.g., "lh.BA3a.label" will scale "fsaverage/label/lh.BA3a.label"; "aparc/\*.label" will find all labels in the "fsaverage/label/aparc" directory). With None, scale all labels. overwrite : bool Overwrite any label file that already exists for subject_to (otherwise existing labels are skipped). subject_from : None | str Name of the original MRI subject (the brain that was scaled to create subject_to). If None, the value is read from subject_to's cfg file. scale : None | float | array_like, shape = (3,) Scaling parameter. If None, the value is read from subject_to's cfg file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. """ subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) # find labels paths = _find_label_paths(subject_from, pattern, subjects_dir) if not paths: return subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) src_root = os.path.join(subjects_dir, subject_from, 'label') dst_root = os.path.join(subjects_dir, subject_to, 'label') # scale labels for fname in paths: dst = os.path.join(dst_root, fname) if not overwrite and os.path.exists(dst): continue dirname = os.path.dirname(dst) if not os.path.exists(dirname): os.makedirs(dirname) src = os.path.join(src_root, fname) l_old = read_label(src) pos = l_old.pos * scale l_new = Label(l_old.vertices, pos, l_old.values, l_old.hemi, l_old.comment, subject=subject_to) l_new.save(dst) @verbose def scale_mri(subject_from, subject_to, scale, overwrite=False, subjects_dir=None, skip_fiducials=False, labels=True, annot=False, *, on_defects='raise', verbose=None): """Create a scaled copy of an MRI subject. Parameters ---------- subject_from : str Name of the subject providing the MRI. subject_to : str New subject name for which to save the scaled MRI. scale : float | array_like, shape = (3,) The scaling factor (one or 3 parameters). overwrite : bool If an MRI already exists for subject_to, overwrite it. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. skip_fiducials : bool Do not scale the MRI fiducials. If False (default), an IOError will be raised if no fiducials file can be found. labels : bool Also scale all labels (default True). annot : bool Copy ``*.annot`` files to the new location (default False). %(on_defects)s .. versionadded:: 1.0 %(verbose)s See Also -------- scale_bem : Add a scaled BEM to a scaled MRI. scale_labels : Add labels to a scaled MRI. scale_source_space : Add a source space to a scaled MRI. Notes ----- This function will automatically call :func:`scale_bem`, :func:`scale_labels`, and :func:`scale_source_space` based on expected filename patterns in the subject directory. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) paths = _find_mri_paths(subject_from, skip_fiducials, subjects_dir) scale = np.atleast_1d(scale) if scale.shape == (3,): if np.isclose(scale[1], scale[0]) and np.isclose(scale[2], scale[0]): scale = scale[0] # speed up scaling conditionals using a singleton elif scale.shape != (1,): raise ValueError('scale must have shape (3,) or (1,), got %s' % (scale.shape,)) # make sure we have an empty target directory dest = subject_dirname.format(subject=subject_to, subjects_dir=subjects_dir) if os.path.exists(dest): if not overwrite: raise IOError("Subject directory for %s already exists: %r" % (subject_to, dest)) shutil.rmtree(dest) logger.debug('create empty directory structure') for dirname in paths['dirs']: dir_ = dirname.format(subject=subject_to, subjects_dir=subjects_dir) os.makedirs(dir_) logger.debug('save MRI scaling parameters') fname = os.path.join(dest, 'MRI scaling parameters.cfg') _write_mri_config(fname, subject_from, subject_to, scale) logger.debug('surf files [in mm]') for fname in paths['surf']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) src = os.path.realpath(src) dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) pts, tri = read_surface(src) write_surface(dest, pts * scale, tri) logger.debug('BEM files [in m]') for bem_name in paths['bem']: scale_bem(subject_to, bem_name, subject_from, scale, subjects_dir, on_defects=on_defects, verbose=False) logger.debug('fiducials [in m]') for fname in paths['fid']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) src = os.path.realpath(src) pts, cframe = read_fiducials(src, verbose=False) for pt in pts: pt['r'] = pt['r'] * scale dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) write_fiducials(dest, pts, cframe, overwrite=True, verbose=False) logger.debug('MRIs [nibabel]') os.mkdir(mri_dirname.format(subjects_dir=subjects_dir, subject=subject_to)) for fname in paths['mri']: mri_name = os.path.basename(fname) _scale_mri(subject_to, mri_name, subject_from, scale, subjects_dir) logger.debug('Transforms') for mri_name in paths['mri']: if mri_name.endswith('T1.mgz'): os.mkdir(mri_transforms_dirname.format(subjects_dir=subjects_dir, subject=subject_to)) for fname in paths['transforms']: xfm_name = os.path.basename(fname) _scale_xfm(subject_to, xfm_name, mri_name, subject_from, scale, subjects_dir) break logger.debug('duplicate files') for fname in paths['duplicate']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) shutil.copyfile(src, dest) logger.debug('source spaces') for fname in paths['src']: src_name = os.path.basename(fname) scale_source_space(subject_to, src_name, subject_from, scale, subjects_dir, verbose=False) logger.debug('labels [in m]') os.mkdir(os.path.join(subjects_dir, subject_to, 'label')) if labels: scale_labels(subject_to, subject_from=subject_from, scale=scale, subjects_dir=subjects_dir) logger.debug('copy *.annot files') # they don't contain scale-dependent information if annot: src_pattern = os.path.join(subjects_dir, subject_from, 'label', '*.annot') dst_dir = os.path.join(subjects_dir, subject_to, 'label') for src_file in iglob(src_pattern): shutil.copy(src_file, dst_dir) @verbose def scale_source_space(subject_to, src_name, subject_from=None, scale=None, subjects_dir=None, n_jobs=1, verbose=None): """Scale a source space for an mri created with scale_mri(). Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination mri subject). src_name : str Source space name. Can be a spacing parameter (e.g., ``'7'``, ``'ico4'``, ``'oct6'``) or a file name of a source space file relative to the bem directory; if the file name contains the subject name, it should be indicated as "{subject}" in ``src_name`` (e.g., ``"{subject}-my_source_space-src.fif"``). subject_from : None | str The subject from which to read the source space. If None, subject_from is read from subject_to's config file. scale : None | float | array, shape = (3,) Scaling factor. Has to be specified if subjects_from is specified, otherwise it is read from subject_to's config file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. n_jobs : int Number of jobs to run in parallel if recomputing distances (only applies if scale is an array of length 3, and will not use more cores than there are source spaces). %(verbose)s Notes ----- When scaling volume source spaces, the source (vertex) locations are scaled, but the reference to the MRI volume is left unchanged. Transforms are updated so that source estimates can be plotted on the original MRI volume. """ subjects_dir, subject_from, scale, uniform = \ _scale_params(subject_to, subject_from, scale, subjects_dir) # if n_params==1 scale is a scalar; if n_params==3 scale is a (3,) array # find the source space file names if src_name.isdigit(): spacing = src_name # spacing in mm src_pattern = src_fname else: match = re.match(r"(oct|ico|vol)-?(\d+)$", src_name) if match: spacing = '-'.join(match.groups()) src_pattern = src_fname else: spacing = None src_pattern = os.path.join(bem_dirname, src_name) src = src_pattern.format(subjects_dir=subjects_dir, subject=subject_from, spacing=spacing) dst = src_pattern.format(subjects_dir=subjects_dir, subject=subject_to, spacing=spacing) # read and scale the source space [in m] sss = read_source_spaces(src) logger.info("scaling source space %s: %s -> %s", spacing, subject_from, subject_to) logger.info("Scale factor: %s", scale) add_dist = False for ss in sss: ss['subject_his_id'] = subject_to ss['rr'] *= scale # additional tags for volume source spaces for key in ('vox_mri_t', 'src_mri_t'): # maintain transform to original MRI volume ss['mri_volume_name'] if key in ss: ss[key]['trans'][:3] *= scale[:, np.newaxis] # distances and patch info if uniform: if ss['dist'] is not None: ss['dist'] *= scale[0] # Sometimes this is read-only due to how it's read ss['nearest_dist'] = ss['nearest_dist'] * scale ss['dist_limit'] = ss['dist_limit'] * scale else: # non-uniform scaling ss['nn'] /= scale _normalize_vectors(ss['nn']) if ss['dist'] is not None: add_dist = True dist_limit = float(np.abs(sss[0]['dist_limit'])) elif ss['nearest'] is not None: add_dist = True dist_limit = 0 if add_dist: logger.info("Recomputing distances, this might take a while") add_source_space_distances(sss, dist_limit, n_jobs) write_source_spaces(dst, sss) def _scale_mri(subject_to, mri_fname, subject_from, scale, subjects_dir): """Scale an MRI by setting its affine.""" subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) if not has_nibabel(): warn('Skipping MRI scaling for %s, please install nibabel') return import nibabel fname_from = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_from), mri_fname) fname_to = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_to), mri_fname) img = nibabel.load(fname_from) zooms = np.array(img.header.get_zooms()) zooms[[0, 2, 1]] *= scale img.header.set_zooms(zooms) # Hack to fix nibabel problems, see # https://github.com/nipy/nibabel/issues/619 img._affine = img.header.get_affine() # or could use None nibabel.save(img, fname_to) def _scale_xfm(subject_to, xfm_fname, mri_name, subject_from, scale, subjects_dir): """Scale a transform.""" subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) # The nibabel warning should already be there in MRI step, if applicable, # as we only get here if T1.mgz is present (and thus a scaling was # attempted) so we can silently return here. if not has_nibabel(): return fname_from = os.path.join( mri_transforms_dirname.format( subjects_dir=subjects_dir, subject=subject_from), xfm_fname) fname_to = op.join( mri_transforms_dirname.format( subjects_dir=subjects_dir, subject=subject_to), xfm_fname) assert op.isfile(fname_from), fname_from assert op.isdir(op.dirname(fname_to)), op.dirname(fname_to) # The "talairach.xfm" file stores the ras_mni transform. # # For "from" subj F, "to" subj T, F->T scaling S, some equivalent vertex # positions F_x and T_x in MRI (Freesurfer RAS) coords, knowing that # we have T_x = S @ F_x, we want to have the same MNI coords computed # for these vertices: # # T_mri_mni @ T_x = F_mri_mni @ F_x # # We need to find the correct T_ras_mni (talaraich.xfm file) that yields # this. So we derive (where † indicates inversion): # # T_mri_mni @ S @ F_x = F_mri_mni @ F_x # T_mri_mni @ S = F_mri_mni # T_ras_mni @ T_mri_ras @ S = F_ras_mni @ F_mri_ras # T_ras_mni @ T_mri_ras = F_ras_mni @ F_mri_ras @ S⁻¹ # T_ras_mni = F_ras_mni @ F_mri_ras @ S⁻¹ @ T_ras_mri # # prepare the scale (S) transform scale = np.atleast_1d(scale) scale = np.tile(scale, 3) if len(scale) == 1 else scale S = Transform('mri', 'mri', scaling(*scale)) # F_mri->T_mri # # Get the necessary transforms of the "from" subject # xfm, kind = _read_fs_xfm(fname_from) assert kind == 'MNI Transform File', kind _, _, F_mri_ras, _, _ = _read_mri_info(mri_name, units='mm') F_ras_mni = Transform('ras', 'mni_tal', xfm) del xfm # # Get the necessary transforms of the "to" subject # mri_name = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_to), op.basename(mri_name)) _, _, T_mri_ras, _, _ = _read_mri_info(mri_name, units='mm') T_ras_mri = invert_transform(T_mri_ras) del mri_name, T_mri_ras # Finally we construct as above: # # T_ras_mni = F_ras_mni @ F_mri_ras @ S⁻¹ @ T_ras_mri # # By moving right to left through the equation. T_ras_mni = \ combine_transforms( combine_transforms( combine_transforms( T_ras_mri, invert_transform(S), 'ras', 'mri'), F_mri_ras, 'ras', 'ras'), F_ras_mni, 'ras', 'mni_tal') _write_fs_xfm(fname_to, T_ras_mni['trans'], kind) def _read_surface(filename, *, on_defects): bem = dict() if filename is not None and op.exists(filename): if filename.endswith('.fif'): bem = read_bem_surfaces( filename, on_defects=on_defects, verbose=False )[0] else: try: bem = read_surface(filename, return_dict=True)[2] bem['rr'] *= 1e-3 complete_surface_info(bem, copy=False) except Exception: raise ValueError( "Error loading surface from %s (see " "Terminal for details)." % filename) return bem @fill_doc class Coregistration(object): """Class for MRI<->head coregistration. Parameters ---------- info : instance of Info | None The measurement info. %(subject)s %(subjects_dir)s %(fiducials)s %(on_defects)s .. versionadded:: 1.0 Attributes ---------- fiducials : instance of DigMontage A montage containing the MRI fiducials. trans : instance of Transform MRI<->Head coordinate transformation. See Also -------- mne.scale_mri Notes ----- Internal computation quantities parameters are in the following units: - rotation are in radians - translation are in m - scale are in scale proportion If using a scale mode, the :func:`~mne.scale_mri` should be used to create a surrogate MRI subject with the proper scale factors. """ def __init__(self, info, subject, subjects_dir=None, fiducials='auto', *, on_defects='raise'): _validate_type(info, (Info, None), 'info') self._info = info self._subject = _check_subject(subject, subject) self._subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) self._scale_mode = None self._on_defects = on_defects self._rot_trans = None self._default_parameters = \ np.array([0., 0., 0., 0., 0., 0., 1., 1., 1.]) self._rotation = self._default_parameters[:3] self._translation = self._default_parameters[3:6] self._scale = self._default_parameters[6:9] self._icp_iterations = 20 self._icp_angle = 0.2 self._icp_distance = 0.2 self._icp_scale = 0.2 self._icp_fid_matches = ('nearest', 'matched') self._icp_fid_match = self._icp_fid_matches[0] self._lpa_weight = 1. self._nasion_weight = 10. self._rpa_weight = 1. self._hsp_weight = 1. self._eeg_weight = 1. self._hpi_weight = 1. self._extra_points_filter = None self._setup_digs() self._setup_bem() self._fid_filename = None self._setup_fiducials(fiducials) self.reset() def _setup_digs(self): if self._info is None: self._dig_dict = dict( hpi=np.zeros((1, 3)), dig_ch_pos_location=np.zeros((1, 3)), hsp=np.zeros((1, 3)), rpa=np.zeros((1, 3)), nasion=np.zeros((1, 3)), lpa=np.zeros((1, 3)), ) else: self._dig_dict = _get_data_as_dict_from_dig( dig=self._info['dig'], exclude_ref_channel=False ) # adjustments: # set weights to 0 for None input # convert fids to float arrays for k, w_atr in zip(['nasion', 'lpa', 'rpa', 'hsp', 'hpi'], ['_nasion_weight', '_lpa_weight', '_rpa_weight', '_hsp_weight', '_hpi_weight']): if self._dig_dict[k] is None: self._dig_dict[k] = np.zeros((0, 3)) setattr(self, w_atr, 0) elif k in ['rpa', 'nasion', 'lpa']: self._dig_dict[k] = np.array([self._dig_dict[k]], float) def _setup_bem(self): # find high-res head model (if possible) high_res_path = _find_head_bem(self._subject, self._subjects_dir, high_res=True) low_res_path = _find_head_bem(self._subject, self._subjects_dir, high_res=False) if high_res_path is None and low_res_path is None: raise RuntimeError("No standard head model was " f"found for subject {self._subject}") if high_res_path is not None: self._bem_high_res = _read_surface( high_res_path, on_defects=self._on_defects ) logger.info(f'Using high resolution head model in {high_res_path}') else: self._bem_high_res = _read_surface( low_res_path, on_defects=self._on_defects ) logger.info(f'Using low resolution head model in {low_res_path}') if low_res_path is None: # This should be very rare! warn('No low-resolution head found, decimating high resolution ' 'mesh (%d vertices): %s' % (len(self._bem_high_res.surf.rr), high_res_path,)) # Create one from the high res one, which we know we have rr, tris = decimate_surface(self._bem_high_res.surf.rr, self._bem_high_res.surf.tris, n_triangles=5120) # directly set the attributes of bem_low_res self._bem_low_res = complete_surface_info( dict(rr=rr, tris=tris), copy=False, verbose=False) else: self._bem_low_res = _read_surface( low_res_path, on_defects=self._on_defects ) def _setup_fiducials(self, fids): _validate_type(fids, (str, dict, list)) # find fiducials file fid_accurate = None if fids == 'auto': fid_files = _find_fiducials_files(self._subject, self._subjects_dir) if len(fid_files) > 0: # Read fiducials from disk fid_filename = fid_files[0].format( subjects_dir=self._subjects_dir, subject=self._subject) logger.info(f'Using fiducials from: {fid_filename}.') fids, _ = read_fiducials(fid_filename) fid_accurate = True self._fid_filename = fid_filename else: fids = 'estimated' if fids == 'estimated': logger.info('Estimating fiducials from fsaverage.') fid_accurate = False fids = get_mni_fiducials(self._subject, self._subjects_dir) fid_accurate = True if fid_accurate is None else fid_accurate if isinstance(fids, list): fid_coords = _fiducial_coords(fids) else: assert isinstance(fids, dict) fid_coords = np.array([fids['lpa'], fids['nasion'], fids['rpa']], dtype=float) self._fid_points = fid_coords self._fid_accurate = fid_accurate # does not seem to happen by itself ... so hard code it: self._reset_fiducials() def _reset_fiducials(self): dig_montage = make_dig_montage( lpa=self._fid_points[0], nasion=self._fid_points[1], rpa=self._fid_points[2], coord_frame='mri' ) self.fiducials = dig_montage def _update_params(self, rot=None, tra=None, sca=None, force_update_omitted=False): if force_update_omitted: tra = self._translation rot_changed = False if rot is not None: rot_changed = True self._last_rotation = self._rotation.copy() self._rotation = rot tra_changed = False if rot_changed or tra is not None: if tra is None: tra = self._translation tra_changed = True self._last_translation = self._translation.copy() self._translation = tra self._head_mri_t = rotation(*self._rotation).T self._head_mri_t[:3, 3] = \ -np.dot(self._head_mri_t[:3, :3], tra) self._transformed_dig_hpi = \ apply_trans(self._head_mri_t, self._dig_dict['hpi']) self._transformed_dig_eeg = \ apply_trans( self._head_mri_t, self._dig_dict['dig_ch_pos_location']) self._transformed_dig_extra = \ apply_trans(self._head_mri_t, self._filtered_extra_points) self._transformed_orig_dig_extra = \ apply_trans(self._head_mri_t, self._dig_dict['hsp']) self._mri_head_t = rotation(*self._rotation) self._mri_head_t[:3, 3] = np.array(tra) if tra_changed or sca is not None: if sca is None: sca = self._scale self._last_scale = self._scale.copy() self._scale = sca self._mri_trans = np.eye(4) self._mri_trans[:, :3] *= sca self._transformed_high_res_mri_points = \ apply_trans(self._mri_trans, self._processed_high_res_mri_points) self._update_nearest_calc() if tra_changed: self._nearest_transformed_high_res_mri_idx_orig_hsp = \ self._nearest_calc.query(self._transformed_orig_dig_extra)[1] self._nearest_transformed_high_res_mri_idx_hpi = \ self._nearest_calc.query(self._transformed_dig_hpi)[1] self._nearest_transformed_high_res_mri_idx_eeg = \ self._nearest_calc.query(self._transformed_dig_eeg)[1] self._nearest_transformed_high_res_mri_idx_rpa = \ self._nearest_calc.query( apply_trans(self._head_mri_t, self._dig_dict['rpa']))[1] self._nearest_transformed_high_res_mri_idx_nasion = \ self._nearest_calc.query( apply_trans(self._head_mri_t, self._dig_dict['nasion']))[1] self._nearest_transformed_high_res_mri_idx_lpa = \ self._nearest_calc.query( apply_trans(self._head_mri_t, self._dig_dict['lpa']))[1] def set_scale_mode(self, scale_mode): """Select how to fit the scale parameters. Parameters ---------- scale_mode : None | str The scale mode can be 'uniform', '3-axis' or disabled. Defaults to None. * 'uniform': 1 scale factor is recovered. * '3-axis': 3 scale factors are recovered. * None: do not scale the MRI. Returns ------- self : Coregistration The modified Coregistration object. """ self._scale_mode = scale_mode return self def set_grow_hair(self, value): """Compensate for hair on the digitizer head shape. Parameters ---------- value : float Move the back of the MRI head outwards by ``value`` (mm). Returns ------- self : Coregistration The modified Coregistration object. """ self._grow_hair = value self._update_params(self._rotation, self._translation, self._scale) return self def set_rotation(self, rot): """Set the rotation parameter. Parameters ---------- rot : array, shape (3,) The rotation parameter (in radians). Returns ------- self : Coregistration The modified Coregistration object. """ self._update_params(rot=np.array(rot)) return self def set_translation(self, tra): """Set the translation parameter. Parameters ---------- tra : array, shape (3,) The translation parameter (in m.). Returns ------- self : Coregistration The modified Coregistration object. """ self._update_params(tra=np.array(tra)) return self def set_scale(self, sca): """Set the scale parameter. Parameters ---------- sca : array, shape (3,) The scale parameter. Returns ------- self : Coregistration The modified Coregistration object. """ self._update_params(sca=np.array(sca)) return self def _update_nearest_calc(self): self._nearest_calc = _DistanceQuery( self._processed_high_res_mri_points * self._scale) @property def _filtered_extra_points(self): if self._extra_points_filter is None: return self._dig_dict['hsp'] else: return self._dig_dict['hsp'][self._extra_points_filter] @property def _parameters(self): return np.concatenate((self._rotation, self._translation, self._scale)) @property def _last_parameters(self): return np.concatenate((self._last_rotation, self._last_translation, self._last_scale)) @property def _changes(self): move = np.linalg.norm(self._last_translation - self._translation) * 1e3 angle = np.rad2deg(_angle_between_quats( rot_to_quat(rotation(*self._rotation)[:3, :3]), rot_to_quat(rotation(*self._last_rotation)[:3, :3]))) percs = 100 * (self._scale - self._last_scale) / self._last_scale return move, angle, percs @property def _nearest_transformed_high_res_mri_idx_hsp(self): return self._nearest_calc.query( apply_trans(self._head_mri_t, self._filtered_extra_points))[1] @property def _has_hsp_data(self): return (self._has_mri_data and len(self._nearest_transformed_high_res_mri_idx_hsp) > 0) @property def _has_hpi_data(self): return (self._has_mri_data and len(self._nearest_transformed_high_res_mri_idx_hpi) > 0) @property def _has_eeg_data(self): return (self._has_mri_data and len(self._nearest_transformed_high_res_mri_idx_eeg) > 0) @property def _has_lpa_data(self): mri_point = self.fiducials.dig[_map_fid_name_to_idx('lpa')] assert mri_point['ident'] == FIFF.FIFFV_POINT_LPA has_mri_data = np.any(mri_point['r']) has_head_data = np.any(self._dig_dict['lpa']) return has_mri_data and has_head_data @property def _has_nasion_data(self): mri_point = self.fiducials.dig[_map_fid_name_to_idx('nasion')] assert mri_point['ident'] == FIFF.FIFFV_POINT_NASION has_mri_data = np.any(mri_point['r']) has_head_data = np.any(self._dig_dict['nasion']) return has_mri_data and has_head_data @property def _has_rpa_data(self): mri_point = self.fiducials.dig[_map_fid_name_to_idx('rpa')] assert mri_point['ident'] == FIFF.FIFFV_POINT_RPA has_mri_data = np.any(mri_point['r']) has_head_data = np.any(self._dig_dict['rpa']) return has_mri_data and has_head_data @property def _processed_high_res_mri_points(self): return self._get_processed_mri_points('high') @property def _processed_low_res_mri_points(self): return self._get_processed_mri_points('low') def _get_processed_mri_points(self, res): bem = self._bem_low_res if res == 'low' else self._bem_high_res points = bem['rr'].copy() if self._grow_hair: assert len(bem['nn']) # should be guaranteed by _read_surface scaled_hair_dist = (1e-3 * self._grow_hair / np.array(self._scale)) hair = points[:, 2] > points[:, 1] points[hair] += bem['nn'][hair] * scaled_hair_dist return points @property def _has_mri_data(self): return len(self._transformed_high_res_mri_points) > 0 @property def _has_dig_data(self): return (self._has_mri_data and len(self._nearest_transformed_high_res_mri_idx_hsp) > 0) @property def _orig_hsp_point_distance(self): mri_points = self._transformed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_orig_hsp] hsp_points = self._transformed_orig_dig_extra return np.linalg.norm(mri_points - hsp_points, axis=-1) def _log_dig_mri_distance(self, prefix): errs_nearest = self.compute_dig_mri_distances() logger.info(f'{prefix} median distance: ' f'{np.median(errs_nearest * 1000):6.2f} mm') @property def scale(self): """Get the current scale factor. Returns ------- scale : ndarray, shape (3,) The scale factors. """ return self._scale.copy() @verbose def fit_fiducials(self, lpa_weight=1., nasion_weight=10., rpa_weight=1., verbose=None): """Find rotation and translation to fit all 3 fiducials. Parameters ---------- lpa_weight : float Relative weight for LPA. The default value is 1. nasion_weight : float Relative weight for nasion. The default value is 10. rpa_weight : float Relative weight for RPA. The default value is 1. %(verbose)s Returns ------- self : Coregistration The modified Coregistration object. """ logger.info('Aligning using fiducials') self._log_dig_mri_distance('Start') n_scale_params = self._n_scale_params if n_scale_params == 3: # enfore 1 even for 3-axis here (3 points is not enough) logger.info("Enforcing 1 scaling parameter for fit " "with fiducials.") n_scale_params = 1 self._lpa_weight = lpa_weight self._nasion_weight = nasion_weight self._rpa_weight = rpa_weight head_pts = np.vstack((self._dig_dict['lpa'], self._dig_dict['nasion'], self._dig_dict['rpa'])) mri_pts = np.vstack( (self.fiducials.dig[0]['r'], # LPA self.fiducials.dig[1]['r'], # Nasion self.fiducials.dig[2]['r']) # RPA ) weights = [lpa_weight, nasion_weight, rpa_weight] if n_scale_params == 0: mri_pts *= self._scale # not done in fit_matched_points x0 = self._parameters x0 = x0[:6 + n_scale_params] est = fit_matched_points(mri_pts, head_pts, x0=x0, out='params', scale=n_scale_params, weights=weights) if n_scale_params == 0: self._update_params(rot=est[:3], tra=est[3:6]) else: assert est.size == 7 est = np.concatenate([est, [est[-1]] * 2]) assert est.size == 9 self._update_params(rot=est[:3], tra=est[3:6], sca=est[6:9]) self._log_dig_mri_distance('End ') return self def _setup_icp(self, n_scale_params): head_pts = list() mri_pts = list() weights = list() if self._has_dig_data and self._hsp_weight > 0: # should be true head_pts.append(self._filtered_extra_points) mri_pts.append(self._processed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_hsp]) weights.append(np.full(len(head_pts[-1]), self._hsp_weight)) for key in ('lpa', 'nasion', 'rpa'): if getattr(self, f'_has_{key}_data'): head_pts.append(self._dig_dict[key]) if self._icp_fid_match == 'matched': idx = _map_fid_name_to_idx(name=key) p = self.fiducials.dig[idx]['r'].reshape(1, -1) mri_pts.append(p) else: assert self._icp_fid_match == 'nearest' mri_pts.append(self._processed_high_res_mri_points[ getattr( self, '_nearest_transformed_high_res_mri_idx_%s' % (key,))]) weights.append(np.full(len(mri_pts[-1]), getattr(self, '_%s_weight' % key))) if self._has_eeg_data and self._eeg_weight > 0: head_pts.append(self._dig_dict['dig_ch_pos_location']) mri_pts.append(self._processed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_eeg]) weights.append(np.full(len(mri_pts[-1]), self._eeg_weight)) if self._has_hpi_data and self._hpi_weight > 0: head_pts.append(self._dig_dict['hpi']) mri_pts.append(self._processed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_hpi]) weights.append(np.full(len(mri_pts[-1]), self._hpi_weight)) head_pts = np.concatenate(head_pts) mri_pts = np.concatenate(mri_pts) weights = np.concatenate(weights) if n_scale_params == 0: mri_pts *= self._scale # not done in fit_matched_points return head_pts, mri_pts, weights def set_fid_match(self, match): """Set the strategy for fitting anatomical landmark (fiducial) points. Parameters ---------- match : 'nearest' | 'matched' Alignment strategy; ``'nearest'`` aligns anatomical landmarks to any point on the head surface; ``'matched'`` aligns to the fiducial points in the MRI. Returns ------- self : Coregistration The modified Coregistration object. """ _check_option('match', match, self._icp_fid_matches) self._icp_fid_match = match return self @verbose def fit_icp(self, n_iterations=20, lpa_weight=1., nasion_weight=10., rpa_weight=1., hsp_weight=1., eeg_weight=1., hpi_weight=1., callback=None, verbose=None): """Find MRI scaling, translation, and rotation to match HSP. Parameters ---------- n_iterations : int Maximum number of iterations. lpa_weight : float Relative weight for LPA. The default value is 1. nasion_weight : float Relative weight for nasion. The default value is 10. rpa_weight : float Relative weight for RPA. The default value is 1. hsp_weight : float Relative weight for HSP. The default value is 1. eeg_weight : float Relative weight for EEG. The default value is 1. hpi_weight : float Relative weight for HPI. The default value is 1. callback : callable | None A function to call on each iteration. Useful for status message updates. It will be passed the keyword arguments ``iteration`` and ``n_iterations``. %(verbose)s Returns ------- self : Coregistration The modified Coregistration object. """ logger.info('Aligning using ICP') self._log_dig_mri_distance('Start ') n_scale_params = self._n_scale_params self._lpa_weight = lpa_weight self._nasion_weight = nasion_weight self._rpa_weight = rpa_weight self._hsp_weight = hsp_weight self._eeg_weight = eeg_weight self._hsp_weight = hpi_weight # Initial guess (current state) est = self._parameters est = est[:[6, 7, None, 9][n_scale_params]] # Do the fits, assigning and evaluating at each step for iteration in range(n_iterations): head_pts, mri_pts, weights = self._setup_icp(n_scale_params) est = fit_matched_points(mri_pts, head_pts, scale=n_scale_params, x0=est, out='params', weights=weights) if n_scale_params == 0: self._update_params(rot=est[:3], tra=est[3:6]) elif n_scale_params == 1: est = np.array(list(est) + [est[-1]] * 2) self._update_params(rot=est[:3], tra=est[3:6], sca=est[6:9]) else: self._update_params(rot=est[:3], tra=est[3:6], sca=est[6:9]) angle, move, scale = self._changes self._log_dig_mri_distance(f' ICP {iteration + 1:2d} ') if angle <= self._icp_angle and move <= self._icp_distance and \ all(scale <= self._icp_scale): break if callback is not None: callback(iteration, n_iterations) self._log_dig_mri_distance('End ') return self @property def _n_scale_params(self): if self._scale_mode is None: n_scale_params = 0 elif self._scale_mode == 'uniform': n_scale_params = 1 else: n_scale_params = 3 return n_scale_params def omit_head_shape_points(self, distance): """Exclude head shape points that are far away from the MRI head. Parameters ---------- distance : float Exclude all points that are further away from the MRI head than this distance (in m.). A value of distance <= 0 excludes nothing. Returns ------- self : Coregistration The modified Coregistration object. """ distance = float(distance) if distance <= 0: return # find the new filter mask = self._orig_hsp_point_distance <= distance n_excluded = np.sum(~mask) logger.info("Coregistration: Excluding %i head shape points with " "distance >= %.3f m.", n_excluded, distance) # set the filter self._extra_points_filter = mask self._update_params(force_update_omitted=True) return self def compute_dig_mri_distances(self): """Compute distance between head shape points and MRI skin surface. Returns ------- dist : array, shape (n_points,) The distance of the head shape points to the MRI skin surface. See Also -------- mne.dig_mri_distances """ # we don't use `dig_mri_distances` here because it should be much # faster to use our already-determined nearest points hsp_points, mri_points, _ = self._setup_icp(0) hsp_points = apply_trans(self._head_mri_t, hsp_points) return np.linalg.norm(mri_points - hsp_points, axis=-1) @property def trans(self): """The head->mri :class:`~mne.transforms.Transform`.""" return Transform('head', 'mri', self._head_mri_t) def reset(self): """Reset all the parameters affecting the coregistration. Returns ------- self : Coregistration The modified Coregistration object. """ self._grow_hair = 0. self.set_rotation(self._default_parameters[:3]) self.set_translation(self._default_parameters[3:6]) self.set_scale(self._default_parameters[6:9]) self._extra_points_filter = None self._update_nearest_calc() return self def _get_fiducials_distance(self): distance = dict() for key in ('lpa', 'nasion', 'rpa'): idx = _map_fid_name_to_idx(name=key) fid = self.fiducials.dig[idx]['r'].reshape(1, -1) transformed_mri = apply_trans(self._mri_trans, fid) transformed_hsp = apply_trans( self._head_mri_t, self._dig_dict[key]) distance[key] = np.linalg.norm( np.ravel(transformed_mri - transformed_hsp)) return np.array(list(distance.values())) * 1e3 def _get_fiducials_distance_str(self): dists = self._get_fiducials_distance() return f"Fiducials: {dists[0]:.1f}, {dists[1]:.1f}, {dists[2]:.1f} mm" def _get_point_distance(self): mri_points = list() hsp_points = list() if self._hsp_weight > 0 and self._has_hsp_data: mri_points.append(self._transformed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_hsp]) hsp_points.append(self._transformed_dig_extra) assert len(mri_points[-1]) == len(hsp_points[-1]) if self._eeg_weight > 0 and self._has_eeg_data: mri_points.append(self._transformed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_eeg]) hsp_points.append(self._transformed_dig_eeg) assert len(mri_points[-1]) == len(hsp_points[-1]) if self._hpi_weight > 0 and self._has_hpi_data: mri_points.append(self._transformed_high_res_mri_points[ self._nearest_transformed_high_res_mri_idx_hpi]) hsp_points.append(self._transformed_dig_hpi) assert len(mri_points[-1]) == len(hsp_points[-1]) if all(len(h) == 0 for h in hsp_points): return None mri_points = np.concatenate(mri_points) hsp_points = np.concatenate(hsp_points) return np.linalg.norm(mri_points - hsp_points, axis=-1) def _get_point_distance_str(self): point_distance = self._get_point_distance() if point_distance is None: return "" dists = 1e3 * point_distance av_dist = np.mean(dists) std_dist = np.std(dists) kinds = [kind for kind, check in (('HSP', self._hsp_weight > 0 and self._has_hsp_data), ('EEG', self._eeg_weight > 0 and self._has_eeg_data), ('HPI', self._hpi_weight > 0 and self._has_hpi_data)) if check] kinds = '+'.join(kinds) return f"{len(dists)} {kinds}: {av_dist:.1f} ± {std_dist:.1f} mm"
[]
[]
[ "SUBJECTS_DIR", "_MNE_FEW_SURFACES" ]
[]
["SUBJECTS_DIR", "_MNE_FEW_SURFACES"]
python
2
0
sessionctx/binloginfo/binloginfo_test.go
// Copyright 2016 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. package binloginfo_test import ( "context" "net" "os" "strconv" "sync" "testing" "time" . "github.com/pingcap/check" "github.com/pingcap/errors" "github.com/pingcap/parser/terror" pumpcli "github.com/pingcap/tidb-tools/tidb-binlog/pump_client" "github.com/pingcap/tidb/ddl" "github.com/pingcap/tidb/domain" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/binloginfo" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/testkit" binlog "github.com/pingcap/tipb/go-binlog" "google.golang.org/grpc" ) func TestT(t *testing.T) { CustomVerboseFlag = true logLevel := os.Getenv("log_level") logutil.InitLogger(&logutil.LogConfig{ Level: logLevel, }) TestingT(t) } type mockBinlogPump struct { mu struct { sync.Mutex payloads [][]byte mockFail bool } } func (p *mockBinlogPump) WriteBinlog(ctx context.Context, req *binlog.WriteBinlogReq) (*binlog.WriteBinlogResp, error) { p.mu.Lock() defer p.mu.Unlock() if p.mu.mockFail { return &binlog.WriteBinlogResp{}, errors.New("mock fail") } p.mu.payloads = append(p.mu.payloads, req.Payload) return &binlog.WriteBinlogResp{}, nil } // PullBinlogs implements PumpServer interface. func (p *mockBinlogPump) PullBinlogs(req *binlog.PullBinlogReq, srv binlog.Pump_PullBinlogsServer) error { return nil } var _ = Suite(&testBinlogSuite{}) type testBinlogSuite struct { store kv.Storage domain *domain.Domain unixFile string serv *grpc.Server pump *mockBinlogPump client *pumpcli.PumpsClient ddl ddl.DDL } const maxRecvMsgSize = 64 * 1024 func (s *testBinlogSuite) SetUpSuite(c *C) { store, err := mockstore.NewMockTikvStore() c.Assert(err, IsNil) s.store = store session.SetSchemaLease(0) s.unixFile = "/tmp/mock-binlog-pump" + strconv.FormatInt(time.Now().UnixNano(), 10) l, err := net.Listen("unix", s.unixFile) c.Assert(err, IsNil) s.serv = grpc.NewServer(grpc.MaxRecvMsgSize(maxRecvMsgSize)) s.pump = new(mockBinlogPump) binlog.RegisterPumpServer(s.serv, s.pump) go s.serv.Serve(l) opt := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("unix", addr, timeout) }) clientCon, err := grpc.Dial(s.unixFile, opt, grpc.WithInsecure()) c.Assert(err, IsNil) c.Assert(clientCon, NotNil) tk := testkit.NewTestKit(c, s.store) s.domain, err = session.BootstrapSession(store) c.Assert(err, IsNil) tk.MustExec("use test") sessionDomain := domain.GetDomain(tk.Se.(sessionctx.Context)) s.ddl = sessionDomain.DDL() s.client = binloginfo.MockPumpsClient(binlog.NewPumpClient(clientCon)) s.ddl.SetBinlogClient(s.client) } func (s *testBinlogSuite) TearDownSuite(c *C) { s.ddl.Stop() s.serv.Stop() os.Remove(s.unixFile) s.store.Close() s.domain.Close() } func (s *testBinlogSuite) TestBinlog(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.Se.GetSessionVars().BinlogClient = s.client pump := s.pump tk.MustExec("drop table if exists local_binlog") ddlQuery := "create table local_binlog (id int primary key, name varchar(10)) shard_row_id_bits=1" binlogDDLQuery := "create table local_binlog (id int primary key, name varchar(10)) /*!90000 shard_row_id_bits=1 */" tk.MustExec(ddlQuery) var matched bool // got matched pre DDL and commit DDL for i := 0; i < 10; i++ { preDDL, commitDDL := getLatestDDLBinlog(c, pump, binlogDDLQuery) if preDDL != nil && commitDDL != nil { if preDDL.DdlJobId == commitDDL.DdlJobId { c.Assert(commitDDL.StartTs, Equals, preDDL.StartTs) c.Assert(commitDDL.CommitTs, Greater, commitDDL.StartTs) matched = true break } } time.Sleep(time.Millisecond * 10) } c.Assert(matched, IsTrue) tk.MustExec("insert local_binlog values (1, 'abc'), (2, 'cde')") prewriteVal := getLatestBinlogPrewriteValue(c, pump) c.Assert(prewriteVal.SchemaVersion, Greater, int64(0)) c.Assert(prewriteVal.Mutations[0].TableId, Greater, int64(0)) expected := [][]types.Datum{ {types.NewIntDatum(1), types.NewStringDatum("abc")}, {types.NewIntDatum(2), types.NewStringDatum("cde")}, } gotRows := mutationRowsToRows(c, prewriteVal.Mutations[0].InsertedRows, 0, 2) c.Assert(gotRows, DeepEquals, expected) tk.MustExec("update local_binlog set name = 'xyz' where id = 2") prewriteVal = getLatestBinlogPrewriteValue(c, pump) oldRow := [][]types.Datum{ {types.NewIntDatum(2), types.NewStringDatum("cde")}, } newRow := [][]types.Datum{ {types.NewIntDatum(2), types.NewStringDatum("xyz")}, } gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 1, 3) c.Assert(gotRows, DeepEquals, oldRow) gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 5, 7) c.Assert(gotRows, DeepEquals, newRow) tk.MustExec("delete from local_binlog where id = 1") prewriteVal = getLatestBinlogPrewriteValue(c, pump) gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].DeletedRows, 1, 3) expected = [][]types.Datum{ {types.NewIntDatum(1), types.NewStringDatum("abc")}, } c.Assert(gotRows, DeepEquals, expected) // Test table primary key is not integer. tk.MustExec("create table local_binlog2 (name varchar(64) primary key, age int)") tk.MustExec("insert local_binlog2 values ('abc', 16), ('def', 18)") tk.MustExec("delete from local_binlog2 where name = 'def'") prewriteVal = getLatestBinlogPrewriteValue(c, pump) c.Assert(prewriteVal.Mutations[0].Sequence[0], Equals, binlog.MutationType_DeleteRow) expected = [][]types.Datum{ {types.NewStringDatum("def"), types.NewIntDatum(18), types.NewIntDatum(-1), types.NewIntDatum(2)}, } gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].DeletedRows, 1, 3, 4, 5) c.Assert(gotRows, DeepEquals, expected) // Test Table don't have primary key. tk.MustExec("create table local_binlog3 (c1 int, c2 int)") tk.MustExec("insert local_binlog3 values (1, 2), (1, 3), (2, 3)") tk.MustExec("update local_binlog3 set c1 = 3 where c1 = 2") prewriteVal = getLatestBinlogPrewriteValue(c, pump) // The encoded update row is [oldColID1, oldColVal1, oldColID2, oldColVal2, -1, handle, // newColID1, newColVal2, newColID2, newColVal2, -1, handle] gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 7, 9) expected = [][]types.Datum{ {types.NewIntDatum(3), types.NewIntDatum(3)}, } c.Assert(gotRows, DeepEquals, expected) expected = [][]types.Datum{ {types.NewIntDatum(-1), types.NewIntDatum(3), types.NewIntDatum(-1), types.NewIntDatum(3)}, } gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 4, 5, 10, 11) c.Assert(gotRows, DeepEquals, expected) tk.MustExec("delete from local_binlog3 where c1 = 3 and c2 = 3") prewriteVal = getLatestBinlogPrewriteValue(c, pump) c.Assert(prewriteVal.Mutations[0].Sequence[0], Equals, binlog.MutationType_DeleteRow) gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].DeletedRows, 1, 3, 4, 5) expected = [][]types.Datum{ {types.NewIntDatum(3), types.NewIntDatum(3), types.NewIntDatum(-1), types.NewIntDatum(3)}, } c.Assert(gotRows, DeepEquals, expected) // Test Mutation Sequence. tk.MustExec("create table local_binlog4 (c1 int primary key, c2 int)") tk.MustExec("insert local_binlog4 values (1, 1), (2, 2), (3, 2)") tk.MustExec("begin") tk.MustExec("delete from local_binlog4 where c1 = 1") tk.MustExec("insert local_binlog4 values (1, 1)") tk.MustExec("update local_binlog4 set c2 = 3 where c1 = 3") tk.MustExec("commit") prewriteVal = getLatestBinlogPrewriteValue(c, pump) c.Assert(prewriteVal.Mutations[0].Sequence, DeepEquals, []binlog.MutationType{ binlog.MutationType_DeleteRow, binlog.MutationType_Insert, binlog.MutationType_Update, }) // Test statement rollback. tk.MustExec("create table local_binlog5 (c1 int primary key)") tk.MustExec("begin") tk.MustExec("insert into local_binlog5 value (1)") // This statement execute fail and should not write binlog. _, err := tk.Exec("insert into local_binlog5 value (4),(3),(1),(2)") c.Assert(err, NotNil) tk.MustExec("commit") prewriteVal = getLatestBinlogPrewriteValue(c, pump) c.Assert(prewriteVal.Mutations[0].Sequence, DeepEquals, []binlog.MutationType{ binlog.MutationType_Insert, }) checkBinlogCount(c, pump) pump.mu.Lock() originBinlogLen := len(pump.mu.payloads) pump.mu.Unlock() tk.MustExec("set @@global.autocommit = 0") tk.MustExec("set @@global.autocommit = 1") pump.mu.Lock() newBinlogLen := len(pump.mu.payloads) pump.mu.Unlock() c.Assert(newBinlogLen, Equals, originBinlogLen) } func (s *testBinlogSuite) TestMaxRecvSize(c *C) { info := &binloginfo.BinlogInfo{ Data: &binlog.Binlog{ Tp: binlog.BinlogType_Prewrite, PrewriteValue: make([]byte, maxRecvMsgSize+1), }, Client: s.client, } err := info.WriteBinlog(1) c.Assert(err, NotNil) c.Assert(terror.ErrCritical.Equal(err), IsFalse, Commentf("%v", err)) } func getLatestBinlogPrewriteValue(c *C, pump *mockBinlogPump) *binlog.PrewriteValue { var bin *binlog.Binlog pump.mu.Lock() for i := len(pump.mu.payloads) - 1; i >= 0; i-- { payload := pump.mu.payloads[i] bin = new(binlog.Binlog) bin.Unmarshal(payload) if bin.Tp == binlog.BinlogType_Prewrite { break } } pump.mu.Unlock() c.Assert(bin, NotNil) preVal := new(binlog.PrewriteValue) preVal.Unmarshal(bin.PrewriteValue) return preVal } func getLatestDDLBinlog(c *C, pump *mockBinlogPump, ddlQuery string) (preDDL, commitDDL *binlog.Binlog) { pump.mu.Lock() for i := len(pump.mu.payloads) - 1; i >= 0; i-- { payload := pump.mu.payloads[i] bin := new(binlog.Binlog) bin.Unmarshal(payload) if bin.Tp == binlog.BinlogType_Commit && bin.DdlJobId > 0 { commitDDL = bin } if bin.Tp == binlog.BinlogType_Prewrite && bin.DdlJobId != 0 { preDDL = bin } if preDDL != nil && commitDDL != nil { break } } pump.mu.Unlock() c.Assert(preDDL.DdlJobId, Greater, int64(0)) c.Assert(preDDL.StartTs, Greater, int64(0)) c.Assert(preDDL.CommitTs, Equals, int64(0)) c.Assert(string(preDDL.DdlQuery), Equals, ddlQuery) return } func checkBinlogCount(c *C, pump *mockBinlogPump) { var bin *binlog.Binlog prewriteCount := 0 ddlCount := 0 pump.mu.Lock() length := len(pump.mu.payloads) for i := length - 1; i >= 0; i-- { payload := pump.mu.payloads[i] bin = new(binlog.Binlog) bin.Unmarshal(payload) if bin.Tp == binlog.BinlogType_Prewrite { if bin.DdlJobId != 0 { ddlCount++ } else { prewriteCount++ } } } pump.mu.Unlock() c.Assert(ddlCount, Greater, 0) match := false for i := 0; i < 10; i++ { pump.mu.Lock() length = len(pump.mu.payloads) pump.mu.Unlock() if (prewriteCount+ddlCount)*2 == length { match = true break } time.Sleep(time.Millisecond * 10) } c.Assert(match, IsTrue) } func mutationRowsToRows(c *C, mutationRows [][]byte, columnValueOffsets ...int) [][]types.Datum { var rows = make([][]types.Datum, 0) for _, mutationRow := range mutationRows { datums, err := codec.Decode(mutationRow, 5) c.Assert(err, IsNil) for i := range datums { if datums[i].Kind() == types.KindBytes { datums[i].SetBytesAsString(datums[i].GetBytes()) } } row := make([]types.Datum, 0, len(columnValueOffsets)) for _, colOff := range columnValueOffsets { row = append(row, datums[colOff]) } rows = append(rows, row) } return rows } // Sometimes this test doesn't clean up fail, let the function name begin with 'Z' // so it runs last and would not disrupt other tests. func (s *testBinlogSuite) TestZIgnoreError(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.Se.GetSessionVars().BinlogClient = s.client tk.MustExec("drop table if exists t") tk.MustExec("create table t (id int)") binloginfo.SetIgnoreError(true) s.pump.mu.Lock() s.pump.mu.mockFail = true s.pump.mu.Unlock() tk.MustExec("insert into t values (1)") tk.MustExec("insert into t values (1)") // Clean up. s.pump.mu.Lock() s.pump.mu.mockFail = false s.pump.mu.Unlock() binloginfo.DisableSkipBinlogFlag() binloginfo.SetIgnoreError(false) } func (s *testBinlogSuite) TestPartitionedTable(c *C) { // This test checks partitioned table write binlog with table ID, rather than partition ID. tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.Se.GetSessionVars().BinlogClient = s.client tk.MustExec("drop table if exists t") tk.MustExec(`create table t (id int) partition by range (id) ( partition p0 values less than (1), partition p1 values less than (4), partition p2 values less than (7), partition p3 values less than (10))`) tids := make([]int64, 0, 10) for i := 0; i < 10; i++ { tk.MustExec("insert into t values (?)", i) prewriteVal := getLatestBinlogPrewriteValue(c, s.pump) tids = append(tids, prewriteVal.Mutations[0].TableId) } c.Assert(len(tids), Equals, 10) for i := 1; i < 10; i++ { c.Assert(tids[i], Equals, tids[0]) } }
[ "\"log_level\"" ]
[]
[ "log_level" ]
[]
["log_level"]
go
1
0
celery/app/base.py
# -*- coding: utf-8 -*- """ celery.app.base ~~~~~~~~~~~~~~~ Application Base Class. :copyright: (c) 2009 - 2012 by Ask Solem. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from __future__ import with_statement import os import warnings import platform as _platform from contextlib import contextmanager from copy import deepcopy from functools import wraps from kombu.clocks import LamportClock from .. import datastructures from .. import platforms from ..exceptions import AlwaysEagerIgnored from ..utils import cached_property, instantiate, lpmerge from .defaults import DEFAULTS, find_deprecated_settings, find import kombu if kombu.VERSION < (2, 0): raise ImportError("Celery requires Kombu version 1.1.0 or higher.") BUGREPORT_INFO = """ platform -> system:%(system)s arch:%(arch)s imp:%(py_i)s software -> celery:%(celery_v)s kombu:%(kombu_v)s py:%(py_v)s settings -> transport:%(transport)s results:%(results)s """ class Settings(datastructures.ConfigurationView): @property def CELERY_RESULT_BACKEND(self): """Resolves deprecated alias ``CELERY_BACKEND``.""" return self.get("CELERY_RESULT_BACKEND") or self.get("CELERY_BACKEND") @property def BROKER_TRANSPORT(self): """Resolves compat aliases :setting:`BROKER_BACKEND` and :setting:`CARROT_BACKEND`.""" return (self.get("BROKER_TRANSPORT") or self.get("BROKER_BACKEND") or self.get("CARROT_BACKEND")) @property def BROKER_BACKEND(self): """Deprecated compat alias to :attr:`BROKER_TRANSPORT`.""" return self.BROKER_TRANSPORT @property def BROKER_HOST(self): return (os.environ.get("CELERY_BROKER_URL") or self.get("BROKER_URL") or self.get("BROKER_HOST")) def find_option(self, name, namespace="celery"): return find(name, namespace) def get_by_parts(self, *parts): return self["_".join(filter(None, parts))] def find_value_for_key(self, name, namespace="celery"): ns, key, _ = self.find_option(name, namespace=namespace) return self.get_by_parts(ns, key) class BaseApp(object): """Base class for apps.""" SYSTEM = platforms.SYSTEM IS_OSX = platforms.IS_OSX IS_WINDOWS = platforms.IS_WINDOWS amqp_cls = "celery.app.amqp:AMQP" backend_cls = None events_cls = "celery.events:Events" loader_cls = "celery.loaders.app:AppLoader" log_cls = "celery.log:Logging" control_cls = "celery.task.control:Control" _pool = None def __init__(self, main=None, loader=None, backend=None, amqp=None, events=None, log=None, control=None, set_as_current=True, accept_magic_kwargs=False, **kwargs): self.main = main self.amqp_cls = amqp or self.amqp_cls self.backend_cls = backend or self.backend_cls self.events_cls = events or self.events_cls self.loader_cls = loader or self.loader_cls self.log_cls = log or self.log_cls self.control_cls = control or self.control_cls self.set_as_current = set_as_current self.accept_magic_kwargs = accept_magic_kwargs self.clock = LamportClock() self.on_init() def on_init(self): """Called at the end of the constructor.""" pass def config_from_object(self, obj, silent=False): """Read configuration from object, where object is either a object, or the name of a module to import. >>> celery.config_from_object("myapp.celeryconfig") >>> from myapp import celeryconfig >>> celery.config_from_object(celeryconfig) """ del(self.conf) return self.loader.config_from_object(obj, silent=silent) def config_from_envvar(self, variable_name, silent=False): """Read configuration from environment variable. The value of the environment variable must be the name of a module to import. >>> os.environ["CELERY_CONFIG_MODULE"] = "myapp.celeryconfig" >>> celery.config_from_envvar("CELERY_CONFIG_MODULE") """ del(self.conf) return self.loader.config_from_envvar(variable_name, silent=silent) def config_from_cmdline(self, argv, namespace="celery"): """Read configuration from argv. The config """ self.conf.update(self.loader.cmdline_config_parser(argv, namespace)) def send_task(self, name, args=None, kwargs=None, countdown=None, eta=None, task_id=None, publisher=None, connection=None, connect_timeout=None, result_cls=None, expires=None, queues=None, **options): """Send task by name. :param name: Name of task to execute (e.g. `"tasks.add"`). :keyword result_cls: Specify custom result class. Default is using :meth:`AsyncResult`. Supports the same arguments as :meth:`~celery.app.task.BaseTask.apply_async`. """ if self.conf.CELERY_ALWAYS_EAGER: warnings.warn(AlwaysEagerIgnored( "CELERY_ALWAYS_EAGER has no effect on send_task")) router = self.amqp.Router(queues) result_cls = result_cls or self.AsyncResult options.setdefault("compression", self.conf.CELERY_MESSAGE_COMPRESSION) options = router.route(options, name, args, kwargs) exchange = options.get("exchange") exchange_type = options.get("exchange_type") with self.default_connection(connection, connect_timeout) as conn: publish = publisher or self.amqp.TaskPublisher(conn, exchange=exchange, exchange_type=exchange_type) try: new_id = publish.delay_task(name, args, kwargs, task_id=task_id, countdown=countdown, eta=eta, expires=expires, **options) finally: publisher or publish.close() return result_cls(new_id) def AsyncResult(self, task_id, backend=None, task_name=None): """Create :class:`celery.result.BaseAsyncResult` instance.""" from ..result import BaseAsyncResult return BaseAsyncResult(task_id, app=self, task_name=task_name, backend=backend or self.backend) def TaskSetResult(self, taskset_id, results, **kwargs): """Create :class:`celery.result.TaskSetResult` instance.""" from ..result import TaskSetResult return TaskSetResult(taskset_id, results, app=self) def broker_connection(self, hostname=None, userid=None, password=None, virtual_host=None, port=None, ssl=None, insist=None, connect_timeout=None, transport=None, transport_options=None, **kwargs): """Establish a connection to the message broker. :keyword hostname: defaults to the :setting:`BROKER_HOST` setting. :keyword userid: defaults to the :setting:`BROKER_USER` setting. :keyword password: defaults to the :setting:`BROKER_PASSWORD` setting. :keyword virtual_host: defaults to the :setting:`BROKER_VHOST` setting. :keyword port: defaults to the :setting:`BROKER_PORT` setting. :keyword ssl: defaults to the :setting:`BROKER_USE_SSL` setting. :keyword insist: defaults to the :setting:`BROKER_INSIST` setting. :keyword connect_timeout: defaults to the :setting:`BROKER_CONNECTION_TIMEOUT` setting. :keyword backend_cls: defaults to the :setting:`BROKER_TRANSPORT` setting. :returns :class:`kombu.connection.BrokerConnection`: """ conf = self.conf return self.amqp.BrokerConnection( hostname or conf.BROKER_HOST, userid or conf.BROKER_USER, password or conf.BROKER_PASSWORD, virtual_host or conf.BROKER_VHOST, port or conf.BROKER_PORT, transport=transport or conf.BROKER_TRANSPORT, insist=self.either("BROKER_INSIST", insist), ssl=self.either("BROKER_USE_SSL", ssl), connect_timeout=self.either( "BROKER_CONNECTION_TIMEOUT", connect_timeout), transport_options=dict(conf.BROKER_TRANSPORT_OPTIONS, **transport_options or {})) @contextmanager def default_connection(self, connection=None, connect_timeout=None): """For use within a with-statement to get a connection from the pool if one is not already provided. :keyword connection: If not provided, then a connection will be acquired from the connection pool. :keyword connect_timeout: *No longer used.* """ if connection: yield connection else: with self.pool.acquire(block=True) as connection: yield connection def with_default_connection(self, fun): """With any function accepting `connection` and `connect_timeout` keyword arguments, establishes a default connection if one is not already passed to it. Any automatically established connection will be closed after the function returns. **Deprecated** Use ``with app.default_connection(connection)`` instead. """ @wraps(fun) def _inner(*args, **kwargs): connection = kwargs.pop("connection", None) with self.default_connection(connection) as c: return fun(*args, **dict(kwargs, connection=c)) return _inner def prepare_config(self, c): """Prepare configuration before it is merged with the defaults.""" find_deprecated_settings(c) return c def now(self): return self.loader.now() def mail_admins(self, subject, body, fail_silently=False): """Send an email to the admins in the :setting:`ADMINS` setting.""" if self.conf.ADMINS: to = [admin_email for _, admin_email in self.conf.ADMINS] return self.loader.mail_admins(subject, body, fail_silently, to=to, sender=self.conf.SERVER_EMAIL, host=self.conf.EMAIL_HOST, port=self.conf.EMAIL_PORT, user=self.conf.EMAIL_HOST_USER, password=self.conf.EMAIL_HOST_PASSWORD, timeout=self.conf.EMAIL_TIMEOUT, use_ssl=self.conf.EMAIL_USE_SSL, use_tls=self.conf.EMAIL_USE_TLS) def select_queues(self, queues=None): if queues: return self.amqp.queues.select_subset(queues, self.conf.CELERY_CREATE_MISSING_QUEUES) def either(self, default_key, *values): """Fallback to the value of a configuration key if none of the `*values` are true.""" for value in values: if value is not None: return value return self.conf.get(default_key) def merge(self, l, r): """Like `dict(a, **b)` except it will keep values from `a` if the value in `b` is :const:`None`.""" return lpmerge(l, r) def _get_backend(self): from ..backends import get_backend_cls return get_backend_cls( self.backend_cls or self.conf.CELERY_RESULT_BACKEND, loader=self.loader)(app=self) def _get_config(self): return Settings({}, [self.prepare_config(self.loader.conf), deepcopy(DEFAULTS)]) def _after_fork(self, obj_): if self._pool: self._pool.force_close_all() self._pool = None def bugreport(self): import celery import kombu return BUGREPORT_INFO % {"system": _platform.system(), "arch": _platform.architecture(), "py_i": platforms.pyimplementation(), "celery_v": celery.__version__, "kombu_v": kombu.__version__, "py_v": _platform.python_version(), "transport": self.conf.BROKER_TRANSPORT, "results": self.conf.CELERY_RESULT_BACKEND} @property def pool(self): if self._pool is None: try: from multiprocessing.util import register_after_fork register_after_fork(self, self._after_fork) except ImportError: pass self._pool = self.broker_connection().Pool( limit=self.conf.BROKER_POOL_LIMIT) return self._pool @cached_property def amqp(self): """Sending/receiving messages. See :class:`~celery.app.amqp.AMQP`.""" return instantiate(self.amqp_cls, app=self) @cached_property def backend(self): """Storing/retrieving task state. See :class:`~celery.backend.base.BaseBackend`.""" return self._get_backend() @cached_property def conf(self): """Current configuration (dict and attribute access).""" return self._get_config() @cached_property def control(self): """Controlling worker nodes. See :class:`~celery.task.control.Control`.""" return instantiate(self.control_cls, app=self) @cached_property def events(self): """Sending/receiving events. See :class:`~celery.events.Events`. """ return instantiate(self.events_cls, app=self) @cached_property def loader(self): """Current loader.""" from ..loaders import get_loader_cls return get_loader_cls(self.loader_cls)(app=self) @cached_property def log(self): """Logging utilities. See :class:`~celery.log.Logging`.""" return instantiate(self.log_cls, app=self) @cached_property def tasks(self): from ..registry import tasks return tasks
[]
[]
[ "CELERY_CONFIG_MODULE", "CELERY_BROKER_URL" ]
[]
["CELERY_CONFIG_MODULE", "CELERY_BROKER_URL"]
python
2
0
apps/eventinghello/src/main/java/com/redhat/developers/LoggerResource.java
package com.redhat.developers; import java.util.Map; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; @Path("/") public class LoggerResource { private static final Logger LOGGER = Logger.getLogger("eventing-hello"); @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/") public String servingEndpoint() { LOGGER.info("ExampleResource's @GET method invoked."); outputEnv(); return "{\"hello\":\"world\"}"; } @POST @Path("/") public Response eventingEndpoint(@Context HttpHeaders httpHeaders, String cloudEventJSON) { LOGGER.info("ExampleResource's @POST method invoked."); outputEnv(); LOGGER.info("ce-id=" + httpHeaders.getHeaderString("ce-id")); LOGGER.info( "ce-source=" + httpHeaders.getHeaderString("ce-source")); LOGGER.info("ce-specversion=" + httpHeaders.getHeaderString("ce-specversion")); LOGGER.info("ce-time=" + httpHeaders.getHeaderString("ce-time")); LOGGER.info("ce-type=" + httpHeaders.getHeaderString("ce-type")); LOGGER.info( "content-type=" + httpHeaders.getHeaderString("content-type")); LOGGER.info("content-length=" + httpHeaders.getHeaderString("content-length")); LOGGER.info("POST:" + cloudEventJSON); return Response.status(Status.OK).entity("{\"hello\":\"world\"}") .build(); } private void outputEnv() { Map<String, String> env = System.getenv(); for (String envName : env.keySet()) { System.out.format("%s=%s%n", envName, env.get(envName)); } } }
[]
[]
[]
[]
[]
java
0
0
dot.py
# -*- coding: UTF-8 -*- import os import sys from subprocess import Popen, PIPE from multiprocessing import Process, Pipe import argparse import json from datetime import datetime from enum import Enum if sys.version_info > (3, 0): from configparser import ConfigParser else: from ConfigParser import ConfigParser class Dotfiles: __XDG_DATA_HOME = os.getenv('XDG_DATA_HOME') or [os.getenv('HOME'), '.local', 'share'] STATE_FILE = os.path.join(*(__XDG_DATA_HOME + ['dotfiles.json'])) def __init__(self): self.dots = {} self.out = Log() def manage(self, args): pargs, print_usage = self.__parse_args(args) if pargs.command: self.__load_state() if pargs.command == 'status': self.status() elif pargs.command == 'add': self.add(pargs.path, pargs.url) elif pargs.command == 'update': self.update() elif pargs.command == 'install': self.install() else: print_usage() def add(self, path, url): rpath = Dot.rpath(path) if os.path.isfile(rpath): self.out.error(path + ' is regular file') exit(1) for dot in self.dots.values(): if dot.path == rpath: self.out.error(path + ' already added') exit(1) if url: if os.path.isdir(rpath): self.out.error(path + ' already exists, can not clone there') exit(1) else: if os.path.isdir(rpath): if Dot.isrepo(rpath): url = Dot.repourl(rpath) else: self.out.error(path + ' is not a valid repo') exit(1) else: self.out.error(path + ' does not exist') exit(1) dot = Dot(rpath, url) dot.getrevision() name = os.path.basename(rpath) self.dots[name] = dot self.__update_state() self.out.info('added ' + name) def status(self): self.out.info('repos status:') self.out.info('') for name, dot in AsyncDo(self.dots, Dot.check): self.out.info(name + "\t" + dot.state.name + "\t" + dot.path) self.out.info(" " + dot.url + " " + dot.revision) def update(self): self.out.info('pulling from remotes...') self.out.info('') for _ in AsyncDo(self.dots, Dot.update): pass self.__update_state() self.status() def install(self, dot_name=None): if dot_name and dot_name in self.dots: self.dots[dot_name].install() return cwd = os.getcwd() for name, dot in self.dots.items(): if dot.path == cwd: dot_name = name break if dot_name: self.dots[dot_name].install() return for dot in self.dots.values(): dot.install() self.__update_state() def __parse_args(self, args): ap = argparse.ArgumentParser() sp = ap.add_subparsers(title='commands', dest='command', metavar=None) sp.add_parser('status', help='list known rc repos and their status') p_add = sp.add_parser('add', help='add rc repo') p_add.add_argument('path', type=str, help='rc repo path') p_add.add_argument('url', type=str, help='rc repo (git) url', nargs='?', default=None) sp.add_parser('update', help='update dot files repos') p_install = sp.add_parser('install', help='install files') p_install.add_argument('repo', type=str, help='repo name', nargs='?', default=None) return ap.parse_args(args), ap.print_usage def __load_state(self): state = {} if os.access(self.STATE_FILE, os.R_OK): with open(self.STATE_FILE, 'r') as f: state = json.loads(f.read()) for repo, details in state.items(): self.dots[repo] = Dot.from_json(details) def __update_state(self): state = {} for name, dot in self.dots.items(): state[name] = dot.as_json() data = json.dumps(state, indent=2, separators=(',', ': '), sort_keys=True) with open(self.STATE_FILE, 'w') as f: f.write(data) DotState = Enum('DotState', 'UNKNOWN EXISTS BLANK') class Dot: @staticmethod def isrepo(rpath): return os.path.isdir(os.path.join(rpath, '.git')) @staticmethod def repourl(rpath): cmd = Cmd(Git.url(rpath)).invoke() return cmd.stdout.strip() @staticmethod def rpath(path): return os.path.abspath(os.path.expanduser(os.path.normpath(path))) @staticmethod def from_json(json): return Dot( url = json.get('url', None), path = json['path'], revision = json.get('revision', None), updated_on = json.get('updated_on', None) and datetime.strptime(json['updated_on'], '%Y-%m-%dT%H:%M:%S.%f'), installed = json.get('installed', {}), errors = json.get('errors', {}), ) def __init__(self, path, url, revision=None, updated_on=None, installed={}, errors={}): self.state = DotState.UNKNOWN self.url = url self.path = path self.revision = revision self.updated_on = updated_on self.installed = {'links': installed.get('links', {}), 'copies': installed.get('copies', {})} self.vcs = Git(self.path) self.errors = {'install': errors.get('install', [])} def as_json(self): return { 'url': self.url, 'path': self.path, 'revision': self.revision, 'updated_on': self.updated_on and self.updated_on.isoformat(), 'installed': self.installed, 'errors': self.errors, } def check(self): self.state = DotState.BLANK if self.vcs.exists() and os.system(' '.join(self.vcs.status())) == 0: # FIXME hardocde self.state = DotState.EXISTS def update(self): self.check() success = None if self.state == DotState.BLANK: if not os.path.exists(self.path): os.mkdir(self.path) success = self.__action(self.vcs.clone(self.url)) else: success = self.__action(self.vcs.pull()) if success: self.getrevision() self.state = DotState.EXISTS def getrevision(self): success, out = self.__action(self.vcs.revision()) if success: self.revision = out.strip() def install(self): self.errors['install'] = [] self.check() if self.state != DotState.EXISTS: return dotfiles_ini = os.path.join(self.path, 'dotfiles.ini') if not os.path.exists(dotfiles_ini): return config = ConfigParser() config.read(dotfiles_ini) # TODO: remove all previously installed symlinks/files self.__make_symlinks(config) def __make_symlinks(self, config): LINKS = 'links' if LINKS not in config.sections(): self.errors['install'].append('there is no links section in dotfiles.ini') return for src, dest in config.items(LINKS): dest = Dot.rpath(dest) src = os.path.join(self.path, src) if os.path.exists(dest): if os.path.islink(dest): if os.readlink(dest) == src: self.installed['links'][src] = dest else: self.errors['install'].append(dest + ' already exists and is symlink to somewhere else') else: self.errors['install'].append(dest + ' already exists and is regular file') else: dest_dir = os.path.dirname(dest) if os.path.isdir(dest_dir): os.symlink(src, dest) self.installed['links'][src] = dest else: try: os.makedirs(dest_dir) os.symlink(src, dest) self.installed['links'][src] = dest except os.error as e: self.errors['install'].append('can not create directory for ' + dest + ' : ' + e) def __action(self, command): cmd = Cmd(command).invoke() if not cmd.success: self.last_error = cmd.stderr self.updated_on = datetime.utcnow() return cmd.success, cmd.stdout class Cmd: def __init__(self, cmd): self.cmd = cmd self.stdout = None self.stderr = None self.exitcode = None def invoke(self): process = Popen( self.cmd, stdout=PIPE, stderr=PIPE ) stdout, stderr = process.communicate() self.stdout, self.stderr = self.__str(stdout), self.__str(stderr) self.exitcode = process.returncode return self def success(self): return self.exitcode == 0 def __str(self, maybe_bytes): if type(maybe_bytes) is bytes: return maybe_bytes.decode('utf-8') return maybe_bytes class AsyncDo: def __init__(self, items, func): self.items = items self.func = func self.workers = [] def __iter__(self): self.__start() self.i = iter(self.items) return self def __next__(self): n = next(self.i) return n, self.items[n] next = __next__ def __start(self): if self.workers: return for name in self.items: p_conn, c_conn = Pipe() worker = Process(target=self.__func, args=(c_conn, self.items[name],)) self.workers.append((worker, p_conn, name)) worker.start() for worker, _, _ in self.workers: worker.join() for _, conn, name in self.workers: self.items[name] = conn.recv() def __func(self, conn, data): self.func(data) conn.send(data) conn.close() class Git: __CMD = ['git'] @staticmethod def url(rpath): return Git.__CMD + ['--git-dir={}/.git'.format(rpath), 'config', 'remote.origin.url'] def __init__(self, path): self.path = path def clone(self, url): return self.__CMD + ['clone', '--quiet', '--recursive', '--', url, self.path] def exists(self): return os.access(os.path.join(self.path, '.git'), os.R_OK) def pull(self): return self.__base() + ['pull'] def push(self): return self.__base() + ['push'] def status(self): return self.__base() + ['status', '--porcelain'] def revision(self): return self.__base() + ['rev-parse', 'HEAD'] def __base(self): return self.__CMD + self.__path_settings() def __path_settings(self): return [t.format(self.path) for t in ['--git-dir={}/.git', '--work-tree={}']] class Log: def info(self, text): sys.stdout.write(". "+text+"\n") def error(self, text): sys.stderr.write(". "+text+"\n") if __name__ == '__main__': Dotfiles().manage(sys.argv[1:])
[]
[]
[ "HOME", "XDG_DATA_HOME" ]
[]
["HOME", "XDG_DATA_HOME"]
python
2
0
tfkit/train.py
import argparse import sys import os from datetime import timedelta import time from itertools import zip_longest import torch from torch.utils import data from tqdm.auto import tqdm from transformers import get_linear_schedule_with_warmup import nlp2 import tfkit import tfkit.utility.tok as tok from tfkit.utility.dataset import get_dataset, dataloader_collate from tfkit.utility.logger import Logger from tfkit.utility.model import load_model_class, save_model, load_pretrained_tokenizer, load_pretrained_model import logging from accelerate import Accelerator transformers_logger = logging.getLogger('transformers') transformers_logger.setLevel(logging.CRITICAL) os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ["OMP_NUM_THREADS"] = "1" def parse_train_args(args): parser = argparse.ArgumentParser() exceed_mode = nlp2.function_get_all_arg_with_value(tok.handle_exceed)['mode'] parser.add_argument("--batch", type=int, default=20, help="batch size, default 20") parser.add_argument("--lr", type=float, nargs='+', default=[5e-5], help="learning rate, default 5e-5") parser.add_argument("--epoch", type=int, default=10, help="epoch, default 10") parser.add_argument("--maxlen", type=int, default=0, help="max tokenized sequence length, default model max len") parser.add_argument("--handle_exceed", choices=exceed_mode, help='select ways to handle input exceed max length') parser.add_argument("--savedir", type=str, default="checkpoints/", help="model saving dir, default /checkpoints") parser.add_argument("--add_tokens_freq", type=int, default=0, help="auto add freq >= x UNK token to word table") parser.add_argument("--add_tokens_file", type=str, help="add token from a list file") parser.add_argument("--train", type=str, nargs='+', required=True, help="train dataset path") parser.add_argument("--test", type=str, nargs='+', required=True, help="test dataset path") parser.add_argument("--no_eval", action='store_true', help="not running evaluation") parser.add_argument("--model", type=str, required=True, nargs='+', choices=tfkit.utility.model.list_all_model(), help="model task") parser.add_argument("--tag", type=str, nargs='+', help="tag to identity task in multi-task") parser.add_argument("--config", type=str, default='bert-base-multilingual-cased', required=True, help='distilbert-base-multilingual-cased|voidful/albert_chinese_small') parser.add_argument("--seed", type=int, default=609, help="random seed, default 609") parser.add_argument("--worker", type=int, default=8, help="number of worker on pre-processing, default 8") parser.add_argument("--grad_accum", type=int, default=1, help="gradient accumulation, default 1") parser.add_argument('--tensorboard', action='store_true', help='Turn on tensorboard graphing') parser.add_argument('--wandb', action='store_true', help='Turn on wandb with project name') parser.add_argument("--resume", help='resume training') parser.add_argument("--cache", action='store_true', help='cache training data') parser.add_argument("--panel", action='store_true', help="enable panel to input argument") input_arg, model_arg = parser.parse_known_args(args) input_arg = {k: v for k, v in vars(input_arg).items() if v is not None} model_arg = {k.replace("--", ""): v for k, v in zip(model_arg[:-1:2], model_arg[1::2])} return input_arg, model_arg def optimizer(model, lr, total_step): optim = torch.optim.AdamW(model.parameters(), lr=lr) scheduler = get_linear_schedule_with_warmup(optim, num_warmup_steps=int(total_step * 0.05), num_training_steps=total_step) return [optim, scheduler] def model_train(models_list, dataloaders, models_tag, input_arg, epoch, logger, accelerator): optims_schs = [] models = [] total_iter = 0 t_loss = 0 end = False total_iter_length = len(dataloaders[0]) pbar = tqdm(total=total_iter_length) data_iters = [] for i, (model, dataloader) in enumerate(zip(models_list, dataloaders)): if not accelerator.state.backend: model = torch.nn.DataParallel(model) model.train() optim = optimizer(model, input_arg.get('lr')[i] if i < len(input_arg.get('lr')) else input_arg.get('lr')[0], total_iter_length) model, optim, dataloader = accelerator.prepare(model, optim, dataloader) optims_schs.append(optim) models.append(model) data_iters.append(iter(dataloader)) while not end: for (model, optim_sch, mtag, train_batch) in zip(models, optims_schs, models_tag, data_iters): optim = optim_sch[0] scheduler = optim_sch[1] train_batch = next(train_batch, None) if train_batch is not None: loss = model(train_batch) loss = loss / input_arg.get('grad_accum') accelerator.backward(loss.mean()) if (total_iter + 1) % input_arg.get('grad_accum') == 0: optim.step() model.zero_grad() scheduler.step() t_loss += loss.mean().detach() logger.write_metric("loss/step", loss.mean().detach(), epoch) if total_iter % 100 == 0 and total_iter != 0: # monitoring logger.write_log( f"epoch: {epoch}, tag: {mtag}, model: {model.__class__.__name__}, step: {total_iter}, loss: {t_loss / total_iter if total_iter > 0 else 0}, total:{total_iter_length}") else: end = True pbar.update(1) total_iter += 1 pbar.close() logger.write_log( f"epoch: {epoch}, step: {total_iter}, loss: {t_loss / total_iter if total_iter > 0 else 0}, total: {total_iter}") return t_loss / total_iter def model_eval(models, dataloaders, fname, input_arg, epoch, logger, accelerator): t_loss = 0 t_length = 0 for m in models: m.eval() with torch.no_grad(): total_iter_length = len(dataloaders[0]) iters = [iter(accelerator.prepare(ds)) for ds in dataloaders] end = False pbar = tqdm(total=total_iter_length) while not end: for model, batch in zip(models, iters): test_batch = next(batch, None) if test_batch is not None: loss = model(test_batch) loss = loss / input_arg.get('grad_accum') t_loss += loss.mean().detach() t_length += 1 pbar.update(1) else: end = True pbar.close() avg_t_loss = t_loss / t_length if t_length > 0 else 0 logger.write_log(f"model: {fname}, Total Loss: {avg_t_loss}") logger.write_metric("eval_loss/step", avg_t_loss, epoch) return avg_t_loss def load_model_and_datas(tokenizer, pretrained, accelerator, model_arg, input_arg): models = [] train_dataset = [] test_dataset = [] train_ds_maxlen = 0 test_ds_maxlen = 0 for model_class_name, train_file, test_file in zip_longest(input_arg.get('model'), input_arg.get('train'), input_arg.get('test'), fillvalue=""): # get model class model_class = load_model_class(model_class_name) # load dataset ds_parameter = {**model_arg, **input_arg} train_ds = get_dataset(train_file, model_class, tokenizer, ds_parameter) test_ds = get_dataset(test_file, model_class, tokenizer, ds_parameter) # load model model = model_class.Model(tokenizer=tokenizer, pretrained=pretrained, tasks_detail=train_ds.task, maxlen=input_arg.get('maxlen'), **model_arg) # append to max len train_ds_maxlen = train_ds.__len__() if train_ds.__len__() > train_ds_maxlen else train_ds_maxlen test_ds_maxlen = test_ds.__len__() if test_ds.__len__() > test_ds_maxlen else test_ds_maxlen train_dataset.append(train_ds) test_dataset.append(test_ds) models.append(model) return models, train_dataset, test_dataset, train_ds_maxlen, test_ds_maxlen def main(arg=None): input_arg, model_arg = parse_train_args(sys.argv[1:]) if arg is None else parse_train_args(arg) accelerator = Accelerator() nlp2.get_dir_with_notexist_create(input_arg.get('savedir')) logger = Logger(savedir=input_arg.get('savedir'), tensorboard=input_arg.get('tensorboard', False), wandb=input_arg.get('wandb', False), print_fn=accelerator.print) logger.write_log("Accelerator") logger.write_log("=======================") logger.write_log(accelerator.state) logger.write_log("=======================") nlp2.set_seed(input_arg.get('seed')) tokenizer = load_pretrained_tokenizer(input_arg.get('config')) pretrained = load_pretrained_model(input_arg.get('config'), input_arg.get('model')) if input_arg.get('maxlen') == 0: input_arg.update({'maxlen': pretrained.config.max_position_embeddings}) # handling add tokens add_tokens = None if input_arg.get('add_tokens_freq', None): logger.write_log("Calculating Unknown Token") add_tokens = tok.get_freqK_unk_token(tokenizer, input_arg.get('train') + input_arg.get('test'), input_arg.get('add_tokens_freq')) if input_arg.get('add_tokens_file', None): logger.write_log("Add token from file") add_tokens = nlp2.read_files_into_lines(input_arg.get('add_tokens_file')) if add_tokens: pretrained, tokenizer = tfkit.utility.model.add_tokens_to_pretrain(pretrained, tokenizer, add_tokens) # load model and data models_tag = input_arg.get('tag') if input_arg.get('tag', None) is not None else [m.lower() + "_" + str(ind) for ind, m in enumerate(input_arg.get('model'))] models, train_dataset, test_dataset, train_ds_maxlen, test_ds_maxlen = load_model_and_datas(tokenizer, pretrained, accelerator, model_arg, input_arg) # balance sample for multi-task for ds in train_dataset: ds.increase_with_sampling(train_ds_maxlen) for ds in test_dataset: ds.increase_with_sampling(test_ds_maxlen) logger.write_config(input_arg) logger.write_log("TRAIN PARAMETER") logger.write_log("=======================") [logger.write_log(str(key) + " : " + str(value)) for key, value in input_arg.items()] logger.write_log("=======================") train_dataloaders = [data.DataLoader(dataset=ds, batch_size=input_arg.get('batch'), shuffle=True, pin_memory=False, collate_fn=dataloader_collate, num_workers=input_arg.get('worker')) for ds in train_dataset] test_dataloaders = [data.DataLoader(dataset=ds, batch_size=input_arg.get('batch'), shuffle=False, pin_memory=False, collate_fn=dataloader_collate, num_workers=input_arg.get('worker')) for ds in test_dataset] # loading model back start_epoch = 1 if input_arg.get('resume'): logger.write_log("Loading back:", input_arg.get('resume')) package = torch.load(input_arg.get('resume')) if 'model_state_dict' in package: models[0].load_state_dict(package['model_state_dict']) else: if len(models) != len(package['models']) and not input_arg.get('tag'): raise Exception( f"resuming from multi-task model, you should specific which task to use with --tag, from {package['tags']}") elif len(models) != len(package['models']): tags = input_arg.get('tag') else: tags = package['tags'] for ind, model_tag in enumerate(tags): tag_ind = package['tags'].index(model_tag) models[ind].load_state_dict(package['models'][tag_ind]) start_epoch = int(package.get('epoch', 1)) + 1 # train/eval loop logger.write_log("training batch : " + str(input_arg.get('batch') * input_arg.get('grad_accum'))) for epoch in range(start_epoch, start_epoch + input_arg.get('epoch')): start_time = time.time() fname = os.path.join(input_arg.get('savedir'), str(epoch)) logger.write_log(f"=========train at epoch={epoch}=========") try: train_avg_loss = model_train(models, train_dataloaders, models_tag, input_arg, epoch, logger, accelerator) logger.write_metric("train_loss/epoch", train_avg_loss, epoch) except KeyboardInterrupt: save_model(models, input_arg, models_tag, epoch, fname + "_interrupt", logger, add_tokens=add_tokens, accelerator=accelerator) pass logger.write_log(f"=========save at epoch={epoch}=========") save_model(models, input_arg, models_tag, epoch, fname, logger, add_tokens=add_tokens, accelerator=accelerator) if input_arg.get('no_eval') is False: logger.write_log(f"=========eval at epoch={epoch}=========") eval_avg_loss = model_eval(models, test_dataloaders, fname, input_arg, epoch, logger, accelerator) logger.write_metric("eval_loss/epoch", eval_avg_loss, epoch) logger.write_log(f"=== Epoch execution time: {timedelta(seconds=(time.time() - start_time))} ===") if __name__ == "__main__": main()
[]
[]
[ "OMP_NUM_THREADS", "TOKENIZERS_PARALLELISM" ]
[]
["OMP_NUM_THREADS", "TOKENIZERS_PARALLELISM"]
python
2
0
server/main.go
package server import ( "cngrok/conn" log "cngrok/log" "cngrok/msg" "cngrok/util" "crypto/tls" "math/rand" "os" "runtime/debug" "time" ) const ( registryCacheSize uint64 = 1024 * 1024 // 1 MB connReadTimeout time.Duration = 10 * time.Second ) // GLOBALS var ( tunnelRegistry *TunnelRegistry controlRegistry *ControlRegistry // XXX: kill these global variables - they're only used in tunnel.go for constructing forwarding URLs opts *Options listeners map[string]*conn.Listener ) func NewProxy(pxyConn conn.Conn, regPxy *msg.RegProxy) { // fail gracefully if the proxy connection fails to register defer func() { if r := recover(); r != nil { pxyConn.Warn("失败,出现错误: %v", r) pxyConn.Close() } }() // set logging prefix pxyConn.SetType("pxy") // look up the control connection for this proxy pxyConn.Info("正在注册新代理 %s", regPxy.ClientId) ctl := controlRegistry.Get(regPxy.ClientId) if ctl == nil { panic("找不到客户端标识符: " + regPxy.ClientId) } ctl.RegisterProxy(pxyConn) } // Listen for incoming control and proxy connections // We listen for incoming control and proxy connections on the same port // for ease of deployment. The hope is that by running on port 443, using // TLS and running all connections over the same port, we can bust through // restrictive firewalls. func tunnelListener(addr string, tlsConfig *tls.Config) { // listen for incoming connections listener, err := conn.Listen(addr, "tun", tlsConfig) if err != nil { panic(err) } log.Info("监听控制和代理连接端口 %s", listener.Addr.String()) for c := range listener.Conns { go func(tunnelConn conn.Conn) { // don't crash on panics defer func() { if r := recover(); r != nil { tunnelConn.Info("隧道侦听失败,出现错误 %v: %s", r, debug.Stack()) } }() tunnelConn.SetReadDeadline(time.Now().Add(connReadTimeout)) var rawMsg msg.Message if rawMsg, err = msg.ReadMsg(tunnelConn); err != nil { tunnelConn.Warn("无法读取信息: %v", err) tunnelConn.Close() return } // don't timeout after the initial read, tunnel heartbeating will kill // dead connections tunnelConn.SetReadDeadline(time.Time{}) switch m := rawMsg.(type) { case *msg.Auth: NewControl(tunnelConn, m) case *msg.RegProxy: NewProxy(tunnelConn, m) default: tunnelConn.Close() } }(c) } } func Main() { // parse options opts = parseArgs() // init logging log.LogTo(opts.logto, opts.loglevel) // seed random number generator seed, err := util.RandomSeed() if err != nil { panic(err) } rand.Seed(seed) // init tunnel/control registry registryCacheFile := os.Getenv("REGISTRY_CACHE_FILE") tunnelRegistry = NewTunnelRegistry(registryCacheSize, registryCacheFile) controlRegistry = NewControlRegistry() // start listeners listeners = make(map[string]*conn.Listener) // load tls configuration tlsConfig, err := LoadTLSConfig(opts.tlsCrt, opts.tlsKey) if err != nil { panic(err) } // listen for http if opts.httpAddr != "" { listeners["http"] = startHttpListener(opts.httpAddr, nil) } // listen for https if opts.httpsAddr != "" { listeners["https"] = startHttpListener(opts.httpsAddr, tlsConfig) } // ngrok clients tunnelListener(opts.tunnelAddr, tlsConfig) }
[ "\"REGISTRY_CACHE_FILE\"" ]
[]
[ "REGISTRY_CACHE_FILE" ]
[]
["REGISTRY_CACHE_FILE"]
go
1
0
prediction/sklearn/structured/custom_routines/prediction/predict.py
#!/usr/bin/env python # Copyright 2019 Google LLC # # 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. # ============================================================================== from google.api_core.client_options import ClientOptions import os import logging import googleapiclient.discovery logging.basicConfig() # In this sample, we will pass all available features in order. instances = [ [0.2, 660, 1175, 8, 10, 7, 8, 33, 17031081402, 17031330100, 41.892, -87.613, 41.859, -87.617, 'Credit Card', 'Taxi Affiliation Services'], [1.0, 300, 545, 9, 22,4 ,32, 8, 17031320100, 17031081500, 41.885, -87.621, 41.893, -87.626, 'Cash', 'Northwest Management LLC'], [1.1, 300, 565, 3, 2, 1, 28, 32, 17031833000, 17031839100, 41.885, -87.657, 41.881, -87.633, 'Credit Card', 'Taxi Affiliation Services'] ] PROJECT_ID = os.getenv('PROJECT_ID') MODEL_NAME = os.getenv('MODEL_NAME') MODEL_VERSION = os.getenv('MODEL_VERSION') REGION = os.getenv('REGION') logging.info('PROJECT_ID: %s', PROJECT_ID) logging.info('MODEL_NAME: %s', MODEL_NAME) logging.info('MODEL_VERSION: %s', MODEL_VERSION) logging.info('REGION: %s', REGION) prefix = "{}-ml".format(REGION) if REGION else "ml" api_endpoint = "https://{}.googleapis.com".format(prefix) client_options = ClientOptions(api_endpoint=api_endpoint) service = googleapiclient.discovery.build('ml', 'v1') name = 'projects/{}/models/{}/versions/{}'.format(PROJECT_ID, MODEL_NAME, MODEL_VERSION) response = service.projects().predict( name=name, body={'instances': instances} ).execute() if 'error' in response: logging.error(response['error']) else: print(response['predictions'])
[]
[]
[ "MODEL_NAME", "REGION", "PROJECT_ID", "MODEL_VERSION" ]
[]
["MODEL_NAME", "REGION", "PROJECT_ID", "MODEL_VERSION"]
python
4
0
regbot/scripts/delete_channel_messages.py
"""Delete all unpinned posts""" from discord import Client import os client = Client() TOKEN = os.getenv("DISCORD_TOKEN") CHANNEL_IDS = [ 764408838626607115, ] @client.event async def on_ready(): print(f"logged in as {client.user}") for channel_id in CHANNEL_IDS: channel = client.get_channel(channel_id) assert channel is not None, "Need valid channel" print(f"Deleting messages for {channel.name}") await channel.purge(limit=1000) print("Messages deleted.") await client.close() client.run(TOKEN)
[]
[]
[ "DISCORD_TOKEN" ]
[]
["DISCORD_TOKEN"]
python
1
0
internal/setup/job.go
/* Copyright 2020 GramLabs, Inc. 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 setup import ( "encoding/base64" "fmt" "os" "path" optimizev1beta2 "github.com/thestormforge/optimize-controller/v2/api/v1beta2" "github.com/thestormforge/optimize-controller/v2/internal/template" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "sigs.k8s.io/yaml" ) // This is overwritten during builds to point to the actual image var ( // Image is the name of the setuptools image to use Image = "setuptools:latest" // ImagePullPolicy controls when the default image should be pulled ImagePullPolicy = string(corev1.PullIfNotPresent) ) // NOTE: The default image names use a ":latest" tag which causes the default pull policy to switch // from "IfNotPresent" to "Always". However, the default image names are not associated with a public // repository and cannot actually be pulled (they only work if they are present). The exact opposite // problem occurs with the production image names: we want those to have a policy of "Always" to address // the potential of a floating tag but they will default to "IfNotPresent" because they do not use // ":latest". To address this we always explicitly specify the pull policy corresponding to the image. // Finally, when using digests, the default of "IfNotPresent" is acceptable as it is unambiguous. // NewJob returns a new setup job for either create or delete func NewJob(t *optimizev1beta2.Trial, mode string) (*batchv1.Job, error) { job := &batchv1.Job{} job.Namespace = t.Namespace job.Name = fmt.Sprintf("%s-%s", t.Name, mode) job.Labels = map[string]string{ optimizev1beta2.LabelExperiment: t.ExperimentNamespacedName().Name, optimizev1beta2.LabelTrial: t.Name, optimizev1beta2.LabelTrialRole: "trialSetup", } job.Spec.BackoffLimit = new(int32) job.Spec.Template.Labels = map[string]string{ optimizev1beta2.LabelExperiment: t.ExperimentNamespacedName().Name, optimizev1beta2.LabelTrial: t.Name, optimizev1beta2.LabelTrialRole: "trialSetup", } job.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever job.Spec.Template.Spec.ServiceAccountName = t.Spec.SetupServiceAccountName // Collect the volumes we need for the pod var volumes = make(map[string]*corev1.Volume) for _, v := range t.Spec.SetupVolumes { volumes[v.Name] = &v } // We need to run as a non-root user that has the same UID and GID id := int64(1000) allowPrivilegeEscalation := false runAsNonRoot := true job.Spec.Template.Spec.SecurityContext = &corev1.PodSecurityContext{ RunAsNonRoot: &runAsNonRoot, } // Create containers for each of the setup tasks for _, task := range t.Spec.SetupTasks { if (mode == ModeCreate && task.SkipCreate) || (mode == ModeDelete && task.SkipDelete) { continue } c := corev1.Container{ Name: fmt.Sprintf("%s-%s", job.Name, task.Name), Image: task.Image, Args: task.Args, Env: []corev1.EnvVar{ {Name: "NAMESPACE", Value: t.Namespace}, {Name: "NAME", Value: task.Name}, {Name: "TRIAL", Value: t.Name}, {Name: "MODE", Value: mode}, }, SecurityContext: &corev1.SecurityContext{ RunAsUser: &id, RunAsGroup: &id, AllowPrivilegeEscalation: &allowPrivilegeEscalation, }, } if len(c.Args) == 0 { c.Args = []string{mode} } if len(task.Command) > 0 && c.Image != "" { c.Command = task.Command } // Check the environment for a default setup tools image name if c.Image == "" { c.Image = os.Getenv("DEFAULT_SETUP_IMAGE") c.ImagePullPolicy = corev1.PullPolicy(os.Getenv("DEFAULT_SETUP_IMAGE_PULL_POLICY")) } // Make sure we have an image if c.Image == "" { c.Image = Image c.ImagePullPolicy = corev1.PullPolicy(ImagePullPolicy) } // Add the trial assignments to the environment c.Env = AppendAssignmentEnv(t, c.Env) // Add the configured volume mounts c.VolumeMounts = append(c.VolumeMounts, task.VolumeMounts...) // For Helm installs, serialize a Konjure configuration helmConfig := newHelmGeneratorConfig(&task) if helmConfig != nil { te := template.New() // Helm Values for _, hv := range task.HelmValues { hgv := helmGeneratorValue{ Name: hv.Name, ForceString: hv.ForceString, } if hv.ValueFrom != nil { // Evaluate the external value source switch { case hv.ValueFrom.ParameterRef != nil: v, ok := t.GetAssignment(hv.ValueFrom.ParameterRef.Name) if !ok { return nil, fmt.Errorf("invalid parameter reference '%s' for Helm value '%s'", hv.ValueFrom.ParameterRef.Name, hv.Name) } if v.Type == intstr.String { hgv.Value = v.StrVal } else { hgv.Value = v.IntVal } default: return nil, fmt.Errorf("unknown source for Helm value '%s'", hv.Name) } } else { // If there is no external source, evaluate the value field as a template v, err := te.RenderHelmValue(&hv, t) if err != nil { return nil, err } hgv.Value = v } helmConfig.Values = append(helmConfig.Values, hgv) } // Helm Values From for _, hvf := range task.HelmValuesFrom { if hvf.ConfigMap != nil { hgv := helmGeneratorValue{ File: path.Join("/workspace", "helm-values", hvf.ConfigMap.Name, "*values.yaml"), } vm := corev1.VolumeMount{ Name: hvf.ConfigMap.Name, MountPath: path.Dir(hgv.File), ReadOnly: true, } if _, ok := volumes[vm.Name]; !ok { vs := corev1.VolumeSource{ ConfigMap: &corev1.ConfigMapVolumeSource{ LocalObjectReference: corev1.LocalObjectReference{Name: hvf.ConfigMap.Name}, }, } volumes[vm.Name] = &corev1.Volume{Name: vm.Name, VolumeSource: vs} } c.VolumeMounts = append(c.VolumeMounts, vm) helmConfig.Values = append(helmConfig.Values, hgv) } } if task.HelmRepository != "" { helmConfig.Repo = task.HelmRepository } // Record the base64 encoded YAML representation in the environment b, err := yaml.Marshal(helmConfig) if err != nil { return nil, err } c.Env = append(c.Env, corev1.EnvVar{Name: "HELM_CONFIG", Value: base64.StdEncoding.EncodeToString(b)}) } job.Spec.Template.Spec.Containers = append(job.Spec.Template.Spec.Containers, c) } // Add all of the volumes we collected to the pod for _, v := range volumes { job.Spec.Template.Spec.Volumes = append(job.Spec.Template.Spec.Volumes, *v) } return job, nil } type helmGeneratorValue struct { File string `json:"file,omitempty"` Name string `json:"name,omitempty"` Value interface{} `json:"value,omitempty"` ForceString bool `json:"forceString,omitempty"` } type helmGeneratorConfig struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` ReleaseName string `json:"releaseName"` Chart string `json:"chart"` Version string `json:"version"` Repo string `json:"repo,omitempty"` Values []helmGeneratorValue `json:"values"` } func newHelmGeneratorConfig(task *optimizev1beta2.SetupTask) *helmGeneratorConfig { if task.HelmChart == "" { return nil } cfg := &helmGeneratorConfig{ ReleaseName: task.Name, Chart: task.HelmChart, Version: task.HelmChartVersion, } cfg.APIVersion = "konjure.carbonrelay.com/v1beta1" cfg.Kind = "HelmGenerator" cfg.Name = task.Name return cfg }
[ "\"DEFAULT_SETUP_IMAGE\"", "\"DEFAULT_SETUP_IMAGE_PULL_POLICY\"" ]
[]
[ "DEFAULT_SETUP_IMAGE_PULL_POLICY", "DEFAULT_SETUP_IMAGE" ]
[]
["DEFAULT_SETUP_IMAGE_PULL_POLICY", "DEFAULT_SETUP_IMAGE"]
go
2
0
modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
/* * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) * Copyright 2018 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openapitools.codegen.languages; import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.mustache.*; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; import static org.openapitools.codegen.utils.StringUtils.camelize; public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig { protected boolean optionalAssemblyInfoFlag = true; protected boolean optionalProjectFileFlag = true; protected boolean optionalMethodArgumentFlag = true; protected boolean useDateTimeOffsetFlag = false; protected boolean useCollection = false; protected boolean returnICollection = false; protected boolean netCoreProjectFileFlag = false; protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name(); protected String licenseUrl = "http://localhost"; protected String licenseName = "NoLicense"; protected String packageVersion = "1.0.0"; protected String packageName = "Org.OpenAPITools"; protected String packageTitle = "OpenAPI Library"; protected String packageProductName = "OpenAPILibrary"; protected String packageDescription = "A library generated from a OpenAPI doc"; protected String packageCompany = "OpenAPI"; protected String packageCopyright = "No Copyright"; protected String packageAuthors = "OpenAPI"; protected String interfacePrefix = "I"; protected String sourceFolder = "src"; // TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src. // This would require updating relative paths (e.g. path to main project file in test project file) protected String testFolder = sourceFolder; protected Set<String> collectionTypes; protected Set<String> mapTypes; // true if support nullable type protected boolean supportNullable = Boolean.FALSE; // nullable type protected Set<String> nullableType = new HashSet<String>(); private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCSharpCodegen.class); public AbstractCSharpCodegen() { super(); supportsInheritance = true; // C# does not use import mapping importMapping.clear(); outputFolder = "generated-code" + File.separator + this.getName(); embeddedTemplateDir = templateDir = this.getName(); collectionTypes = new HashSet<String>( Arrays.asList( "IList", "List", "ICollection", "Collection", "IEnumerable") ); mapTypes = new HashSet<String>( Arrays.asList("IDictionary") ); // NOTE: C# uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons. reservedWords.addAll( Arrays.asList( // set "client" as a reserved word to avoid conflicts with Org.OpenAPITools.Client // this is a workaround and can be removed if c# api client is updated to use // fully qualified name "Client", "client", "parameter", // local variable names in API methods (endpoints) "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", "localVarPostBody", "localVarHttpHeaderAccepts", "localVarHttpHeaderAccept", "localVarHttpContentTypes", "localVarHttpContentType", "localVarStatusCode", // C# reserved words "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while") ); // TODO: Either include fully qualified names here or handle in DefaultCodegen via lastIndexOf(".") search languageSpecificPrimitives = new HashSet<String>( Arrays.asList( "String", "string", "bool?", "bool", "double?", "double", "decimal?", "decimal", "int?", "int", "long?", "long", "float?", "float", "byte[]", "ICollection", "Collection", "List", "Dictionary", "DateTime?", "DateTime", "DateTimeOffset?", "DataTimeOffset", "Boolean", "Double", "Int32", "Int64", "Float", "Guid?", "System.IO.Stream", // not really a primitive, we include it to avoid model import "Object") ); instantiationTypes.put("array", "List"); instantiationTypes.put("list", "List"); instantiationTypes.put("map", "Dictionary"); // Nullable types here assume C# 2 support is not part of base typeMapping = new HashMap<String, String>(); typeMapping.put("string", "string"); typeMapping.put("binary", "byte[]"); typeMapping.put("ByteArray", "byte[]"); typeMapping.put("boolean", "bool?"); typeMapping.put("integer", "int?"); typeMapping.put("float", "float?"); typeMapping.put("long", "long?"); typeMapping.put("double", "double?"); typeMapping.put("number", "decimal?"); typeMapping.put("DateTime", "DateTime?"); typeMapping.put("date", "DateTime?"); typeMapping.put("file", "System.IO.Stream"); typeMapping.put("array", "List"); typeMapping.put("list", "List"); typeMapping.put("map", "Dictionary"); typeMapping.put("object", "Object"); typeMapping.put("UUID", "Guid?"); // nullable type nullableType = new HashSet<String>( Arrays.asList("decimal", "bool", "int", "float", "long", "double", "DateTime", "Guid") ); } public void setReturnICollection(boolean returnICollection) { this.returnICollection = returnICollection; } public void setUseCollection(boolean useCollection) { this.useCollection = useCollection; if (useCollection) { typeMapping.put("array", "Collection"); typeMapping.put("list", "Collection"); instantiationTypes.put("array", "Collection"); instantiationTypes.put("list", "Collection"); } } public void setOptionalMethodArgumentFlag(boolean flag) { this.optionalMethodArgumentFlag = flag; } public void setNetCoreProjectFileFlag(boolean flag) { this.netCoreProjectFileFlag = flag; } public void useDateTimeOffset(boolean flag) { this.useDateTimeOffsetFlag = flag; if (flag) { typeMapping.put("DateTime", "DateTimeOffset?"); } else { typeMapping.put("DateTime", "DateTime?"); } } @Override public void processOpts() { super.processOpts(); if (StringUtils.isEmpty(System.getenv("CSHARP_POST_PROCESS_FILE"))) { LOGGER.info("Environment variable CSHARP_POST_PROCESS_FILE not defined so the C# code may not be properly formatted by uncrustify (0.66 or later) or other code formatter. To define it, try `export CSHARP_POST_PROCESS_FILE=\"/usr/local/bin/uncrustify --no-backup\" && export UNCRUSTIFY_CONFIG=/path/to/uncrustify-rules.cfg` (Linux/Mac). Note: replace /path/to with the location of uncrustify-rules.cfg"); LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); } // License info if (additionalProperties.containsKey(CodegenConstants.LICENSE_URL)) { setLicenseUrl((String) additionalProperties.get(CodegenConstants.LICENSE_URL)); } else { additionalProperties.put(CodegenConstants.LICENSE_URL, this.licenseUrl); } if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) { setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME)); } else { additionalProperties.put(CodegenConstants.LICENSE_NAME, this.licenseName); } // {{packageVersion}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } // {{sourceFolder}} if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } else { additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder); } // {{packageName}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { LOGGER.warn(String.format(Locale.ROOT, "%s is not used by C# generators. Please use %s", CodegenConstants.INVOKER_PACKAGE, CodegenConstants.PACKAGE_NAME)); } // {{packageTitle}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_TITLE)) { setPackageTitle((String) additionalProperties.get(CodegenConstants.PACKAGE_TITLE)); } else { additionalProperties.put(CodegenConstants.PACKAGE_TITLE, packageTitle); } // {{packageProductName}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_PRODUCTNAME)) { setPackageProductName((String) additionalProperties.get(CodegenConstants.PACKAGE_PRODUCTNAME)); } else { additionalProperties.put(CodegenConstants.PACKAGE_PRODUCTNAME, packageProductName); } // {{packageDescription}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_DESCRIPTION)) { setPackageDescription((String) additionalProperties.get(CodegenConstants.PACKAGE_DESCRIPTION)); } else { additionalProperties.put(CodegenConstants.PACKAGE_DESCRIPTION, packageDescription); } // {{packageCompany}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COMPANY)) { setPackageCompany((String) additionalProperties.get(CodegenConstants.PACKAGE_COMPANY)); } else { additionalProperties.put(CodegenConstants.PACKAGE_COMPANY, packageCompany); } // {{packageCopyright}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COPYRIGHT)) { setPackageCopyright((String) additionalProperties.get(CodegenConstants.PACKAGE_COPYRIGHT)); } else { additionalProperties.put(CodegenConstants.PACKAGE_COPYRIGHT, packageCopyright); } // {{packageAuthors}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_AUTHORS)) { setPackageAuthors((String) additionalProperties.get(CodegenConstants.PACKAGE_AUTHORS)); } else { additionalProperties.put(CodegenConstants.PACKAGE_AUTHORS, packageAuthors); } // {{useDateTimeOffset}} if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) { useDateTimeOffset(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_DATETIME_OFFSET)); } else { additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); } if (additionalProperties.containsKey(CodegenConstants.USE_COLLECTION)) { setUseCollection(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_COLLECTION)); } else { additionalProperties.put(CodegenConstants.USE_COLLECTION, useCollection); } if (additionalProperties.containsKey(CodegenConstants.RETURN_ICOLLECTION)) { setReturnICollection(convertPropertyToBooleanAndWriteBack(CodegenConstants.RETURN_ICOLLECTION)); } else { additionalProperties.put(CodegenConstants.RETURN_ICOLLECTION, returnICollection); } if (additionalProperties.containsKey(CodegenConstants.NETCORE_PROJECT_FILE)) { setNetCoreProjectFileFlag(convertPropertyToBooleanAndWriteBack(CodegenConstants.NETCORE_PROJECT_FILE)); } else { additionalProperties.put(CodegenConstants.NETCORE_PROJECT_FILE, netCoreProjectFileFlag); } if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) { setInterfacePrefix(""); } else if (!"true".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) { // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix. setInterfacePrefix(sanitizeName(useInterfacePrefix)); } } // This either updates additionalProperties with the above fixes, or sets the default if the option was not specified. additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); addMustacheLambdas(additionalProperties); } private void addMustacheLambdas(Map<String, Object> objs) { Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>() .put("lowercase", new LowercaseLambda().generator(this)) .put("uppercase", new UppercaseLambda()) .put("titlecase", new TitlecaseLambda()) .put("camelcase", new CamelCaseLambda().generator(this)) .put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true)) .put("indented", new IndentedLambda()) .put("indented_8", new IndentedLambda(8, " ")) .put("indented_12", new IndentedLambda(12, " ")) .put("indented_16", new IndentedLambda(16, " ")) .build(); if (objs.containsKey("lambda")) { LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " + "You'll likely need to use a custom template, " + "see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. "); objs.put("_lambda", lambdas); } else { objs.put("lambda", lambdas); } } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); } @Override public Map<String, Object> postProcessModels(Map<String, Object> objs) { List<Object> models = (List<Object>) objs.get("models"); for (Object _mo : models) { Map<String, Object> mo = (Map<String, Object>) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); for (CodegenProperty var : cm.vars) { // check to see if model name is same as the property name // which will result in compilation error // if found, prepend with _ to workaround the limitation if (var.name.equalsIgnoreCase(cm.name)) { var.name = "_" + var.name; } } } // process enum in models return postProcessModelsEnum(objs); } /** * Invoked by {@link DefaultGenerator} after all models have been post-processed, allowing for a last pass of codegen-specific model cleanup. * * @param objs Current state of codegen object model. * @return An in-place modified state of the codegen object model. */ @Override public Map<String, Object> postProcessAllModels(Map<String, Object> objs) { final Map<String, Object> processed = super.postProcessAllModels(objs); postProcessEnumRefs(processed); return processed; } /** * C# differs from other languages in that Enums are not _true_ objects; enums are compiled to integral types. * So, in C#, an enum is considers more like a user-defined primitive. * <p> * When working with enums, we can't always assume a RefModel is a nullable type (where default(YourType) == null), * so this post processing runs through all models to find RefModel'd enums. Then, it runs through all vars and modifies * those vars referencing RefModel'd enums to work the same as inlined enums rather than as objects. * * @param models processed models to be further processed for enum references */ @SuppressWarnings({"unchecked"}) private void postProcessEnumRefs(final Map<String, Object> models) { Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>(); for (Map.Entry<String, Object> entry : models.entrySet()) { CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models); if (model.isEnum) { enumRefs.put(entry.getKey(), model); } } for (Map.Entry<String, Object> entry : models.entrySet()) { String openAPIName = entry.getKey(); CodegenModel model = ModelUtils.getModelByName(openAPIName, models); if (model != null) { for (CodegenProperty var : model.allVars) { if (enumRefs.containsKey(var.dataType)) { // Handle any enum properties referred to by $ref. // This is different in C# than most other generators, because enums in C# are compiled to integral types, // while enums in many other languages are true objects. CodegenModel refModel = enumRefs.get(var.dataType); var.allowableValues = refModel.allowableValues; var.isEnum = true; // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. var.isPrimitiveType = true; } } // We're looping all models here. if (model.isEnum) { // We now need to make allowableValues.enumVars look like the context of CodegenProperty Boolean isString = false; Boolean isInteger = false; Boolean isLong = false; Boolean isByte = false; if (model.dataType.startsWith("byte")) { // C# Actually supports byte and short enums, swagger spec only supports byte. isByte = true; model.vendorExtensions.put("x-enum-byte", true); } else if (model.dataType.startsWith("int32")) { isInteger = true; model.vendorExtensions.put("x-enum-integer", true); } else if (model.dataType.startsWith("int64")) { isLong = true; model.vendorExtensions.put("x-enum-long", true); } else { // C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity) isString = true; model.vendorExtensions.put("x-enum-string", true); } // Since we iterate enumVars for modelnnerEnum and enumClass templates, and CodegenModel is missing some of CodegenProperty's properties, // we can take advantage of Mustache's contextual lookup to add the same "properties" to the model's enumVars scope rather than CodegenProperty's scope. List<Map<String, String>> enumVars = (ArrayList<Map<String, String>>) model.allowableValues.get("enumVars"); List<Map<String, Object>> newEnumVars = new ArrayList<Map<String, Object>>(); for (Map<String, String> enumVar : enumVars) { Map<String, Object> mixedVars = new HashMap<String, Object>(); mixedVars.putAll(enumVar); mixedVars.put("isString", isString); mixedVars.put("isLong", isLong); mixedVars.put("isInteger", isInteger); mixedVars.put("isByte", isByte); newEnumVars.add(mixedVars); } if (!newEnumVars.isEmpty()) { model.allowableValues.put("enumVars", newEnumVars); } } } else { LOGGER.warn("Expected to retrieve model %s by name, but no model was found. Check your -Dmodels inclusions.", openAPIName); } } } /** * Update codegen property's enum by adding "enumVars" (with name and value) * * @param var list of CodegenProperty */ @Override public void updateCodegenPropertyEnum(CodegenProperty var) { if (var.vendorExtensions == null) { var.vendorExtensions = new HashMap<>(); } super.updateCodegenPropertyEnum(var); // Because C# uses nullable primitives for datatype, and datatype is used in DefaultCodegen for determining enum-ness, guard against weirdness here. if (var.isEnum) { if ("byte".equals(var.dataFormat)) {// C# Actually supports byte and short enums. var.vendorExtensions.put("x-enum-byte", true); var.isString = false; var.isLong = false; var.isInteger = false; } else if ("int32".equals(var.dataFormat)) { var.isInteger = true; var.isString = false; var.isLong = false; } else if ("int64".equals(var.dataFormat)) { var.isLong = true; var.isString = false; var.isInteger = false; } else {// C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity) var.isString = true; var.isInteger = false; var.isLong = false; } } } @Override public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) { super.postProcessOperationsWithModels(objs, allModels); if (objs != null) { Map<String, Object> operations = (Map<String, Object>) objs.get("operations"); if (operations != null) { List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); for (CodegenOperation operation : ops) { // Check return types for collection if (operation.returnType != null) { String typeMapping; int namespaceEnd = operation.returnType.lastIndexOf("."); if (namespaceEnd > 0) { typeMapping = operation.returnType.substring(namespaceEnd); } else { typeMapping = operation.returnType; } if (this.collectionTypes.contains(typeMapping)) { operation.isListContainer = true; operation.returnContainer = operation.returnType; if (this.returnICollection && ( typeMapping.startsWith("List") || typeMapping.startsWith("Collection"))) { // NOTE: ICollection works for both List<T> and Collection<T> int genericStart = typeMapping.indexOf("<"); if (genericStart > 0) { operation.returnType = "ICollection" + typeMapping.substring(genericStart); } } } else { operation.returnContainer = operation.returnType; operation.isMapContainer = this.mapTypes.contains(typeMapping); } } if (operation.examples != null) { for (Map<String, String> example : operation.examples) { for (Map.Entry<String, String> entry : example.entrySet()) { // Replace " with \", \r, \n with \\r, \\n String val = entry.getValue().replace("\"", "\\\"") .replace("\r", "\\r") .replace("\n", "\\n"); entry.setValue(val); } } } if (!isSupportNullable()) { for (CodegenParameter parameter : operation.allParams) { CodegenModel model = null; for (Object modelHashMap : allModels) { CodegenModel codegenModel = ((HashMap<String, CodegenModel>) modelHashMap).get("model"); if (codegenModel.getClassname().equals(parameter.dataType)) { model = codegenModel; break; } } if (model == null) { // Primitive data types all come already marked parameter.isNullable = true; } else { // Effectively mark enum models as enums and non-nullable if (model.isEnum) { parameter.isEnum = true; parameter.allowableValues = model.allowableValues; parameter.isPrimitiveType = true; parameter.isNullable = false; } else { parameter.isNullable = true; } } } } processOperation(operation); } } } return objs; } protected void processOperation(CodegenOperation operation) { // default noop } @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + apiPackage(); } @Override public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + modelPackage(); } @Override public String toModelFilename(String name) { // should be the same as the model name return toModelName(name); } @Override public String toOperationId(String operationId) { // throw exception if method name is empty (should not occur as an auto-generated method name will be used) if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method name (operationId) not allowed"); } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } return camelize(sanitizeName(operationId)); } @Override public String toVarName(String name) { // sanitize name name = sanitizeName(name); // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; } // camelize the variable name // pet_id => PetId name = camelize(name); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } return name; } @Override public String toParamName(String name) { // sanitize name name = sanitizeName(name); // replace - with _ e.g. created-at => created_at name = name.replaceAll("-", "_"); // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; } // camelize(lower) the variable name // pet_id => petId name = camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } return name; } @Override public String escapeReservedWord(String name) { if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } /** * Return the example value of the property * * @param p OpenAPI property object * @return string presentation of the example value of the property */ @Override public String toExampleValue(Schema p) { if (ModelUtils.isStringSchema(p)) { if (p.getExample() != null) { return "\"" + p.getExample().toString() + "\""; } } else if (ModelUtils.isBooleanSchema(p)) { if (p.getExample() != null) { return p.getExample().toString(); } } else if (ModelUtils.isDateSchema(p)) { // TODO } else if (ModelUtils.isDateTimeSchema(p)) { // TODO } else if (ModelUtils.isNumberSchema(p)) { if (p.getExample() != null) { return p.getExample().toString(); } } else if (ModelUtils.isIntegerSchema(p)) { if (p.getExample() != null) { return p.getExample().toString(); } } return null; } /** * Return the default value of the property * @param p OpenAPI property object * @return string presentation of the default value of the property */ @Override public String toDefaultValue(Schema p) { if (ModelUtils.isBooleanSchema(p)) { if (p.getDefault() != null) { return p.getDefault().toString(); } } else if (ModelUtils.isDateSchema(p)) { if (p.getDefault() != null) { return "\"" + p.getDefault().toString() + "\""; } } else if (ModelUtils.isDateTimeSchema(p)) { if (p.getDefault() != null) { return "\"" + p.getDefault().toString() + "\""; } } else if (ModelUtils.isNumberSchema(p)) { if (p.getDefault() != null) { if (ModelUtils.isFloatSchema(p)) { // float return p.getDefault().toString() + "F"; } else if (ModelUtils.isDoubleSchema(p)) { // double return p.getDefault().toString() + "D"; } else { // decimal return p.getDefault().toString() + "M"; } } } else if (ModelUtils.isIntegerSchema(p)) { if (p.getDefault() != null) { return p.getDefault().toString(); } } else if (ModelUtils.isStringSchema(p)) { if (p.getDefault() != null) { String _default = (String) p.getDefault(); if (p.getEnum() == null) { return "\"" + _default + "\""; } else { // convert to enum var name later in postProcessModels return _default; } } } return null; } @Override protected boolean isReservedWord(String word) { // NOTE: This differs from super's implementation in that C# does _not_ want case insensitive matching. return reservedWords.contains(word); } public String getNullableType(Schema p, String type) { if (languageSpecificPrimitives.contains(type)) { return type; } else { return null; } } @Override public String getSchemaType(Schema p) { String openAPIType = super.getSchemaType(p); String type; if (openAPIType == null) { LOGGER.error("OpenAPI Type for {} is null. Default to UNKNOWN_OPENAPI_TYPE instead.", p.getName()); openAPIType = "UNKNOWN_OPENAPI_TYPE"; } if (typeMapping.containsKey(openAPIType)) { type = typeMapping.get(openAPIType); String languageType = getNullableType(p, type); if (languageType != null) { return languageType; } } else { type = openAPIType; } return toModelName(type); } /** * Provides C# strongly typed declaration for simple arrays of some type and arrays of arrays of some type. * * @param arr The input array property * @return The type declaration when the type is an array of arrays. */ private String getArrayTypeDeclaration(ArraySchema arr) { // TODO: collection type here should be fully qualified namespace to avoid model conflicts // This supports arrays of arrays. String arrayType = typeMapping.get("array"); StringBuilder instantiationType = new StringBuilder(arrayType); Schema items = arr.getItems(); String nestedType = getTypeDeclaration(items); // TODO: We may want to differentiate here between generics and primitive arrays. instantiationType.append("<").append(nestedType).append(">"); return instantiationType.toString(); } @Override public String toInstantiationType(Schema p) { if (ModelUtils.isArraySchema(p)) { return getArrayTypeDeclaration((ArraySchema) p); } return super.toInstantiationType(p); } @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isArraySchema(p)) { return getArrayTypeDeclaration((ArraySchema) p); } else if (ModelUtils.isMapSchema(p)) { // Should we also support maps of maps? Schema inner = ModelUtils.getAdditionalProperties(p); return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">"; } return super.getTypeDeclaration(p); } @Override public String toModelName(String name) { // We need to check if import-mapping has a different model for this class, so we use it // instead of the auto-generated one. if (importMapping.containsKey(name)) { return importMapping.get(name); } if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; } if (!StringUtils.isEmpty(modelNameSuffix)) { name = name + "_" + modelNameSuffix; } name = sanitizeName(name); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } // camelize the model name // phone_number => PhoneNumber return camelize(name); } @Override public String apiTestFileFolder() { return outputFolder + ".Test"; } @Override public String modelTestFileFolder() { return outputFolder + ".Test"; } @Override public String toApiTestFilename(String name) { return toApiName(name) + "Tests"; } @Override public String toModelTestFilename(String name) { return toModelName(name) + "Tests"; } public void setLicenseUrl(String licenseUrl) {this.licenseUrl = licenseUrl;} public void setLicenseName(String licenseName) {this.licenseName = licenseName;} public void setPackageName(String packageName) { this.packageName = packageName; } public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } public void setPackageTitle(String packageTitle) { this.packageTitle = packageTitle; } public void setPackageProductName(String packageProductName) { this.packageProductName = packageProductName; } public void setPackageDescription(String packageDescription) { this.packageDescription = packageDescription; } public void setPackageCompany(String packageCompany) { this.packageCompany = packageCompany; } public void setPackageCopyright(String packageCopyright) { this.packageCopyright = packageCopyright; } public void setPackageAuthors(String packageAuthors) { this.packageAuthors = packageAuthors; } public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } public String getInterfacePrefix() { return interfacePrefix; } public void setInterfacePrefix(final String interfacePrefix) { this.interfacePrefix = interfacePrefix; } public boolean isSupportNullable() { return supportNullable; } public void setSupportNullable(final boolean supportNullable) { this.supportNullable = supportNullable; } @Override public String toEnumValue(String value, String datatype) { // C# only supports enums as literals for int, int?, long, long?, byte, and byte?. All else must be treated as strings. // Per: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. // but we're not supporting unsigned integral types or shorts. if (datatype.startsWith("int") || datatype.startsWith("long") || datatype.startsWith("byte")) { return value; } return escapeText(value); } @Override public String toEnumVarName(String name, String datatype) { if (name.length() == 0) { return "Empty"; } // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(getSymbolName(name)); } String enumName = sanitizeName(name); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); enumName = camelize(enumName) + "Enum"; if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { return enumName; } } @Override public String toEnumName(CodegenProperty property) { return sanitizeName(camelize(property.name)) + "Enum"; } public String testPackageName() { return this.packageName + ".Test"; } @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } @Override public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*").replace("--", "- -"); } @Override public boolean isDataTypeString(String dataType) { // also treat double/decimal/float as "string" in enum so that the values (e.g. 2.8) get double-quoted return "String".equalsIgnoreCase(dataType) || "double?".equals(dataType) || "decimal?".equals(dataType) || "float?".equals(dataType) || "double".equals(dataType) || "decimal".equals(dataType) || "float".equals(dataType); } @Override public void setParameterExampleValue(CodegenParameter codegenParameter) { // set the example value // if not specified in x-example, generate a default value // TODO need to revise how to obtain the example value if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); } else if (Boolean.TRUE.equals(codegenParameter.isBoolean)) { codegenParameter.example = "true"; } else if (Boolean.TRUE.equals(codegenParameter.isLong)) { codegenParameter.example = "789"; } else if (Boolean.TRUE.equals(codegenParameter.isInteger)) { codegenParameter.example = "56"; } else if (Boolean.TRUE.equals(codegenParameter.isFloat)) { codegenParameter.example = "3.4F"; } else if (Boolean.TRUE.equals(codegenParameter.isDouble)) { codegenParameter.example = "1.2D"; } else if (Boolean.TRUE.equals(codegenParameter.isNumber)) { codegenParameter.example = "8.14"; } else if (Boolean.TRUE.equals(codegenParameter.isBinary)) { codegenParameter.example = "BINARY_DATA_HERE"; } else if (Boolean.TRUE.equals(codegenParameter.isByteArray)) { codegenParameter.example = "BYTE_ARRAY_DATA_HERE"; } else if (Boolean.TRUE.equals(codegenParameter.isFile)) { codegenParameter.example = "/path/to/file.txt"; } else if (Boolean.TRUE.equals(codegenParameter.isDate)) { codegenParameter.example = "2013-10-20"; } else if (Boolean.TRUE.equals(codegenParameter.isDateTime)) { codegenParameter.example = "2013-10-20T19:20:30+01:00"; } else if (Boolean.TRUE.equals(codegenParameter.isUuid)) { codegenParameter.example = "38400000-8cf0-11bd-b23e-10b96e4ef00d"; } else if (Boolean.TRUE.equals(codegenParameter.isString)) { codegenParameter.example = codegenParameter.paramName + "_example"; } } @Override public void postProcessFile(File file, String fileType) { if (file == null) { return; } String csharpPostProcessFile = System.getenv("CSHARP_POST_PROCESS_FILE"); if (StringUtils.isEmpty(csharpPostProcessFile)) { return; // skip if CSHARP_POST_PROCESS_FILE env variable is not defined } // only process files with .cs extension if ("cs".equals(FilenameUtils.getExtension(file.toString()))) { String command = csharpPostProcessFile + " " + file.toString(); try { Process p = Runtime.getRuntime().exec(command); int exitValue = p.waitFor(); if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { LOGGER.info("Successfully executed: " + command); } } catch (Exception e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); } } } }
[ "\"CSHARP_POST_PROCESS_FILE\"", "\"CSHARP_POST_PROCESS_FILE\"" ]
[]
[ "CSHARP_POST_PROCESS_FILE" ]
[]
["CSHARP_POST_PROCESS_FILE"]
java
1
0
service/modules/accela.py
"""Functions related to interacting with Accela.""" import os import json import requests import sentry_sdk from ..modules.util import timer # pylint: disable=too-few-public-methods class Accela(): """Functions related to interacting with Accela.""" @staticmethod @timer def send_email_to_accela(record_id, emails): """ Send record to Accela """ url = os.environ.get('ACCELA_MS_BASE_URL') + '/records/' + record_id + '/comments' headers = { 'X-SFDS-APIKEY': os.environ.get('ACCELA_MS_APIKEY'), 'X-ACCELA-ENV': os.environ.get('ACCELA_ENV'), 'X-ACCELA-USERNAME': os.environ.get('ACCELA_USERNAME') } params = {} data = json.dumps(emails) response = requests.put(url, headers=headers, data=data, params=params) with sentry_sdk.configure_scope() as scope: scope.set_extra('accela_re_emails_status_code', response.status_code) scope.set_extra('accela_re_emails_json', response.json()) return response @staticmethod @timer def send_record_to_accela(record_json): """ Send record to Accela """ url = os.environ.get('ACCELA_MS_BASE_URL') + '/records' headers = { 'X-SFDS-APIKEY': os.environ.get('ACCELA_MS_APIKEY'), 'X-ACCELA-ENV': os.environ.get('ACCELA_ENV'), 'X-ACCELA-USERNAME': os.environ.get('ACCELA_USERNAME') } params = {} data = json.dumps(record_json) response = requests.post(url, headers=headers, data=data, params=params) return response
[]
[]
[ "ACCELA_USERNAME", "ACCELA_ENV", "ACCELA_MS_APIKEY", "ACCELA_MS_BASE_URL" ]
[]
["ACCELA_USERNAME", "ACCELA_ENV", "ACCELA_MS_APIKEY", "ACCELA_MS_BASE_URL"]
python
4
0
config.go
package appy import ( "encoding/hex" "fmt" "io/ioutil" "net/http" "os" "strings" "time" "github.com/joho/godotenv" ) type ( // Config defines the application settings. Config struct { AppyEnv string `env:"APPY_ENV" envDefault:"development"` AssetHost string `env:"ASSET_HOST" envDefault:""` // GraphQL related configuration. GQLPlaygroundEnabled bool `env:"GQL_PLAYGROUND_ENABLED" envDefault:"false"` GQLPlaygroundPath string `env:"GQL_PLAYGROUND_PATH" envDefault:"/docs/graphql"` GQLAPQCacheSize int `env:"GQL_APQ_CACHE_SIZE" envDefault:"100"` GQLQueryCacheSize int `env:"GQL_QUERY_CACHE_SIZE" envDefault:"1000"` GQLComplexityLimit int `env:"GQL_COMPLEXITY_LIMIT" envDefault:"100"` GQLMultipartMaxMemory int64 `env:"GQL_MULTIPART_MAX_MEMORY" envDefault:"0"` GQLMultipartMaxUploadSize int64 `env:"GQL_MULTIPART_MAX_UPLOAD_SIZE" envDefault:"0"` GQLWebsocketKeepAliveDuration time.Duration `env:"GQL_WEBSOCKET_KEEP_ALIVE_DURATION" envDefault:"10s"` // Server related configuration. HTTPDebugEnabled bool `env:"HTTP_DEBUG_ENABLED" envDefault:"false"` HTTPGzipCompressLevel int `env:"HTTP_GZIP_COMPRESS_LEVEL" envDefault:"-1"` HTTPGzipExcludedExts []string `env:"HTTP_GZIP_EXCLUDED_EXTS" envDefault:""` HTTPGzipExcludedPaths []string `env:"HTTP_GZIP_EXCLUDED_PATHS" envDefault:""` HTTPLogFilterParameters []string `env:"HTTP_LOG_FILTER_PARAMETERS" envDefault:"password"` HTTPHealthCheckURL string `env:"HTTP_HEALTH_CHECK_URL" envDefault:"/health_check"` HTTPHost string `env:"HTTP_HOST" envDefault:"localhost"` HTTPPort string `env:"HTTP_PORT" envDefault:"3000"` HTTPGracefulTimeout time.Duration `env:"HTTP_GRACEFUL_TIMEOUT" envDefault:"30s"` HTTPIdleTimeout time.Duration `env:"HTTP_IDLE_TIMEOUT" envDefault:"75s"` HTTPMaxHeaderBytes int `env:"HTTP_MAX_HEADER_BYTES" envDefault:"0"` HTTPReadTimeout time.Duration `env:"HTTP_READ_TIMEOUT" envDefault:"60s"` HTTPReadHeaderTimeout time.Duration `env:"HTTP_READ_HEADER_TIMEOUT" envDefault:"60s"` HTTPWriteTimeout time.Duration `env:"HTTP_WRITE_TIMEOUT" envDefault:"60s"` HTTPSSLCertPath string `env:"HTTP_SSL_CERT_PATH" envDefault:"./tmp/ssl"` HTTPSSLEnabled bool `env:"HTTP_SSL_ENABLED" envDefault:"false"` HTTPSSLPort string `env:"HTTP_SSL_PORT" envDefault:"3443"` // Session related configuration using redis pool. HTTPSessionRedisAddr string `env:"HTTP_SESSION_REDIS_ADDR" envDefault:"localhost:6379"` HTTPSessionRedisAuth string `env:"HTTP_SESSION_REDIS_AUTH" envDefault:""` HTTPSessionRedisDb string `env:"HTTP_SESSION_REDIS_DB" envDefault:"0"` HTTPSessionRedisMaxActive int `env:"HTTP_SESSION_REDIS_MAX_ACTIVE" envDefault:"64"` HTTPSessionRedisMaxIdle int `env:"HTTP_SESSION_REDIS_MAX_IDLE" envDefault:"32"` HTTPSessionRedisIdleTimeout time.Duration `env:"HTTP_SESSION_REDIS_IDLE_TIMEOUT" envDefault:"30s"` HTTPSessionRedisMaxConnLifetime time.Duration `env:"HTTP_SESSION_REDIS_MAX_CONN_LIFETIME" envDefault:"30s"` HTTPSessionRedisWait bool `env:"HTTP_SESSION_REDIS_WAIT" envDefault:"true"` // Session related configuration. HTTPSessionName string `env:"HTTP_SESSION_NAME" envDefault:"_session"` HTTPSessionProvider string `env:"HTTP_SESSION_PROVIDER" envDefault:"cookie"` HTTPSessionExpiration int `env:"HTTP_SESSION_EXPIRATION" envDefault:"1209600"` HTTPSessionDomain string `env:"HTTP_SESSION_DOMAIN" envDefault:"localhost"` HTTPSessionHTTPOnly bool `env:"HTTP_SESSION_HTTP_ONLY" envDefault:"true"` HTTPSessionPath string `env:"HTTP_SESSION_PATH" envDefault:"/"` HTTPSessionSameSite http.SameSite `env:"HTTP_SESSION_SAME_SITE" envDefault:"1"` HTTPSessionSecure bool `env:"HTTP_SESSION_SECURE" envDefault:"false"` HTTPSessionSecrets [][]byte `env:"HTTP_SESSION_SECRETS,required" envDefault:""` // Security related configuration. HTTPAllowedHosts []string `env:"HTTP_ALLOWED_HOSTS" envDefault:""` HTTPCSRFCookieDomain string `env:"HTTP_CSRF_COOKIE_DOMAIN" envDefault:"localhost"` HTTPCSRFCookieHTTPOnly bool `env:"HTTP_CSRF_COOKIE_HTTP_ONLY" envDefault:"true"` HTTPCSRFCookieMaxAge int `env:"HTTP_CSRF_COOKIE_MAX_AGE" envDefault:"0"` HTTPCSRFCookieName string `env:"HTTP_CSRF_COOKIE_NAME" envDefault:"_csrf_token"` HTTPCSRFCookiePath string `env:"HTTP_CSRF_COOKIE_PATH" envDefault:"/"` HTTPCSRFCookieSameSite http.SameSite `env:"HTTP_CSRF_COOKIE_SAME_SITE" envDefault:"1"` HTTPCSRFCookieSecure bool `env:"HTTP_CSRF_COOKIE_SECURE" envDefault:"false"` HTTPCSRFFieldName string `env:"HTTP_CSRF_FIELD_NAME" envDefault:"authenticity_token"` HTTPCSRFRequestHeader string `env:"HTTP_CSRF_REQUEST_HEADER" envDefault:"X-CSRF-Token"` HTTPCSRFSecret []byte `env:"HTTP_CSRF_SECRET,required" envDefault:""` HTTPSSLRedirect bool `env:"HTTP_SSL_REDIRECT" envDefault:"false"` HTTPSSLTemporaryRedirect bool `env:"HTTP_SSL_TEMPORARY_REDIRECT" envDefault:"false"` HTTPSSLHost string `env:"HTTP_SSL_HOST" envDefault:""` HTTPSTSSeconds int64 `env:"HTTP_STS_SECONDS" envDefault:"0"` HTTPSTSIncludeSubdomains bool `env:"HTTP_STS_INCLUDE_SUBDOMAINS" envDefault:"false"` HTTPFrameDeny bool `env:"HTTP_FRAME_DENY" envDefault:"false"` HTTPCustomFrameOptionsValue string `env:"HTTP_CUSTOM_FRAME_OPTIONS_VALUE" envDefault:""` HTTPContentTypeNosniff bool `env:"HTTP_CONTENT_TYPE_NOSNIFF" envDefault:"false"` HTTPBrowserXSSFilter bool `env:"HTTP_BROWSER_XSS_FILTER" envDefault:"false"` HTTPContentSecurityPolicy string `env:"HTTP_CONTENT_SECURITY_POLICY" envDefault:""` HTTPReferrerPolicy string `env:"HTTP_REFERRER_POLICY" envDefault:""` HTTPIENoOpen bool `env:"HTTP_IE_NO_OPEN" envDefault:"false"` HTTPSSLProxyHeaders map[string]string `env:"HTTP_SSL_PROXY_HEADERS" envDefault:"X-Forwarded-Proto:https"` // I18n related configuration. I18nDefaultLocale string `env:"I18N_DEFAULT_LOCALE" envDefault:"en"` // Mailer related configuration. MailerSMTPAddr string `env:"MAILER_SMTP_ADDR" envDefault:""` MailerSMTPPlainAuthIdentity string `env:"MAILER_SMTP_PLAIN_AUTH_IDENTITY" envDefault:""` MailerSMTPPlainAuthUsername string `env:"MAILER_SMTP_PLAIN_AUTH_USERNAME" envDefault:""` MailerSMTPPlainAuthPassword string `env:"MAILER_SMTP_PLAIN_AUTH_PASSWORD" envDefault:""` MailerSMTPPlainAuthHost string `env:"MAILER_SMTP_PLAIN_AUTH_HOST" envDefault:""` MailerPreviewBaseURL string `env:"MAILER_PREVIEW_BASE_URL" envDefault:"/appy/mailers"` path string errors []error masterKey []byte } ) // NewConfig initializes Config instance. func NewConfig(asset *Asset, logger *Logger, support Supporter) *Config { var errs []error masterKey, err := parseMasterKey(asset) if err != nil { errs = append(errs, err) } config := &Config{} if masterKey != nil { config.path = asset.Layout()["config"] + "/.env." + os.Getenv("APPY_ENV") config.masterKey = masterKey decryptErrs := config.decryptConfig(asset, masterKey, support) if len(decryptErrs) > 0 { errs = append(errs, decryptErrs...) } err = support.ParseEnv(config) if err != nil { errs = append(errs, err) } } if len(errs) > 0 { config.errors = errs } return config } // MasterKey returns the master key for the current environment. func (c *Config) MasterKey() []byte { return c.masterKey } // Errors returns all the config retrieving/parsing errors. func (c *Config) Errors() []error { return c.errors } // Path returns the config path. func (c *Config) Path() string { return c.path } // IsProtectedEnv is used to protect the app from being destroyed by a command accidentally. func (c *Config) IsProtectedEnv() bool { return c.AppyEnv == "production" } func (c Config) decryptConfig(asset *Asset, masterKey []byte, support Supporter) []error { reader, err := asset.Open(c.path) if err != nil { return []error{err} } envMap, err := godotenv.Parse(reader) if err != nil { os.Clearenv() return []error{err} } // Parse the environment variables that aren't defined in the config .env file which can be used to override the ones // defined in config .env file. origEnvMap := map[string]bool{} origEnv := os.Environ() for _, rawEnvLine := range origEnv { key := strings.Split(rawEnvLine, "=")[0] origEnvMap[key] = true } var errs []error if len(masterKey) != 0 { for key, value := range envMap { if origEnvMap[key] || value == "" { continue } decodeStr, _ := hex.DecodeString(value) plaintext, err := support.AESDecrypt(decodeStr, masterKey) if len(plaintext) < 1 || err != nil { errs = append(errs, fmt.Errorf("unable to decrypt '%s' value in '%s'", key, c.path)) } os.Setenv(key, string(plaintext)) } } return errs } func parseMasterKey(asset *Asset) ([]byte, error) { var ( err error key []byte ) env := "development" if os.Getenv("APPY_ENV") != "" { env = os.Getenv("APPY_ENV") } if os.Getenv("APPY_MASTER_KEY") != "" { key = []byte(os.Getenv("APPY_MASTER_KEY")) } if len(key) == 0 && IsDebugBuild() { key, err = ioutil.ReadFile(asset.Layout()["config"] + "/" + env + ".key") if err != nil { return nil, ErrReadMasterKeyFile } } key = []byte(strings.Trim(string(key), "\n")) key = []byte(strings.Trim(string(key), " ")) if len(key) == 0 { return nil, ErrMissingMasterKey } return key, nil }
[ "\"APPY_ENV\"", "\"APPY_ENV\"", "\"APPY_ENV\"", "\"APPY_MASTER_KEY\"", "\"APPY_MASTER_KEY\"" ]
[]
[ "APPY_MASTER_KEY", "APPY_ENV" ]
[]
["APPY_MASTER_KEY", "APPY_ENV"]
go
2
0